Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qqmlpropertyvalidator.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant
4
7
8#include <private/qqmlcustomparser_p.h>
9#include <private/qqmlglobal_p.h>
10#include <private/qqmlirbuilder_p.h>
11#include <private/qqmlpropertycachecreator_p.h>
12#include <private/qqmlpropertyresolver_p.h>
13#include <private/qqmlstringconverters_p.h>
14#include <private/qqmlsignalnames_p.h>
15
16#include <QtCore/qdatetime.h>
17
19
20static bool isPrimitiveType(QMetaType metaType)
21{
22 switch (metaType.id()) {
23#define HANDLE_PRIMITIVE(Type, id, T)
24 case QMetaType::Type:
25QT_FOR_EACH_STATIC_PRIMITIVE_TYPE(HANDLE_PRIMITIVE);
26#undef HANDLE_PRIMITIVE
27 return true;
28 default:
29 return false;
30 }
31}
32
33QQmlPropertyValidator::QQmlPropertyValidator(
34 QQmlTypeLoader *typeLoader, const QQmlImports *imports,
35 const QQmlRefPointer<QV4::CompiledData::CompilationUnit> &compilationUnit)
36 : m_typeLoader(typeLoader)
37 , compilationUnit(compilationUnit)
38 , imports(imports)
39 , qmlUnit(compilationUnit->unitData())
40 , propertyCaches(compilationUnit->propertyCaches)
41 , bindingPropertyDataPerObject(&compilationUnit->bindingPropertyDataPerObject)
42{
43 bindingPropertyDataPerObject->resize(compilationUnit->objectCount());
44}
45
46QList<QQmlError> QQmlPropertyValidator::validate()
47{
48 return validateObject(/*root object*/0, /*instantiatingBinding*/nullptr);
49}
50
52
54{
55 bool operator()(quint32 name, const QV4::CompiledData::Binding *binding) const
56 {
57 return name < binding->propertyNameIndex;
58 }
59 bool operator()(const QV4::CompiledData::Binding *binding, quint32 name) const
60 {
61 return binding->propertyNameIndex < name;
62 }
63 bool operator()(const QV4::CompiledData::Binding *lhs, const QV4::CompiledData::Binding *rhs) const
64 {
65 return lhs->propertyNameIndex < rhs->propertyNameIndex;
66 }
67};
68
69QList<QQmlError> QQmlPropertyValidator::validateObject(
70 int objectIndex, const QV4::CompiledData::Binding *instantiatingBinding,
71 bool populatingValueTypeGroupedProperty,
72 QQmlPropertyResolver::RevisionCheck checkRevision) const
73{
74 // Implicit component wrappers (>= objectCount) have no CU object.
75 // Validate the child object instead.
76 if (objectIndex >= compilationUnit->objectCount()) {
77 return validateObject(
78 compilationUnit->resolvedIndex(objectIndex), instantiatingBinding,
79 populatingValueTypeGroupedProperty, checkRevision);
80 }
81
82 const QV4::CompiledData::Object *obj = compilationUnit->objectAt(objectIndex);
83 for (auto it = obj->inlineComponentsBegin(); it != obj->inlineComponentsEnd(); ++it) {
84 const auto errors = validateObject(it->objectIndex, /* instantiatingBinding*/ nullptr);
85 if (!errors.isEmpty())
86 return errors;
87 }
88
89 if (compilationUnit->objectIsComponent(objectIndex)
90 && !obj->hasFlag(QV4::CompiledData::Object::IsInlineComponentRoot)) {
91 Q_ASSERT(obj->nBindings == 1);
92 const QV4::CompiledData::Binding *componentBinding = obj->bindingTable();
93 Q_ASSERT(componentBinding->type() == QV4::CompiledData::Binding::Type_Object);
94 return validateObject(componentBinding->value.objectIndex, componentBinding);
95 }
96
97 QQmlPropertyCache::ConstPtr propertyCache = propertyCaches.at(objectIndex);
98 if (!propertyCache)
99 return QList<QQmlError>();
100
101 QQmlCustomParser *customParser = nullptr;
102 if (auto typeRef = resolvedType(obj->inheritedTypeNameIndex)) {
103
104 // This binding instantiates a separate object. The separate object can have an ID and its
105 // own grouped properties even if it's then assigned to a value type, for example a 'var', or
106 // anything with an invokable ctor taking a QObject*.
107 populatingValueTypeGroupedProperty = false;
108
109 const auto type = typeRef->type();
110 if (type.isValid())
111 customParser = type.customParser();
112 }
113
114 QList<const QV4::CompiledData::Binding*> customBindings;
115
116 // Collect grouped properties first for sanity checking
117 // vector values are sorted by property name string index.
118 GroupedPropertyVector groupedProperties;
119 const QV4::CompiledData::Binding *binding = obj->bindingTable();
120 for (quint32 i = 0; i < obj->nBindings; ++i, ++binding) {
121 if (!binding->isGroupedProperty())
122 continue;
123
124 if (binding->hasFlag(QV4::CompiledData::Binding::IsOnAssignment))
125 continue;
126
127 if (populatingValueTypeGroupedProperty) {
128 return recordError(binding->location, tr("Property assignment expected"));
129 }
130
131 GroupedPropertyVector::const_iterator pos = std::lower_bound(groupedProperties.constBegin(), groupedProperties.constEnd(), binding->propertyNameIndex, BindingFinder());
132 groupedProperties.insert(pos, binding);
133 }
134
135 QQmlPropertyResolver propertyResolver(propertyCache);
136
137 QString defaultPropertyName;
138 const QQmlPropertyData *defaultProperty = nullptr;
139 if (obj->indexOfDefaultPropertyOrAlias != -1) {
140 const QQmlPropertyCache *cache = propertyCache->parent().data();
141 defaultPropertyName = cache->defaultPropertyName();
142 defaultProperty = cache->defaultProperty();
143 } else {
144 defaultPropertyName = propertyCache->defaultPropertyName();
145 defaultProperty = propertyCache->defaultProperty();
146 }
147
148 QV4::CompiledData::BindingPropertyData collectedBindingPropertyData(obj->nBindings);
149
150 binding = obj->bindingTable();
151 for (quint32 i = 0; i < obj->nBindings; ++i, ++binding) {
152 QString name = stringAt(binding->propertyNameIndex);
153 const QV4::CompiledData::Binding::Type bindingType = binding->type();
154 const QV4::CompiledData::Binding::Flags bindingFlags = binding->flags();
155
156 if (customParser) {
157 if (bindingType == QV4::CompiledData::Binding::Type_AttachedProperty) {
158 if (customParser->flags() & QQmlCustomParser::AcceptsAttachedProperties) {
159 customBindings << binding;
160 continue;
161 }
162 } else if (QQmlSignalNames::isHandlerName(name)
163 && !(customParser->flags() & QQmlCustomParser::AcceptsSignalHandlers)) {
164 customBindings << binding;
165 continue;
166 }
167 }
168
169 bool bindingToDefaultProperty = false;
170 bool isGroupedProperty = instantiatingBinding
171 && instantiatingBinding->type() == QV4::CompiledData::Binding::Type_GroupedProperty;
172
173 bool notInRevision = false;
174 const QQmlPropertyData *pd = nullptr;
175 if (!name.isEmpty()) {
176 if (compilationUnit->bindingIsSignalHandlerExpression(objectIndex, i)
177 || compilationUnit->bindingIsSignalHandlerObject(objectIndex, i)) {
178 pd = propertyResolver.signal(
179 *QQmlSignalNames::anyHandlerNameToSignalName(name), &notInRevision,
180 checkRevision);
181 } else if (compilationUnit->bindingIsPropertyObserver(objectIndex, i)) {
182 pd = propertyResolver.property(
183 *QQmlSignalNames::changedHandlerNameToPropertyName(name), &notInRevision,
184 checkRevision);
185 } else {
186 pd = propertyResolver.property(name, &notInRevision, checkRevision);
187 }
188
189 if (notInRevision) {
190 QString typeName = stringAt(obj->inheritedTypeNameIndex);
191 if (auto *objectType = resolvedType(obj->inheritedTypeNameIndex)) {
192 const auto type = objectType->type();
193 if (type.isValid()) {
194 const auto version = objectType->version();
195 return recordError(binding->location,
196 tr("\"%1.%2\" is not available in %3 %4.%5.")
197 .arg(typeName, name, type.module(),
198 QString::number(version.majorVersion()),
199 QString::number(version.minorVersion())));
200 }
201 } else {
202 return recordError(binding->location,
203 tr("\"%1.%2\" is not available due to component versioning.")
204 .arg(typeName, name));
205 }
206 }
207 } else {
208 if (isGroupedProperty)
209 return recordError(binding->location, tr("Cannot assign a value directly to a grouped property"));
210
211 pd = defaultProperty;
212 name = defaultPropertyName;
213 bindingToDefaultProperty = true;
214 }
215
216 if (pd)
217 collectedBindingPropertyData[i] = pd;
218
219 if (name.constData()->isUpper() && !binding->isAttachedProperty()) {
220 QQmlImportResolutionResult resolution;
221 imports->resolveType(
222 m_typeLoader, stringAt(binding->propertyNameIndex), &resolution);
223 if (resolution.ns)
224 return recordError(binding->location, tr("Invalid use of namespace"));
225 return recordError(binding->location, tr("Invalid attached object assignment"));
226 }
227
228 if (bindingType >= QV4::CompiledData::Binding::Type_Object
229 && (pd || binding->isAttachedProperty() || binding->isGroupedProperty())) {
230 const bool populatingValueTypeGroupedProperty
231 = pd
232 && QQmlMetaType::metaObjectForValueType(pd->propType())
233 && !binding->hasFlag(QV4::CompiledData::Binding::IsOnAssignment);
234
235 // As this is a sub-object, its properties are qualified. We can ignore revisions.
236 const QList<QQmlError> subObjectValidatorErrors = validateObject(
237 binding->value.objectIndex, binding, populatingValueTypeGroupedProperty,
238 QQmlPropertyResolver::IgnoreRevision);
239
240 if (!subObjectValidatorErrors.isEmpty())
241 return subObjectValidatorErrors;
242 }
243
244 // Signal handlers were resolved and checked earlier in the signal handler conversion pass.
245 if (compilationUnit->bindingIsSignalHandler(objectIndex, i))
246 continue;
247
248 if ((pd && bindingType == QV4::CompiledData::Binding::Type_AttachedProperty)
249 || (!pd && bindingType == QV4::CompiledData::Binding::Type_GroupedProperty)) {
250 if (instantiatingBinding && (instantiatingBinding->isAttachedProperty()
251 || instantiatingBinding->isGroupedProperty())) {
252 return recordError(
253 binding->location, tr("%1 properties cannot be used here")
254 .arg(bindingType == QV4::CompiledData::Binding::Type_AttachedProperty
255 ? QStringLiteral("Attached")
256 : QStringLiteral("Group")));
257 }
258 continue;
259 } else if (bindingType == QV4::CompiledData::Binding::Type_AttachedProperty) {
260 continue;
261 }
262
263 if (pd) {
264 GroupedPropertyVector::const_iterator assignedGroupedProperty = std::lower_bound(groupedProperties.constBegin(), groupedProperties.constEnd(), binding->propertyNameIndex, BindingFinder());
265 const bool assigningToGroupedProperty = assignedGroupedProperty != groupedProperties.constEnd() && !(binding->propertyNameIndex < (*assignedGroupedProperty)->propertyNameIndex);
266
267 if (!pd->isWritable()
268 && !pd->isQList()
269 && !binding->isGroupedProperty()
270 && !(bindingFlags & QV4::CompiledData::Binding::InitializerForReadOnlyDeclaration)
271 ) {
272
273 if (assigningToGroupedProperty && bindingType < QV4::CompiledData::Binding::Type_Object)
274 return recordError(binding->valueLocation, tr("Cannot assign a value directly to a grouped property"));
275 return recordError(binding->valueLocation, tr("Invalid property assignment: \"%1\" is a read-only property").arg(name));
276 }
277
278 if (!pd->isQList() && (bindingFlags & QV4::CompiledData::Binding::IsListItem)) {
279 QString error;
280 if (pd->propType() == QMetaType::fromType<QQmlScriptString>())
281 error = tr( "Cannot assign multiple values to a script property");
282 else
283 error = tr( "Cannot assign multiple values to a singular property");
284 return recordError(binding->valueLocation, error);
285 }
286
287 if (!bindingToDefaultProperty
288 && !binding->isGroupedProperty()
289 && !(bindingFlags & QV4::CompiledData::Binding::IsOnAssignment)
290 && assigningToGroupedProperty) {
291 QV4::CompiledData::Location loc = binding->valueLocation;
292 if (loc < (*assignedGroupedProperty)->valueLocation)
293 loc = (*assignedGroupedProperty)->valueLocation;
294
295 if (pd && QQmlMetaType::isValueType(pd->propType()))
296 return recordError(loc, tr("Property has already been assigned a value"));
297 return recordError(loc, tr("Cannot assign a value directly to a grouped property"));
298 }
299
300 if (bindingType < QV4::CompiledData::Binding::Type_Script) {
301 QQmlError bindingError = validateLiteralBinding(propertyCache, pd, binding);
302 if (bindingError.isValid())
303 return recordError(bindingError);
304 } else if (bindingType == QV4::CompiledData::Binding::Type_Object) {
305 QQmlError bindingError = validateObjectBinding(
306 pd, name, binding,
307 compilationUnit->bindingIsSignalHandlerObject(objectIndex, i));
308 if (bindingError.isValid())
309 return recordError(bindingError);
310 } else if (binding->isGroupedProperty()) {
311 if (QQmlMetaType::isValueType(pd->propType())) {
312 if (QQmlMetaType::metaObjectForValueType(pd->propType())) {
313 if (!pd->isWritable()) {
314 return recordError(binding->location, tr("Invalid property assignment: \"%1\" is a read-only property").arg(name));
315 }
316 } else {
317 return recordError(binding->location, tr("Invalid grouped property access"));
318 }
319 } else {
320 const QMetaType type = pd->propType();
321 if (isPrimitiveType(type)) {
322 return recordError(
323 binding->location,
324 tr("Invalid grouped property access: Property \"%1\" with primitive type \"%2\".")
325 .arg(name, QString::fromUtf8(type.name()))
326 );
327 }
328
329 if (!QQmlMetaType::propertyCacheForType(type)) {
330 auto mo = type.metaObject();
331 if (!mo) {
332 return recordError(binding->location,
333 tr("Invalid grouped property access: Property \"%1\" with type \"%2\", which is neither a value nor an object type")
334 .arg(name, QString::fromUtf8(type.name()))
335 );
336 }
337 if (QMetaObjectPrivate::get(mo)->flags & DynamicMetaObject) {
338 return recordError(binding->location,
339 tr("Unsupported grouped property access: Property \"%1\" with type \"%2\" has a dynamic meta-object.")
340 .arg(name, QString::fromUtf8(type.name()))
341 );
342 }
343 // fall through, this is okay
344 }
345 }
346 }
347 } else {
348 if (customParser) {
349 customBindings << binding;
350 continue;
351 }
352 if (bindingToDefaultProperty) {
353 return recordError(binding->location, tr("Cannot assign to non-existent default property"));
354 } else {
355 return recordError(binding->location, tr("Cannot assign to non-existent property \"%1\"").arg(name));
356 }
357 }
358 }
359
360 if (obj->idNameIndex) {
361 if (populatingValueTypeGroupedProperty)
362 return recordError(obj->locationOfIdProperty, tr("Invalid use of id property with a value type"));
363
364 bool notInRevision = false;
365 collectedBindingPropertyData
366 << propertyResolver.property(QStringLiteral("id"), &notInRevision, checkRevision);
367 }
368
369 if (customParser && !customBindings.isEmpty()) {
370 customParser->clearErrors();
371 customParser->validator = this;
372 customParser->imports = imports;
373 customParser->verifyBindings(compilationUnit, customBindings);
374 customParser->validator = nullptr;
375 customParser->imports = (QQmlImports*)nullptr;
376 QList<QQmlError> parserErrors = customParser->errors();
377 if (!parserErrors.isEmpty())
378 return parserErrors;
379 }
380
381 (*bindingPropertyDataPerObject)[objectIndex] = collectedBindingPropertyData;
382
383 QList<QQmlError> noError;
384 return noError;
385}
386
387QQmlError QQmlPropertyValidator::validateLiteralBinding(
388 const QQmlPropertyCache::ConstPtr &propertyCache, const QQmlPropertyData *property,
389 const QV4::CompiledData::Binding *binding) const
390{
391 if (property->isQList()) {
392 return qQmlCompileError(binding->valueLocation, tr("Cannot assign primitives to lists"));
393 }
394
395 QQmlError noError;
396
397 if (property->isEnum()) {
398 // TODO: For historical reasons you can assign any number to an enum property alias
399 // This can be fixed with an opt-out mechanism, for example a pragma.
400 if (property->isAlias() && binding->isNumberBinding())
401 return noError;
402
403 QString value = compilationUnit->bindingValueAsString(binding);
404 QMetaProperty p = propertyCache->firstCppMetaObject()->property(property->coreIndex());
405 bool ok;
406 if (p.isFlagType()) {
407 p.enumerator().keysToValue(value.toUtf8().constData(), &ok);
408 } else
409 p.enumerator().keyToValue(value.toUtf8().constData(), &ok);
410
411 if (!ok) {
412 return qQmlCompileError(binding->valueLocation, tr("Invalid property assignment: unknown enumeration"));
413 }
414 return noError;
415 }
416
417 auto warnOrError = [&](const QString &error) {
418 return qQmlCompileError(binding->valueLocation, error);
419 };
420
421 const QV4::CompiledData::Binding::Type bindingType = binding->type();
422 const auto isStringBinding = [&]() -> bool {
423 // validateLiteralBinding is not supposed to be used on scripts
424 Q_ASSERT(bindingType != QV4::CompiledData::Binding::Type_Script);
425 return bindingType == QV4::CompiledData::Binding::Type_String;
426 };
427
428 switch (property->propType().id()) {
429 case QMetaType::QVariant:
430 break;
431 case QMetaType::QString: {
432 if (!binding->evaluatesToString()) {
433 return warnOrError(tr("Invalid property assignment: string expected"));
434 }
435 }
436 break;
437 case QMetaType::QStringList: {
438 if (!binding->evaluatesToString()) {
439 return warnOrError(tr("Invalid property assignment: string or string list expected"));
440 }
441 }
442 break;
443 case QMetaType::QByteArray: {
444 if (bindingType != QV4::CompiledData::Binding::Type_String)
445 return warnOrError(tr("Invalid property assignment: byte array expected"));
446 }
447 break;
448 case QMetaType::QUrl: {
449 if (bindingType != QV4::CompiledData::Binding::Type_String)
450 return warnOrError(tr("Invalid property assignment: url expected"));
451 }
452 break;
453 case QMetaType::UInt: {
454 if (bindingType == QV4::CompiledData::Binding::Type_Number) {
455 double d = compilationUnit->bindingValueAsNumber(binding);
456 if (double(uint(d)) == d)
457 return noError;
458 }
459 return warnOrError(tr("Invalid property assignment: unsigned int expected"));
460 }
461 break;
462 case QMetaType::Int: {
463 if (bindingType == QV4::CompiledData::Binding::Type_Number) {
464 double d = compilationUnit->bindingValueAsNumber(binding);
465 if (double(int(d)) == d)
466 return noError;
467 }
468 return warnOrError(tr("Invalid property assignment: int expected"));
469 }
470 break;
471 case QMetaType::LongLong:
472 case QMetaType::ULongLong:
473 case QMetaType::Long:
474 case QMetaType::ULong:
475 case QMetaType::Float:
476 case QMetaType::Double: {
477 if (bindingType != QV4::CompiledData::Binding::Type_Number) {
478 return warnOrError(tr("Invalid property assignment: number expected"));
479 }
480 }
481 break;
482 case QMetaType::QColor: {
483 bool ok = false;
484 if (isStringBinding())
485 QQmlStringConverters::rgbaFromString(compilationUnit->bindingValueAsString(binding), &ok);
486 if (!ok) {
487 return warnOrError(tr("Invalid property assignment: color expected"));
488 }
489 }
490 break;
491#if QT_CONFIG(datestring)
492 case QMetaType::QDate: {
493 bool ok = false;
494 if (isStringBinding())
495 QQmlStringConverters::dateFromString(compilationUnit->bindingValueAsString(binding), &ok);
496 if (!ok) {
497 return warnOrError(tr("Invalid property assignment: date expected"));
498 }
499 }
500 break;
501 case QMetaType::QTime: {
502 bool ok = false;
503 if (isStringBinding())
504 QQmlStringConverters::timeFromString(compilationUnit->bindingValueAsString(binding), &ok);
505 if (!ok) {
506 return warnOrError(tr("Invalid property assignment: time expected"));
507 }
508 }
509 break;
510 case QMetaType::QDateTime: {
511 bool ok = false;
512 if (isStringBinding())
513 QQmlStringConverters::dateTimeFromString(compilationUnit->bindingValueAsString(binding), &ok);
514 if (!ok) {
515 return warnOrError(tr("Invalid property assignment: datetime expected"));
516 }
517 }
518 break;
519#endif // datestring
520 case QMetaType::QPoint: {
521 bool ok = false;
522 if (isStringBinding())
523 QQmlStringConverters::pointFFromString(compilationUnit->bindingValueAsString(binding), &ok);
524 if (!ok) {
525 return warnOrError(tr("Invalid property assignment: point expected"));
526 }
527 }
528 break;
529 case QMetaType::QPointF: {
530 bool ok = false;
531 if (isStringBinding())
532 QQmlStringConverters::pointFFromString(compilationUnit->bindingValueAsString(binding), &ok);
533 if (!ok) {
534 return warnOrError(tr("Invalid property assignment: point expected"));
535 }
536 }
537 break;
538 case QMetaType::QSize: {
539 bool ok = false;
540 if (isStringBinding())
541 QQmlStringConverters::sizeFFromString(compilationUnit->bindingValueAsString(binding), &ok);
542 if (!ok) {
543 return warnOrError(tr("Invalid property assignment: size expected"));
544 }
545 }
546 break;
547 case QMetaType::QSizeF: {
548 bool ok = false;
549 if (isStringBinding())
550 QQmlStringConverters::sizeFFromString(compilationUnit->bindingValueAsString(binding), &ok);
551 if (!ok) {
552 return warnOrError(tr("Invalid property assignment: size expected"));
553 }
554 }
555 break;
556 case QMetaType::QRect: {
557 bool ok = false;
558 if (isStringBinding())
559 QQmlStringConverters::rectFFromString(compilationUnit->bindingValueAsString(binding), &ok);
560 if (!ok) {
561 return warnOrError(tr("Invalid property assignment: rect expected"));
562 }
563 }
564 break;
565 case QMetaType::QRectF: {
566 bool ok = false;
567 if (isStringBinding())
568 QQmlStringConverters::rectFFromString(compilationUnit->bindingValueAsString(binding), &ok);
569 if (!ok) {
570 return warnOrError(tr("Invalid property assignment: point expected"));
571 }
572 }
573 break;
574 case QMetaType::Bool: {
575 if (bindingType != QV4::CompiledData::Binding::Type_Boolean) {
576 return warnOrError(tr("Invalid property assignment: boolean expected"));
577 }
578 }
579 break;
580 case QMetaType::QVector2D:
581 case QMetaType::QVector3D:
582 case QMetaType::QVector4D:
583 case QMetaType::QQuaternion: {
584 auto typeName = [&]() {
585 switch (property->propType().id()) {
586 case QMetaType::QVector2D: return QStringLiteral("2D vector");
587 case QMetaType::QVector3D: return QStringLiteral("3D vector");
588 case QMetaType::QVector4D: return QStringLiteral("4D vector");
589 case QMetaType::QQuaternion: return QStringLiteral("quaternion");
590 default: return QString();
591 }
592 };
593 const QVariant result = QQmlValueTypeProvider::createValueType(
594 compilationUnit->bindingValueAsString(binding),
595 property->propType());
596 if (!result.isValid()) {
597 return warnOrError(tr("Invalid property assignment: %1 expected")
598 .arg(typeName()));
599 }
600 }
601 break;
602 case QMetaType::QRegularExpression:
603 return warnOrError(tr("Invalid property assignment: regular expression expected; use /pattern/ syntax"));
604 default: {
605 // generate single literal value assignment to a list property if required
606 if (property->propType() == QMetaType::fromType<QList<double>>()
607 || property->propType() == QMetaType::fromType<QList<float>>()) {
608 if (bindingType != QV4::CompiledData::Binding::Type_Number) {
609 return warnOrError(tr("Invalid property assignment: number or array of numbers expected"));
610 }
611 break;
612 } else if (property->propType() == QMetaType::fromType<QList<int> >()) {
613 bool ok = (bindingType == QV4::CompiledData::Binding::Type_Number);
614 if (ok) {
615 double n = compilationUnit->bindingValueAsNumber(binding);
616 if (double(int(n)) != n)
617 ok = false;
618 }
619 if (!ok)
620 return warnOrError(tr("Invalid property assignment: int or array of ints expected"));
621 break;
622 } else if (property->propType() == QMetaType::fromType<QList<bool> >()) {
623 if (bindingType != QV4::CompiledData::Binding::Type_Boolean) {
624 return warnOrError(tr("Invalid property assignment: bool or array of bools expected"));
625 }
626 break;
627 } else if (property->propType() == QMetaType::fromType<QList<QUrl> >()) {
628 if (bindingType != QV4::CompiledData::Binding::Type_String) {
629 return warnOrError(tr("Invalid property assignment: url or array of urls expected"));
630 }
631 break;
632 } else if (property->propType() == QMetaType::fromType<QList<QString> >()) {
633 if (!binding->evaluatesToString()) {
634 return warnOrError(tr("Invalid property assignment: string or array of strings expected"));
635 }
636 break;
637 } else if (property->propType() == QMetaType::fromType<QJSValue>()) {
638 break;
639 } else if (property->propType() == QMetaType::fromType<QQmlScriptString>()) {
640 break;
641 } else if (property->isQObject()
642 && bindingType == QV4::CompiledData::Binding::Type_Null) {
643 break;
644 } else if (QQmlMetaType::qmlType(property->propType()).canConstructValueType()) {
645 break;
646 }
647
648 return warnOrError(tr("Invalid property assignment: unsupported type \"%1\"").arg(QLatin1StringView(property->propType().name())));
649 }
650 break;
651 }
652 return noError;
653}
654
655/*!
656 Returns true if from can be assigned to a (QObject) property of type
657 to.
658*/
659bool QQmlPropertyValidator::canCoerce(QMetaType to, QQmlPropertyCache::ConstPtr fromMo) const
660{
661 if (QQmlMetaType::canConvert(fromMo, to))
662 return true;
663
664 // if we have an inline component from the current file,
665 // it is not properly registered at this point, as registration
666 // only occurs after the whole file has been validated
667 // Therefore we need to check the ICs here
668 for (const auto &icDatum : std::as_const(compilationUnit->inlineComponentData)) {
669 if (icDatum.qmlType.typeId() != to)
670 continue;
671
672 const auto toMo = compilationUnit->propertyCaches.at(icDatum.objectIndex);
673 for (QQmlPropertyCache::ConstPtr parent = fromMo; parent; parent = parent->parent()) {
674 if (parent == toMo)
675 return true;
676 }
677 return false;
678 }
679
680 return false;
681}
682
683QList<QQmlError> QQmlPropertyValidator::recordError(const QV4::CompiledData::Location &location, const QString &description) const
684{
685 QList<QQmlError> errors;
686 errors.append(qQmlCompileError(location, description));
687 return errors;
688}
689
690QList<QQmlError> QQmlPropertyValidator::recordError(const QQmlError &error) const
691{
692 QList<QQmlError> errors;
693 errors.append(error);
694 return errors;
695}
696
697QQmlError QQmlPropertyValidator::validateObjectBinding(
698 const QQmlPropertyData *property, const QString &propertyName,
699 const QV4::CompiledData::Binding *binding, bool isSignalHandlerObject) const
700{
701 QQmlError noError;
702
703 if (binding->hasFlag(QV4::CompiledData::Binding::IsOnAssignment)) {
704 Q_ASSERT(binding->type() == QV4::CompiledData::Binding::Type_Object);
705
706 bool isValueSource = false;
707 bool isPropertyInterceptor = false;
708
709 const QV4::CompiledData::Object *targetObject = compilationUnit->objectAt(binding->value.objectIndex);
710 if (auto *typeRef = resolvedType(targetObject->inheritedTypeNameIndex)) {
711 QQmlPropertyCache::ConstPtr cache = typeRef->createPropertyCache();
712 const QMetaObject *mo = cache ? cache->firstCppMetaObject() : nullptr;
713 QQmlType qmlType;
714 while (mo && !qmlType.isValid()) {
715 qmlType = QQmlMetaType::qmlType(mo);
716 mo = mo->superClass();
717 }
718
719 isValueSource = qmlType.propertyValueSourceCast() != -1;
720 isPropertyInterceptor = qmlType.propertyValueInterceptorCast() != -1;
721 }
722
723 if (!isValueSource && !isPropertyInterceptor) {
724 return qQmlCompileError(
725 binding->valueLocation,
726 tr("\"%1\" cannot operate on \"%2\"")
727 .arg(stringAt(targetObject->inheritedTypeNameIndex), propertyName));
728 }
729
730 return noError;
731 }
732
733 const QMetaType propType = property->propType();
734 const auto rhsType = [&]() {
735 return stringAt(compilationUnit->objectAt(binding->value.objectIndex)
736 ->inheritedTypeNameIndex);
737 };
738
739 if (QQmlMetaType::isInterface(propType)) {
740 // Can only check at instantiation time if the created sub-object successfully casts to the
741 // target interface.
742 return noError;
743 } else if (propType == QMetaType::fromType<QVariant>()
744 || propType == QMetaType::fromType<QJSValue>()) {
745 // We can convert everything to QVariant :)
746 return noError;
747 } else if (property->isQList()) {
748 const QMetaType listType = QQmlMetaType::listValueType(property->propType());
749 if (!QQmlMetaType::isInterface(listType)) {
750 QQmlPropertyCache::ConstPtr source = propertyCaches.at(binding->value.objectIndex);
751
752 if (const int wrapper = compilationUnit->implicitComponentForObject(
753 binding->value.objectIndex); wrapper != -1) {
754 // If the child is wrapped in an implicit component, use the wrapper for coercion.
755 source = propertyCaches.at(wrapper);
756 }
757
758 if (!canCoerce(listType, source)) {
759 const QString expectedTypeName = QString::fromUtf8(listType.name()).remove(QLatin1Char('*'));
760 return qQmlCompileError(binding->valueLocation,
761 tr("Cannot assign object of type \"%1\" to list property \"%2\"; expected \"%3\"")
762 .arg(source->className(), propertyName, expectedTypeName));
763 }
764 }
765 return noError;
766 } else if (isSignalHandlerObject && property->isFunction()) {
767 return noError;
768 } else if (isPrimitiveType(propType)) {
769 auto typeName = QString::fromUtf8(QMetaType(propType).name());
770 return qQmlCompileError(
771 binding->location,
772 tr("Cannot assign value of type \"%1\" to property \"%2\", expecting \"%3\"")
773 .arg(rhsType(), propertyName, typeName));
774 } else if (propType == QMetaType::fromType<QQmlScriptString>()) {
775 return qQmlCompileError(binding->valueLocation, tr("Invalid property assignment: script expected"));
776 } else if (!QQmlMetaType::isValueType(property->propType())) {
777 QQmlPropertyCache::ConstPtr propertyMetaObject;
778
779 // if we have an inline component from the current file,
780 // it is not properly registered at this point, as registration
781 // only occurs after the whole file has been validated
782 // Therefore we need to check the ICs here
783 for (const auto &icDatum: std::as_const(compilationUnit->inlineComponentData)) {
784 if (icDatum.qmlType.typeId() == property->propType()) {
785 propertyMetaObject = compilationUnit->propertyCaches.at(icDatum.objectIndex);
786 break;
787 }
788 }
789
790 if (!propertyMetaObject) {
791 // We want to use the raw metaObject here as the raw metaobject is the
792 // actual property type before we applied any extensions that might
793 // effect the properties on the type, but don't effect assignability
794 // Not passing a version ensures that we get the raw metaObject.
795 propertyMetaObject = QQmlMetaType::rawPropertyCacheForType(propType);
796 }
797
798 if (propertyMetaObject) {
799 // Will be true if the assigned type inherits propertyMetaObject
800 // Determine isAssignable value
801 bool isAssignable = false;
802 QQmlPropertyCache::ConstPtr source = propertyCaches.at(binding->value.objectIndex);
803
804 if (const int wrapper = compilationUnit->implicitComponentForObject(
805 binding->value.objectIndex); wrapper != -1) {
806 // If the child is wrapped in an implicit component, use the wrapper.
807 source = propertyCaches.at(wrapper);
808 }
809
810 const auto inheritsFrom = [&](const QQmlPropertyCache::ConstPtr &target) {
811 for (QQmlPropertyCache::ConstPtr c = source; c; c = c->parent()) {
812 if (c == target)
813 return true;
814 }
815 return false;
816 };
817
818 isAssignable = inheritsFrom(propertyMetaObject);
819
820 if (!isAssignable && propertyMetaObject->isComposite()) {
821 // a single metatype can map to multiple property caches when there are
822 // multiple engines; rawPropertyCacheForType only returns one of them.
823 const auto candidates = QQmlMetaType::rawCompositePropertyCachesForType(propType);
824 for (const auto &candidate : candidates) {
825 if (inheritsFrom(candidate)) {
826 isAssignable = true;
827 break;
828 }
829 }
830 }
831
832 if (!isAssignable) {
833 return qQmlCompileError(binding->valueLocation, tr("Cannot assign object of type \"%1\" to property of type \"%2\" as the former is neither the same as the latter nor a sub-class of it.")
834 .arg(rhsType()).arg(QLatin1String(property->propType().name())));
835 }
836 } else {
837 return qQmlCompileError(binding->valueLocation, tr("Cannot assign to property of unknown type \"%1\".")
838 .arg(QLatin1String(property->propType().name())));
839 }
840
841 }
842 return noError;
843}
844
845QT_END_NAMESPACE
Combined button and popup list for selecting options.
QVarLengthArray< const QV4::CompiledData::Binding *, 8 > GroupedPropertyVector
static QT_BEGIN_NAMESPACE bool isPrimitiveType(QMetaType metaType)
bool operator()(quint32 name, const QV4::CompiledData::Binding *binding) const
bool operator()(const QV4::CompiledData::Binding *binding, quint32 name) const
bool operator()(const QV4::CompiledData::Binding *lhs, const QV4::CompiledData::Binding *rhs) const