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
qqmlobjectcreator.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
6
7#include <private/qjsvalue_p.h>
8#include <private/qqmlanybinding_p.h>
9#include <private/qqmlbinding_p.h>
10#include <private/qqmlboundsignal_p.h>
11#include <private/qqmlcomponent_p.h>
12#include <private/qqmlcomponentattached_p.h>
13#include <private/qqmlcustomparser_p.h>
14#include <private/qqmldebugconnector_p.h>
15#include <private/qqmldebugserviceinterfaces_p.h>
16#include <private/qqmlengine_p.h>
17#include <private/qqmlpropertybinding_p.h>
18#include <private/qqmlpropertyvalueinterceptor_p.h>
19#include <private/qqmlscriptdata_p.h>
20#include <private/qqmlscriptstring_p.h>
21#include <private/qqmlsourcecoordinate_p.h>
22#include <private/qqmlstringconverters_p.h>
23#include <private/qqmlvaluetypeproxybinding_p.h>
24#include <private/qqmlvme_p.h>
25#include <private/qqmlvmemetaobject_p.h>
26#include <private/qv4function_p.h>
27#include <private/qv4functionobject_p.h>
28#include <private/qv4generatorobject_p.h>
29#include <private/qv4qobjectwrapper_p.h>
30#include <private/qv4referenceobject_p.h>
31#include <private/qv4resolvedtypereference_p.h>
32
33#include <qtqml_tracepoints_p.h>
34
35#include <QtCore/qscopedvaluerollback.h>
36#include <QtCore/qloggingcategory.h>
37
38Q_STATIC_LOGGING_CATEGORY(lcQmlDefaultMethod, "qt.qml.defaultmethod")
39
40QT_USE_NAMESPACE
41
42Q_TRACE_PREFIX(qtqml,
43"namespace QV4 {" \
44"struct ExecutionEngine;"\
45"class ExecutableCompilationUnit;"\
46"namespace CompiledData {"\
47"struct Object;"\
48"}}"\
49"class QQmlEngine;"
50)
51
52Q_TRACE_POINT(qtqml, QQmlObjectCreator_createInstance_entry, const QV4::ExecutableCompilationUnit *compilationUnit, const QV4::CompiledData::Object *object, const QUrl &url)
53Q_TRACE_POINT(qtqml, QQmlObjectCreator_createInstance_exit, const QString &typeName)
54
55QQmlObjectCreator::QQmlObjectCreator(
56 const QQmlRefPointer<QQmlContextData> &parentContext,
57 const QQmlRefPointer<QV4::ExecutableCompilationUnit> &compilationUnit,
58 const QQmlRefPointer<QQmlContextData> &creationContext,
59 const QString &inlineComponentName,
60 QQmlIncubatorPrivate *incubator)
61 : phase(Startup)
62 , m_inlineComponentName(inlineComponentName)
63 , compilationUnit(compilationUnit)
64 , propertyCaches(compilationUnit->propertyCachesPtr())
65 , sharedState(new QQmlObjectCreatorSharedState, QQmlRefPointer<QQmlObjectCreatorSharedState>::Adopt)
66 , topLevelCreator(true)
67 , isContextObject(true)
68 , incubator(incubator)
69{
70 init(parentContext);
71
72 sharedState->componentAttached = nullptr;
73 sharedState->allJavaScriptObjects = ObjectInCreationGCAnchorList();
74 sharedState->creationContext = creationContext;
75 sharedState->rootContext.reset();
76 sharedState->hadTopLevelRequiredProperties = false;
77
78 if (auto profiler = QQmlEnginePrivate::get(engine)->profiler) {
79 Q_QML_PROFILE_IF_ENABLED(QQmlProfilerDefinitions::ProfileCreating, profiler,
80 sharedState->profiler.init(profiler));
81 } else {
82 Q_UNUSED(profiler);
83 }
84}
85
86QQmlObjectCreator::QQmlObjectCreator(const QQmlRefPointer<QQmlContextData> &parentContext,
87 const QQmlRefPointer<QV4::ExecutableCompilationUnit> &compilationUnit, const QString inlineComponentName,
88 QQmlObjectCreatorSharedState *inheritedSharedState, bool isContextObject)
89 : phase(Startup)
90 , m_inlineComponentName(inlineComponentName)
91 , compilationUnit(compilationUnit)
92 , propertyCaches(compilationUnit->propertyCachesPtr())
93 , sharedState(inheritedSharedState)
94 , topLevelCreator(false)
95 , isContextObject(isContextObject)
96 , incubator(nullptr)
97{
98 init(parentContext);
99}
100
101void QQmlObjectCreator::init(const QQmlRefPointer<QQmlContextData> &providedParentContext)
102{
103 parentContext = providedParentContext;
104 engine = parentContext->engine();
105 v4 = engine->handle();
106
107 Q_ASSERT(compilationUnit);
108 Q_ASSERT(compilationUnit->engine == v4);
109 if (!compilationUnit->runtimeStrings)
110 compilationUnit->populate();
111
112 qmlUnit = compilationUnit->unitData();
113 _qobject = nullptr;
114 _scopeObject = nullptr;
115 _bindingTarget = nullptr;
116 _valueTypeProperty = nullptr;
117 _compiledObject = nullptr;
118 _compiledObjectIndex = -1;
119 _ddata = nullptr;
120 _vmeMetaObject = nullptr;
121 _qmlContext = nullptr;
122}
123
124QQmlObjectCreator::~QQmlObjectCreator()
125{
126 if (topLevelCreator) {
127 {
128 // This signals to other methods further up the stack that we have
129 // "recursed" and they should be aborted.
130 QQmlObjectCreatorRecursionWatcher watcher(this);
131 }
132 while (sharedState->componentAttached) {
133 QQmlComponentAttached *a = sharedState->componentAttached;
134 a->removeFromList();
135 }
136 }
137}
138
139QObject *QQmlObjectCreator::create(int subComponentIndex, QObject *parent, QQmlInstantiationInterrupt *interrupt, int flags)
140{
141 if (phase == CreatingObjectsPhase2) {
142 phase = ObjectsCreated;
143 return context->contextObject();
144 }
145 Q_ASSERT(phase == Startup);
146 phase = CreatingObjects;
147
148 int objectToCreate;
149 bool isComponentRoot = false; // either a "real" component of or an inline component
150
151 if (subComponentIndex == -1) {
152 objectToCreate = /*root object*/0;
153 isComponentRoot = true;
154 } else {
155 Q_ASSERT(subComponentIndex >= 0);
156 if (flags & CreationFlags::InlineComponent) {
157 if (compilationUnit->componentsAreBound()
158 && compilationUnit != parentContext->typeCompilationUnit()) {
159 recordError({}, tr("Cannot instantiate bound inline component in different file"));
160 phase = ObjectsCreated;
161 return nullptr;
162 }
163 objectToCreate = subComponentIndex;
164 isComponentRoot = true;
165 } else {
166 Q_ASSERT(flags & CreationFlags::NormalObject);
167 if (compilationUnit->componentsAreBound()
168 && sharedState->creationContext != parentContext) {
169 recordError({}, tr("Cannot instantiate bound component "
170 "outside its creation context"));
171 phase = ObjectsCreated;
172 return nullptr;
173 }
174 if (subComponentIndex < compilationUnit->objectCount()) {
175 const QV4::CompiledData::Object *compObj
176 = compilationUnit->objectAt(subComponentIndex);
177 objectToCreate = compObj->bindingTable()->value.objectIndex;
178 } else {
179 // Implicit component wrappers have index >= objectCount().
180 // Read child index from the property cache instead of the CU object.
181 objectToCreate = compilationUnit->resolvedIndex(subComponentIndex);
182 }
183 }
184 }
185
186 QQmlEnginePrivate *enginePriv = QQmlEnginePrivate::get(engine);
187 context = isComponentRoot
188 ? enginePriv->createComponentRootContext(compilationUnit, parentContext,
189 subComponentIndex)
190 : enginePriv->createBareContext(compilationUnit, parentContext, subComponentIndex);
191
192 if (!sharedState->rootContext) {
193 sharedState->rootContext = context;
194 sharedState->rootContext->setIncubator(incubator);
195 sharedState->rootContext->setRootObjectInCreation(true);
196 }
197
198 QV4::Scope scope(v4);
199
200 Q_ASSERT(sharedState->allJavaScriptObjects.canTrack() || topLevelCreator);
201 if (topLevelCreator)
202 sharedState->allJavaScriptObjects = ObjectInCreationGCAnchorList(scope);
203
204 if (!isComponentRoot && sharedState->creationContext) {
205 // otherwise QQmlEnginePrivate::createComponentRootContext() handles it
206 QV4::ScopedValue scripts(scope, sharedState->creationContext->importedScripts());
207 context->setImportedScripts(v4, scripts);
208 }
209
210 QObject *instance = createInstance(objectToCreate, parent, /*isContextObject*/true);
211 if (instance) {
212 QQmlData *ddata = QQmlData::get(instance);
213 Q_ASSERT(ddata);
214 ddata->compilationUnit = compilationUnit;
215 }
216
217 if (topLevelCreator)
218 sharedState->allJavaScriptObjects = ObjectInCreationGCAnchorList();
219
220 phase = CreatingObjectsPhase2;
221
222 if (interrupt && interrupt->shouldInterrupt())
223 return nullptr;
224
225 phase = ObjectsCreated;
226
227 if (instance) {
228 if (QQmlEngineDebugService *service
229 = QQmlDebugConnector::service<QQmlEngineDebugService>()) {
230 if (!parentContext->isInternal())
231 parentContext->asQQmlContextPrivate()->appendInstance(instance);
232 service->objectCreated(engine, instance);
233 } else if (!parentContext->isInternal() && QQmlDebugConnector::service<QV4DebugService>()) {
234 parentContext->asQQmlContextPrivate()->appendInstance(instance);
235 }
236 }
237
238 return instance;
239}
240
241void QQmlObjectCreator::beginPopulateDeferred(const QQmlRefPointer<QQmlContextData> &newContext)
242{
243 context = newContext;
244 sharedState->rootContext = newContext;
245
246 Q_ASSERT(topLevelCreator);
247 Q_ASSERT(!sharedState->allJavaScriptObjects.canTrack());
248
249 // FIXME (QTBUG-122956): allocating from the short lived scope does not make any sense
250 QV4::Scope valueScope(v4);
251 sharedState->allJavaScriptObjects = ObjectInCreationGCAnchorList(valueScope);
252}
253
254void QQmlObjectCreator::populateDeferred(QObject *instance, int deferredIndex,
255 const QQmlPropertyPrivate *qmlProperty,
256 const QV4::CompiledData::Binding *binding)
257{
258 doPopulateDeferred(instance, deferredIndex, [this, qmlProperty, binding]() {
259 Q_ASSERT(qmlProperty);
260
261 QQmlListProperty<QObject> savedList;
262 qSwap(_currentList, savedList);
263
264 const QQmlPropertyData &property = qmlProperty->core;
265
266 if (property.propType().flags().testFlag(QMetaType::IsQmlList)) {
267 void *argv[1] = { (void*)&_currentList };
268 QMetaObject::metacall(_qobject, QMetaObject::ReadProperty, property.coreIndex(), argv);
269 } else if (_currentList.object) {
270 _currentList = QQmlListProperty<QObject>();
271 }
272
273 setPropertyBinding(&property, binding);
274
275 qSwap(_currentList, savedList);
276 });
277}
278
279void QQmlObjectCreator::populateDeferred(QObject *instance, int deferredIndex)
280{
281 doPopulateDeferred(instance, deferredIndex, [this]() { setupBindings(ApplyDeferred); });
282}
283
284bool QQmlObjectCreator::populateDeferredProperties(QObject *instance,
285 const QQmlData::DeferredData *deferredData)
286{
287 beginPopulateDeferred(deferredData->context);
288 populateDeferred(instance, deferredData->deferredIdx);
289 finalizePopulateDeferred();
290 return errors.isEmpty();
291}
292
293void QQmlObjectCreator::populateDeferredBinding(const QQmlProperty &qmlProperty, int deferredIndex,
294 const QV4::CompiledData::Binding *binding)
295{
296 if (binding) {
297 populateDeferred(qmlProperty.object(), deferredIndex, QQmlPropertyPrivate::get(qmlProperty),
298 binding);
299 } else {
300 populateDeferred(qmlProperty.object(), deferredIndex);
301 }
302}
303
304void QQmlObjectCreator::populateDeferredInstance(
305 QObject *outerObject, int deferredIndex, int index, QObject *instance,
306 QObject *bindingTarget, const QQmlPropertyData *valueTypeProperty,
307 const QV4::CompiledData::Binding *binding)
308{
309 doPopulateDeferred(outerObject, deferredIndex, [&]() {
310 populateInstance(index, instance, bindingTarget, valueTypeProperty, binding);
311 });
312}
313
314void QQmlObjectCreator::finalizePopulateDeferred()
315{
316 phase = ObjectsCreated;
317}
318
319void QQmlObjectCreator::setPropertyValue(const QQmlPropertyData *property, const QV4::CompiledData::Binding *binding,
320 std::optional<int> foldedNumber)
321{
322 QQmlPropertyData::WriteFlags propertyWriteFlags = QQmlPropertyData::BypassInterceptor | QQmlPropertyData::RemoveBindingOnAliasWrite;
323 QV4::Scope scope(v4);
324
325 QMetaType propertyType = property->propType();
326
327 const QV4::CompiledData::Binding::Type effectiveType
328 = foldedNumber ? QV4::CompiledData::Binding::Type_Number : binding->type();
329 const auto effectiveNumber = [&]() -> double {
330 return foldedNumber ? double(*foldedNumber) : compilationUnit->bindingValueAsNumber(binding);
331 };
332
333 if (property->isEnum()) {
334 if (foldedNumber.has_value() ||
335 // TODO: For historical reasons you can assign any number to an enum property alias
336 // This can be fixed with an opt-out mechanism, for example a pragma.
337 (property->isAlias() && binding->isNumberBinding())) {
338 propertyType = property->propType().underlyingType();
339 } else {
340 // ### This should be resolved earlier at compile time and the binding value should be changed accordingly.
341 QVariant value = compilationUnit->bindingValueAsString(binding);
342 bool ok = QQmlPropertyPrivate::write(_qobject, *property, value, context);
343 Q_ASSERT(ok);
344 Q_UNUSED(ok);
345 return;
346 }
347 }
348
349 auto assertOrNull = [&](bool ok)
350 {
351 Q_ASSERT(ok || effectiveType == QV4::CompiledData::Binding::Type_Null);
352 Q_UNUSED(ok);
353 };
354
355 auto assertType = [&](QV4::CompiledData::Binding::Type type)
356 {
357 Q_ASSERT(effectiveType == type || effectiveType == QV4::CompiledData::Binding::Type_Null);
358 Q_UNUSED(type);
359 };
360
361 if (property->isQObject()) {
362 if (effectiveType == QV4::CompiledData::Binding::Type_Null) {
363 QObject *value = nullptr;
364 const bool ok = property->writeProperty(_qobject, &value, propertyWriteFlags);
365 Q_ASSERT(ok);
366 Q_UNUSED(ok);
367 return;
368 }
369 }
370
371 switch (propertyType.id()) {
372 case QMetaType::QVariant: {
373 if (effectiveType == QV4::CompiledData::Binding::Type_Number) {
374 double n = effectiveNumber();
375 if (double(int(n)) == n) {
376 if (property->isVarProperty()) {
377 _vmeMetaObject->setVMEProperty(property->coreIndex(), QV4::Value::fromInt32(int(n)));
378 } else {
379 int i = int(n);
380 QVariant value(i);
381 property->writeProperty(_qobject, &value, propertyWriteFlags);
382 }
383 } else {
384 if (property->isVarProperty()) {
385 _vmeMetaObject->setVMEProperty(property->coreIndex(), QV4::Value::fromDouble(n));
386 } else {
387 QVariant value(n);
388 property->writeProperty(_qobject, &value, propertyWriteFlags);
389 }
390 }
391 } else if (effectiveType == QV4::CompiledData::Binding::Type_Boolean) {
392 if (property->isVarProperty()) {
393 _vmeMetaObject->setVMEProperty(property->coreIndex(), QV4::Value::fromBoolean(binding->valueAsBoolean()));
394 } else {
395 QVariant value(binding->valueAsBoolean());
396 property->writeProperty(_qobject, &value, propertyWriteFlags);
397 }
398 } else if (effectiveType == QV4::CompiledData::Binding::Type_Null) {
399 if (property->isVarProperty()) {
400 _vmeMetaObject->setVMEProperty(property->coreIndex(), QV4::Value::nullValue());
401 } else {
402 QVariant nullValue = QVariant::fromValue(nullptr);
403 property->writeProperty(_qobject, &nullValue, propertyWriteFlags);
404 }
405 } else {
406 QString stringValue = compilationUnit->bindingValueAsString(binding);
407 if (property->isVarProperty()) {
408 QV4::ScopedString s(scope, v4->newString(stringValue));
409 _vmeMetaObject->setVMEProperty(property->coreIndex(), s);
410 } else {
411 QVariant value = stringValue;
412 property->writeProperty(_qobject, &value, propertyWriteFlags);
413 }
414 }
415 }
416 break;
417 case QMetaType::QString: {
418 assertOrNull(binding->evaluatesToString());
419 QString value = compilationUnit->bindingValueAsString(binding);
420 property->writeProperty(_qobject, &value, propertyWriteFlags);
421 }
422 break;
423 case QMetaType::QStringList: {
424 assertOrNull(binding->evaluatesToString());
425 QStringList value(compilationUnit->bindingValueAsString(binding));
426 property->writeProperty(_qobject, &value, propertyWriteFlags);
427 }
428 break;
429 case QMetaType::QByteArray: {
430 assertType(QV4::CompiledData::Binding::Type_String);
431 QByteArray value(compilationUnit->bindingValueAsString(binding).toUtf8());
432 property->writeProperty(_qobject, &value, propertyWriteFlags);
433 }
434 break;
435 case QMetaType::QUrl: {
436 assertType(QV4::CompiledData::Binding::Type_String);
437 const QString string = compilationUnit->bindingValueAsString(binding);
438 QUrl value = (!string.isEmpty() && QQmlPropertyPrivate::resolveUrlsOnAssignment())
439 ? compilationUnit->finalUrl().resolved(QUrl(string))
440 : QUrl(string);
441 property->writeProperty(_qobject, &value, propertyWriteFlags);
442 }
443 break;
444 case QMetaType::UInt: {
445 assertType(QV4::CompiledData::Binding::Type_Number);
446 double d = effectiveNumber();
447 uint value = uint(d);
448 property->writeProperty(_qobject, &value, propertyWriteFlags);
449 break;
450 }
451 break;
452 case QMetaType::Int: {
453 assertType(QV4::CompiledData::Binding::Type_Number);
454 double d = effectiveNumber();
455 int value = int(d);
456 property->writeProperty(_qobject, &value, propertyWriteFlags);
457 break;
458 }
459 break;
460 case QMetaType::SChar: {
461 assertType(QV4::CompiledData::Binding::Type_Number);
462 double d = effectiveNumber();
463 qint8 value = qint8(d);
464 property->writeProperty(_qobject, &value, propertyWriteFlags);
465 break;
466 }
467 case QMetaType::UChar: {
468 assertType(QV4::CompiledData::Binding::Type_Number);
469 double d = effectiveNumber();
470 quint8 value = quint8(d);
471 property->writeProperty(_qobject, &value, propertyWriteFlags);
472 break;
473 }
474 case QMetaType::Short: {
475 assertType(QV4::CompiledData::Binding::Type_Number);
476 double d = effectiveNumber();
477 qint16 value = qint16(d);
478 property->writeProperty(_qobject, &value, propertyWriteFlags);
479 break;
480 }
481 case QMetaType::UShort: {
482 assertType(QV4::CompiledData::Binding::Type_Number);
483 double d = effectiveNumber();
484 quint16 value = quint16(d);
485 property->writeProperty(_qobject, &value, propertyWriteFlags);
486 break;
487 }
488 case QMetaType::LongLong: {
489 assertType(QV4::CompiledData::Binding::Type_Number);
490 double d = effectiveNumber();
491 qint64 value = qint64(d);
492 property->writeProperty(_qobject, &value, propertyWriteFlags);
493 break;
494 }
495 case QMetaType::ULongLong: {
496 assertType(QV4::CompiledData::Binding::Type_Number);
497 double d = effectiveNumber();
498 quint64 value = quint64(d);
499 property->writeProperty(_qobject, &value, propertyWriteFlags);
500 break;
501 }
502 break;
503 case QMetaType::Float: {
504 assertType(QV4::CompiledData::Binding::Type_Number);
505 float value = float(effectiveNumber());
506 property->writeProperty(_qobject, &value, propertyWriteFlags);
507 }
508 break;
509 case QMetaType::Double: {
510 assertType(QV4::CompiledData::Binding::Type_Number);
511 double value = effectiveNumber();
512 property->writeProperty(_qobject, &value, propertyWriteFlags);
513 }
514 break;
515 case QMetaType::QColor: {
516 bool ok = false;
517 QVariant data = QQmlStringConverters::colorFromString(
518 compilationUnit->bindingValueAsString(binding), &ok);
519 Q_ASSERT(ok); // We've checked this in QQmlPropertyValidator
520 property->writeProperty(_qobject, data.data(), propertyWriteFlags);
521 }
522 break;
523#if QT_CONFIG(datestring)
524 case QMetaType::QDate: {
525 bool ok = false;
526 QDate value = QQmlStringConverters::dateFromString(compilationUnit->bindingValueAsString(binding), &ok);
527 assertOrNull(ok);
528 property->writeProperty(_qobject, &value, propertyWriteFlags);
529 }
530 break;
531 case QMetaType::QTime: {
532 bool ok = false;
533 QTime value = QQmlStringConverters::timeFromString(compilationUnit->bindingValueAsString(binding), &ok);
534 assertOrNull(ok);
535 property->writeProperty(_qobject, &value, propertyWriteFlags);
536 }
537 break;
538 case QMetaType::QDateTime: {
539 bool ok = false;
540 QDateTime value = QQmlStringConverters::dateTimeFromString(
541 compilationUnit->bindingValueAsString(binding), &ok);
542 assertOrNull(ok);
543 property->writeProperty(_qobject, &value, propertyWriteFlags);
544 }
545 break;
546#endif // datestring
547 case QMetaType::QPoint: {
548 bool ok = false;
549 QPoint value = QQmlStringConverters::pointFFromString(compilationUnit->bindingValueAsString(binding), &ok).toPoint();
550 assertOrNull(ok);
551 property->writeProperty(_qobject, &value, propertyWriteFlags);
552 }
553 break;
554 case QMetaType::QPointF: {
555 bool ok = false;
556 QPointF value = QQmlStringConverters::pointFFromString(compilationUnit->bindingValueAsString(binding), &ok);
557 assertOrNull(ok);
558 property->writeProperty(_qobject, &value, propertyWriteFlags);
559 }
560 break;
561 case QMetaType::QSize: {
562 bool ok = false;
563 QSize value = QQmlStringConverters::sizeFFromString(compilationUnit->bindingValueAsString(binding), &ok).toSize();
564 assertOrNull(ok);
565 property->writeProperty(_qobject, &value, propertyWriteFlags);
566 }
567 break;
568 case QMetaType::QSizeF: {
569 bool ok = false;
570 QSizeF value = QQmlStringConverters::sizeFFromString(compilationUnit->bindingValueAsString(binding), &ok);
571 assertOrNull(ok);
572 property->writeProperty(_qobject, &value, propertyWriteFlags);
573 }
574 break;
575 case QMetaType::QRect: {
576 bool ok = false;
577 QRect value = QQmlStringConverters::rectFFromString(compilationUnit->bindingValueAsString(binding), &ok).toRect();
578 assertOrNull(ok);
579 property->writeProperty(_qobject, &value, propertyWriteFlags);
580 }
581 break;
582 case QMetaType::QRectF: {
583 bool ok = false;
584 QRectF value = QQmlStringConverters::rectFFromString(compilationUnit->bindingValueAsString(binding), &ok);
585 assertOrNull(ok);
586 property->writeProperty(_qobject, &value, propertyWriteFlags);
587 }
588 break;
589 case QMetaType::Bool: {
590 assertType(QV4::CompiledData::Binding::Type_Boolean);
591 bool value = binding->valueAsBoolean();
592 property->writeProperty(_qobject, &value, propertyWriteFlags);
593 }
594 break;
595 case QMetaType::QVector2D:
596 case QMetaType::QVector3D:
597 case QMetaType::QVector4D:
598 case QMetaType::QQuaternion: {
599 QVariant result = QQmlValueTypeProvider::createValueType(
600 compilationUnit->bindingValueAsString(binding), propertyType);
601 assertOrNull(result.isValid());
602 property->writeProperty(_qobject, result.data(), propertyWriteFlags);
603 break;
604 }
605 default: {
606 // generate single literal value assignment to a list property if required
607 if (propertyType == QMetaType::fromType<QList<double>>()) {
608 assertType(QV4::CompiledData::Binding::Type_Number);
609 QList<double> value;
610 value.append(compilationUnit->bindingValueAsNumber(binding));
611 property->writeProperty(_qobject, &value, propertyWriteFlags);
612 break;
613 } else if (propertyType == QMetaType::fromType<QList<float>>()) {
614 assertType(QV4::CompiledData::Binding::Type_Number);
615 QList<float> value;
616 value.append(float(compilationUnit->bindingValueAsNumber(binding)));
617 property->writeProperty(_qobject, &value, propertyWriteFlags);
618 break;
619 } else if (propertyType == QMetaType::fromType<QList<int>>()) {
620 assertType(QV4::CompiledData::Binding::Type_Number);
621 double n = compilationUnit->bindingValueAsNumber(binding);
622 QList<int> value;
623 value.append(int(n));
624 property->writeProperty(_qobject, &value, propertyWriteFlags);
625 break;
626 } else if (propertyType == QMetaType::fromType<QList<bool>>()) {
627 assertType(QV4::CompiledData::Binding::Type_Boolean);
628 QList<bool> value;
629 value.append(binding->valueAsBoolean());
630 property->writeProperty(_qobject, &value, propertyWriteFlags);
631 break;
632 } else if (propertyType == QMetaType::fromType<QList<QUrl>>()) {
633 assertType(QV4::CompiledData::Binding::Type_String);
634 const QUrl url(compilationUnit->bindingValueAsString(binding));
635 QList<QUrl> value {
636 QQmlPropertyPrivate::resolveUrlsOnAssignment()
637 ? compilationUnit->finalUrl().resolved(url)
638 : url
639 };
640 property->writeProperty(_qobject, &value, propertyWriteFlags);
641 break;
642 } else if (propertyType == QMetaType::fromType<QList<QString>>()) {
643 assertOrNull(binding->evaluatesToString());
644 QList<QString> value;
645 value.append(compilationUnit->bindingValueAsString(binding));
646 property->writeProperty(_qobject, &value, propertyWriteFlags);
647 break;
648 } else if (propertyType == QMetaType::fromType<QJSValue>()) {
649 QJSValue value;
650 switch (binding->type()) {
651 case QV4::CompiledData::Binding::Type_Boolean:
652 value = QJSValue(binding->valueAsBoolean());
653 break;
654 case QV4::CompiledData::Binding::Type_Number: {
655 const double n = compilationUnit->bindingValueAsNumber(binding);
656 if (double(int(n)) == n)
657 value = QJSValue(int(n));
658 else
659 value = QJSValue(n);
660 break;
661 }
662 case QV4::CompiledData::Binding::Type_Null:
663 value = QJSValue::NullValue;
664 break;
665 default:
666 value = QJSValue(compilationUnit->bindingValueAsString(binding));
667 break;
668 }
669 property->writeProperty(_qobject, &value, propertyWriteFlags);
670 break;
671 } else {
672 QVariant source;
673 switch (binding->type()) {
674 case QV4::CompiledData::Binding::Type_Boolean:
675 source = binding->valueAsBoolean();
676 break;
677 case QV4::CompiledData::Binding::Type_Number: {
678 const double n = compilationUnit->bindingValueAsNumber(binding);
679 if (double(int(n)) == n)
680 source = int(n);
681 else
682 source = n;
683 break;
684 }
685 case QV4::CompiledData::Binding::Type_Null:
686 source = QVariant::fromValue<std::nullptr_t>(nullptr);
687 break;
688 case QV4::CompiledData::Binding::Type_Invalid:
689 break;
690 default:
691 source = compilationUnit->bindingValueAsString(binding);
692 break;
693 }
694
695 QVariant target = QQmlValueTypeProvider::createValueType(
696 source, propertyType, engine->handle());
697 if (target.isValid()) {
698 property->writeProperty(_qobject, target.data(), propertyWriteFlags);
699 break;
700 }
701 }
702
703 // string converters are not exposed, so ending up here indicates an error
704 QString stringValue = compilationUnit->bindingValueAsString(binding);
705 QMetaProperty metaProperty = _qobject->metaObject()->property(property->coreIndex());
706 recordError(binding->location, tr("Cannot assign value %1 to property"
707" %2").arg(stringValue, QString::fromUtf8(metaProperty.name())));
708 }
709 break;
710 }
711}
712
713static QQmlType qmlTypeForObject(QObject *object)
714{
715 QQmlType type;
716 const QMetaObject *mo = object->metaObject();
717 while (mo && !type.isValid()) {
718 type = QQmlMetaType::qmlType(mo);
719 mo = mo->superClass();
720 }
721 return type;
722}
723
724void QQmlObjectCreator::setupBindings(BindingSetupFlags mode)
725{
726 QQmlListProperty<QObject> savedList;
727 qSwap(_currentList, savedList);
728
729 const QV4::CompiledData::BindingPropertyData *propertyData
730 = compilationUnit->bindingPropertyDataPerObjectAt(_compiledObjectIndex);
731
732 if (_compiledObject->idNameIndex) {
733 const QQmlPropertyData *idProperty = propertyData->last();
734 Q_ASSERT(!idProperty || !idProperty->isValid() || idProperty->name(_qobject) == QLatin1String("id"));
735 if (idProperty && idProperty->isValid() && idProperty->isWritable() && idProperty->propType().id() == QMetaType::QString) {
736 QV4::CompiledData::Binding idBinding;
737 idBinding.propertyNameIndex = 0; // Not used
738 idBinding.clearFlags();
739 idBinding.setType(QV4::CompiledData::Binding::Type_String);
740 idBinding.stringIndex = _compiledObject->idNameIndex;
741 idBinding.location = _compiledObject->location; // ###
742 idBinding.value.nullMarker = 0; // zero the value field to make codechecker happy
743 setPropertyValue(idProperty, &idBinding);
744 }
745 }
746
747 // ### this is best done through type-compile-time binding skip lists.
748 if (_valueTypeProperty) {
749 QQmlAbstractBinding *binding = QQmlPropertyPrivate::binding(_bindingTarget, QQmlPropertyIndex(_valueTypeProperty->coreIndex()));
750
751 if (binding && binding->kind() != QQmlAbstractBinding::ValueTypeProxy) {
752 QQmlPropertyPrivate::removeBinding(
753 _bindingTarget, QQmlPropertyIndex(_valueTypeProperty->coreIndex()),
754 QQmlPropertyPrivate::OverrideSticky);
755 } else if (binding) {
756 QQmlValueTypeProxyBinding *proxy = static_cast<QQmlValueTypeProxyBinding *>(binding);
757
758 if (qmlTypeForObject(_bindingTarget).isValid()) {
759 quint32 bindingSkipList = 0;
760
761 const QQmlPropertyData *defaultProperty = _compiledObject->indexOfDefaultPropertyOrAlias != -1 ? _propertyCache->parent()->defaultProperty() : _propertyCache->defaultProperty();
762
763 const QV4::CompiledData::Binding *binding = _compiledObject->bindingTable();
764 for (quint32 i = 0; i < _compiledObject->nBindings; ++i, ++binding) {
765 const QQmlPropertyData *property = binding->propertyNameIndex != 0
766 ? _propertyCache->property(stringAt(binding->propertyNameIndex),
767 _qobject, context)
768 : defaultProperty;
769 if (property)
770 bindingSkipList |= (1 << property->coreIndex());
771 }
772
773 proxy->removeBindings(bindingSkipList);
774 }
775 }
776 }
777
778 const QQmlPropertyData *defaultProperty = _compiledObject->indexOfDefaultPropertyOrAlias != -1
779 ? _propertyCache->parent()->defaultProperty()
780 : _propertyCache->defaultProperty();
781
782 int currentListPropertyIndex = -1;
783
784 // Prepare list property state and call setPropertyBinding for one binding.
785 const auto applyBinding = [&](const QQmlPropertyData *property,
786 const QV4::CompiledData::Binding *binding) -> bool {
787 if (property && property->propType().flags().testFlag(QMetaType::IsQmlList)) {
788 if (property->coreIndex() != currentListPropertyIndex) {
789 void *argv[1] = { (void*)&_currentList };
790 QMetaObject::metacall(_qobject, QMetaObject::ReadProperty, property->coreIndex(), argv);
791 currentListPropertyIndex = property->coreIndex();
792
793 // manage override behavior
794 const QMetaObject *const metaobject = _qobject->metaObject();
795 const int qmlListBehavorClassInfoIndex = metaobject->indexOfClassInfo("QML.ListPropertyAssignBehavior");
796 if (qmlListBehavorClassInfoIndex != -1) { // QML.ListPropertyAssignBehavior class info is set
797 const char *overrideBehavior =
798 metaobject->classInfo(qmlListBehavorClassInfoIndex).value();
799 if (!strcmp(overrideBehavior,
800 "Replace")) {
801 if (_currentList.clear) {
802 _currentList.clear(&_currentList);
803 }
804 } else {
805 bool isDefaultProperty =
806 (property->name(_qobject)
807 == QString::fromUtf8(
808 metaobject
809 ->classInfo(metaobject->indexOfClassInfo(
810 "DefaultProperty"))
811 .value()));
812 if (!isDefaultProperty
813 && (!strcmp(overrideBehavior,
814 "ReplaceIfNotDefault"))) {
815 if (_currentList.clear) {
816 _currentList.clear(&_currentList);
817 }
818 }
819 }
820 }
821 }
822 } else if (_currentList.object) {
823 _currentList = QQmlListProperty<QObject>();
824 currentListPropertyIndex = -1;
825 }
826
827 return setPropertyBinding(property, binding);
828 };
829
830 // Explicit default property bindings (propertyNameIndex != 0 but resolving
831 // to the default property) are deferred during iteration and applied in file-offset order once
832 // we reach the implicit default bindings (propertyNameIndex == 0).
833 QVarLengthArray<const QV4::CompiledData::Binding *, 8> explicitDefaultPropertyBindings;
834
835 const auto applyExplicitDefaultPropertyBindings = [&]() -> bool {
836 for (const QV4::CompiledData::Binding *b : std::as_const(explicitDefaultPropertyBindings)) {
837 if (!applyBinding(defaultProperty, b))
838 return false;
839 }
840 explicitDefaultPropertyBindings.clear();
841 return true;
842 };
843
844 const QV4::CompiledData::RuntimeBindingIndex *bindingOrder =
845 compilationUnit->bindingApplicationOrder(_compiledObjectIndex);
846 for (quint32 k = 0; k < _compiledObject->nBindings; ++k) {
847 const quint32 i = bindingOrder[k];
848 const QV4::CompiledData::Binding *binding = _compiledObject->bindingTable() + i;
849 const QQmlPropertyData *const property = propertyData->at(i);
850 if (property) {
851 const QQmlPropertyData *targetProperty = property;
852 if (targetProperty->isAlias()) {
853 // follow alias
854 QQmlPropertyIndex originalIndex(targetProperty->coreIndex(),
855 _valueTypeProperty ? _valueTypeProperty->coreIndex()
856 : -1);
857 auto [targetObject, targetIndex] =
858 QQmlPropertyPrivate::findAliasTarget(_bindingTarget, originalIndex);
859 QQmlData *data = QQmlData::get(targetObject);
860 Q_ASSERT(data && data->propertyCache);
861 targetProperty = data->propertyCache->property(targetIndex.coreIndex());
862 sharedState->requiredProperties.remove({ targetObject, targetProperty });
863 }
864 sharedState->requiredProperties.remove({ _bindingTarget, property });
865 }
866
867 if (compilationUnit->bindingIsCustomParser(_compiledObjectIndex, i))
868 continue;
869
870 if (compilationUnit->bindingIsDeferred(_compiledObjectIndex, i)) {
871 if (!(mode & ApplyDeferred))
872 continue;
873 } else if (!(mode & ApplyImmediate)) {
874 continue;
875 }
876
877 // Defer explicit bindings to the default property until we reach the
878 // implicit default bindings, where they will be interleaved by offset.
879 if (binding->propertyNameIndex != quint32(0)
880 && defaultProperty
881 && property == defaultProperty) {
882 explicitDefaultPropertyBindings.append(binding);
883 continue;
884 }
885
886 // Flush deferred explicit default bindings if file offset is <= the
887 // current implicit default binding's offset.
888 if (binding->propertyNameIndex == quint32(0)
889 && !explicitDefaultPropertyBindings.isEmpty()
890 && !(binding->location < explicitDefaultPropertyBindings.first()->location)) {
891 if (!applyExplicitDefaultPropertyBindings())
892 return;
893 }
894
895 if (!applyBinding(property, binding))
896 return;
897 }
898
899 // Flush any remaining deferred explicit default bindings.
900 if (!applyExplicitDefaultPropertyBindings())
901 return;
902 qSwap(_currentList, savedList);
903}
904
905bool QQmlObjectCreator::setPropertyBinding(const QQmlPropertyData *bindingProperty, const QV4::CompiledData::Binding *binding)
906{
907 const int bindingIndex = int(binding - _compiledObject->bindingTable());
908 const std::optional<int> foldedNumber
909 = compilationUnit->bindingFoldedEnum(_compiledObjectIndex, bindingIndex);
910 const QV4::CompiledData::Binding::Type bindingType = binding->type();
911 if (bindingType == QV4::CompiledData::Binding::Type_AttachedProperty) {
912 const QV4::CompiledData::Object *obj = compilationUnit->objectAt(binding->value.objectIndex);
913 QQmlObjectCreationProfiler profiler(sharedState->profiler.profiler, obj);
914
915 Q_ASSERT(stringAt(obj->inheritedTypeNameIndex).isEmpty());
916 QV4::ResolvedTypeReference *tr = resolvedType(binding->propertyNameIndex);
917 Q_ASSERT(tr);
918 QQmlType attachedType = tr->type();
919 QQmlTypeLoader *typeLoader = QQmlTypeLoader::get(engine);
920 if (!attachedType.isValid()) {
921 QQmlTypeNameCache::Result res
922 = context->imports()->query(stringAt(binding->propertyNameIndex), typeLoader);
923 if (res.isValid())
924 attachedType = res.type;
925 else
926 return false;
927 }
928
929 Q_QML_OC_PROFILE(
930 sharedState->profiler,
931 profiler.update(compilationUnit.data(), obj, attachedType.qmlTypeName(),
932 context->url()));
933
934 QObject *qmlObject = qmlAttachedPropertiesObject(
935 _qobject, attachedType.attachedPropertiesFunction(typeLoader));
936 if (!qmlObject) {
937 recordError(binding->location,
938 QStringLiteral("Could not create attached properties object '%1'")
939 .arg(QString::fromUtf8(attachedType.typeName())));
940 return false;
941 }
942
943 const size_t objectIndex = sharedState->allCreatedObjects.size();
944 sharedState->allCreatedObjects.push_back(qmlObject);
945 const QQmlType attachedObjectType
946 = QQmlMetaType::qmlType(attachedType.attachedPropertiesType(typeLoader));
947 const int parserStatusCast = attachedObjectType.parserStatusCast();
948 QQmlParserStatus *parserStatus = nullptr;
949 if (parserStatusCast != -1)
950 parserStatus = reinterpret_cast<QQmlParserStatus*>(reinterpret_cast<char *>(qmlObject) + parserStatusCast);
951 if (parserStatus) {
952 parserStatus->classBegin();
953 // we ignore them for profiling, because it doesn't interact well with the logic anyway
954 sharedState->allParserStatusCallbacks.push_back({objectIndex, parserStatusCast});
955 }
956
957 if (!populateInstance(binding->value.objectIndex, qmlObject, qmlObject,
958 /*value type property*/ nullptr, binding))
959 return false;
960 return true;
961 }
962
963 // ### resolve this at compile time
964 if (bindingProperty && bindingProperty->propType() == QMetaType::fromType<QQmlScriptString>()) {
965 QQmlScriptString ss(compilationUnit->bindingValueAsScriptString(binding),
966 context->asQQmlContext(), _scopeObject);
967 ss.d.data()->bindingId = bindingType == QV4::CompiledData::Binding::Type_Script ? binding->value.compiledScriptIndex : (quint32)QQmlBinding::Invalid;
968 ss.d.data()->lineNumber = binding->location.line();
969 ss.d.data()->columnNumber = binding->location.column();
970 ss.d.data()->isStringLiteral = bindingType == QV4::CompiledData::Binding::Type_String;
971 ss.d.data()->isNumberLiteral = bindingType == QV4::CompiledData::Binding::Type_Number;
972 ss.d.data()->numberValue = compilationUnit->bindingValueAsNumber(binding);
973
974 QQmlPropertyData::WriteFlags propertyWriteFlags = QQmlPropertyData::BypassInterceptor |
975 QQmlPropertyData::RemoveBindingOnAliasWrite;
976 int propertyWriteStatus = -1;
977 void *argv[] = { &ss, nullptr, &propertyWriteStatus, &propertyWriteFlags };
978 QMetaObject::metacall(_qobject, QMetaObject::WriteProperty, bindingProperty->coreIndex(), argv);
979 return true;
980 }
981
982 QObject *createdSubObject = nullptr;
983 if (bindingType == QV4::CompiledData::Binding::Type_Object) {
984 // This is not a top level object. Its required properties don't count towards the
985 // top level required properties.
986 QScopedValueRollback topLevelRequired(sharedState->hadTopLevelRequiredProperties);
987 int objectIndex = binding->value.objectIndex;
988 if (const int wrapperIdx = compilationUnit->implicitComponentForObject(objectIndex);
989 wrapperIdx != -1) {
990 // If the child has an implicit component wrapper, redirect to it.
991 objectIndex = wrapperIdx;
992 }
993 createdSubObject = createInstance(objectIndex, _bindingTarget);
994 if (!createdSubObject)
995 return false;
996 }
997
998 if (bindingType == QV4::CompiledData::Binding::Type_GroupedProperty) {
999 const QV4::CompiledData::Object *obj = compilationUnit->objectAt(binding->value.objectIndex);
1000 if (stringAt(obj->inheritedTypeNameIndex).isEmpty()) {
1001
1002 QObject *groupObject = nullptr;
1003 QQmlGadgetPtrWrapper *valueType = nullptr;
1004 const QQmlPropertyData *valueTypeProperty = nullptr;
1005 QObject *bindingTarget = _bindingTarget;
1006 int groupObjectIndex = binding->value.objectIndex;
1007
1008 if (!bindingProperty) {
1009 for (int i = 0, end = compilationUnit->objectCount(); i != end; ++i) {
1010 const QV4::CompiledData::Object *external = compilationUnit->objectAt(i);
1011 if (external->idNameIndex == binding->propertyNameIndex) {
1012 bindingTarget = groupObject = context->idValue(compilationUnit->objectId(i));
1013 break;
1014 }
1015 }
1016 if (!groupObject)
1017 return true;
1018 } else if (QQmlMetaType::isValueType(bindingProperty->propType())) {
1019 valueType = QQmlGadgetPtrWrapper::instance(engine, bindingProperty->propType());
1020 if (!valueType) {
1021 recordError(binding->location, tr("Cannot set properties on %1 as it is null").arg(stringAt(binding->propertyNameIndex)));
1022 return false;
1023 }
1024
1025 valueType->read(_qobject, bindingProperty->coreIndex());
1026
1027 groupObject = valueType;
1028 valueTypeProperty = bindingProperty;
1029 } else if (bindingProperty->propType().flags() & QMetaType::PointerToQObject) {
1030 void *argv[1] = { &groupObject };
1031 QMetaObject::metacall(_qobject, QMetaObject::ReadProperty, bindingProperty->coreIndex(), argv);
1032 if (!groupObject) {
1033 QQmlPropertyIndex index(bindingProperty->coreIndex());
1034 auto anyBinding = QQmlAnyBinding::ofProperty(_qobject, index);
1035 if (anyBinding) {
1036 // if there is a binding, try to force-evaluate it now
1037 // this might instantiate a necessary part of a grouped property
1038 anyBinding.refresh();
1039 QMetaObject::metacall(_qobject, QMetaObject::ReadProperty, bindingProperty->coreIndex(), argv);
1040 }
1041 if (!groupObject) {
1042 recordError(binding->location, tr("Cannot set properties on %1 as it is null").arg(stringAt(binding->propertyNameIndex)));
1043 return false;
1044 }
1045 }
1046
1047 bindingTarget = groupObject;
1048 } else {
1049 recordError(
1050 binding->location,
1051 tr("Using grouped property syntax on %1 which has no properties")
1052 .arg(stringAt(binding->propertyNameIndex)));
1053 return false;
1054 }
1055
1056 if (!populateInstance(groupObjectIndex, groupObject, bindingTarget, valueTypeProperty,
1057 binding)) {
1058 return false;
1059 }
1060
1061 if (valueType) {
1062 valueType->write(
1063 _qobject, bindingProperty->coreIndex(),
1064 QQmlPropertyData::BypassInterceptor,
1065 QV4::ReferenceObject::AllProperties);
1066 }
1067
1068 return true;
1069 }
1070 }
1071
1072 if (!bindingProperty) // ### error
1073 return true;
1074
1075 const QV4::CompiledData::Binding::Flags bindingFlags = binding->flags();
1076 const bool allowedToRemoveBinding
1077 = !compilationUnit->bindingIsSignalHandlerExpression(_compiledObjectIndex, bindingIndex)
1078 && !(bindingFlags & QV4::CompiledData::Binding::IsOnAssignment)
1079 && !compilationUnit->bindingIsPropertyObserver(_compiledObjectIndex, bindingIndex)
1080 && !_valueTypeProperty;
1081
1082 if (allowedToRemoveBinding) {
1083 if (bindingProperty->acceptsQBinding()) {
1084 removePendingBinding(_bindingTarget, bindingProperty->coreIndex());
1085 } else {
1086 QQmlPropertyPrivate::removeBinding(
1087 _bindingTarget, QQmlPropertyIndex(bindingProperty->coreIndex()),
1088 QQmlPropertyPrivate::OverrideSticky);
1089 }
1090 }
1091
1092 if (!foldedNumber
1093 && (bindingType == QV4::CompiledData::Binding::Type_Script || binding->isTranslationBinding())) {
1094 if (compilationUnit->bindingIsSignalHandlerExpression(_compiledObjectIndex, bindingIndex)
1095 || compilationUnit->bindingIsPropertyObserver(_compiledObjectIndex, bindingIndex)) {
1096 QV4::Function *runtimeFunction = compilationUnit->runtimeFunctions[binding->value.compiledScriptIndex];
1097 int signalIndex = _propertyCache->methodIndexToSignalIndex(bindingProperty->coreIndex());
1098 QQmlBoundSignalExpression *expr = new QQmlBoundSignalExpression(
1099 _bindingTarget, signalIndex, context,
1100 _scopeObject, runtimeFunction, currentQmlContext());
1101
1102 if (bindingProperty->notifiesViaBindable()) {
1103 auto target = _bindingTarget;
1104 if (bindingProperty->isAlias()) {
1105 // If the property is an alias, we cannot obtain the bindable interface directly with qt_metacall
1106 // so instead, we resolve the alias to obtain the actual target
1107 // This should be faster than doing a detour through the metaobject of the target, and relying on
1108 // QMetaObject::metacall doing the correct resolution
1109 QQmlPropertyIndex originalIndex(bindingProperty->coreIndex(), _valueTypeProperty ? _valueTypeProperty->coreIndex() : -1);
1110 auto [aliasTargetObject, aliasTargetIndex] = QQmlPropertyPrivate::findAliasTarget(target, originalIndex);
1111 target = aliasTargetObject;
1112 QQmlData *data = QQmlData::get(target);
1113 Q_ASSERT(data && data->propertyCache);
1114 bindingProperty = data->propertyCache->property(aliasTargetIndex.coreIndex());
1115 }
1116 auto &observer = QQmlData::get(_scopeObject)->propertyObservers.emplace_back(expr);
1117 QUntypedBindable bindable;
1118 void *argv[] = { &bindable };
1119 target->qt_metacall(QMetaObject::BindableProperty, bindingProperty->coreIndex(), argv);
1120 Q_ASSERT(bindable.isValid());
1121 bindable.observe(&observer);
1122 } else {
1123 QQmlBoundSignal *bs = new QQmlBoundSignal(_bindingTarget, signalIndex, _scopeObject, engine);
1124 bs->takeExpression(expr);
1125 }
1126 } else if (bindingProperty->acceptsQBinding()) {
1127 QUntypedPropertyBinding qmlBinding;
1128 if (binding->isTranslationBinding()) {
1129 qmlBinding = QQmlTranslationPropertyBinding::create(bindingProperty, compilationUnit, binding);
1130 } else {
1131 QV4::Function *runtimeFunction = compilationUnit->runtimeFunctions[binding->value.compiledScriptIndex];
1132 QQmlPropertyIndex index(bindingProperty->coreIndex(), -1);
1133 qmlBinding = QQmlPropertyBinding::create(bindingProperty, runtimeFunction, _scopeObject, context, currentQmlContext(), _bindingTarget, index);
1134 }
1135 sharedState.data()->allQPropertyBindings.push_back(DeferredQPropertyBinding {_bindingTarget, bindingProperty->coreIndex(), qmlBinding });
1136
1137 QQmlData *data = QQmlData::get(_bindingTarget, true);
1138 data->setBindingBit(_bindingTarget, bindingProperty->coreIndex());
1139 } else {
1140 // When writing bindings to grouped properties implemented as value types,
1141 // such as point.x: { someExpression; }, then the binding is installed on
1142 // the point property (_qobjectForBindings) and after evaluating the expression,
1143 // the result is written to a value type virtual property, that contains the sub-index
1144 // of the "x" property.
1145 QQmlBinding::Ptr qmlBinding;
1146 const QQmlPropertyData *targetProperty = bindingProperty;
1147 const QQmlPropertyData *subprop = nullptr;
1148 if (_valueTypeProperty) {
1149 targetProperty = _valueTypeProperty;
1150 subprop = bindingProperty;
1151 }
1152 if (binding->isTranslationBinding()) {
1153 qmlBinding = QQmlBinding::createTranslationBinding(
1154 compilationUnit, binding, _scopeObject, context);
1155 } else {
1156 QV4::Function *runtimeFunction = compilationUnit->runtimeFunctions[binding->value.compiledScriptIndex];
1157 qmlBinding = QQmlBinding::create(targetProperty, runtimeFunction, _scopeObject,
1158 context, currentQmlContext());
1159 }
1160
1161 auto bindingTarget = _bindingTarget;
1162 auto valueTypeProperty = _valueTypeProperty;
1163 auto assignBinding = [qmlBinding, bindingTarget, targetProperty, subprop, bindingProperty, valueTypeProperty](QQmlObjectCreatorSharedState *sharedState) mutable -> bool {
1164 if (!qmlBinding->setTarget(bindingTarget, *targetProperty, subprop) && targetProperty->isAlias())
1165 return false;
1166
1167 sharedState->allCreatedBindings.push_back(qmlBinding);
1168
1169 if (bindingProperty->isAlias()) {
1170 QQmlPropertyPrivate::setBinding(qmlBinding.data(), QQmlPropertyPrivate::DontEnable);
1171 } else {
1172 qmlBinding->addToObject();
1173
1174 if (!valueTypeProperty) {
1175 QQmlData *targetDeclarativeData = QQmlData::get(bindingTarget);
1176 Q_ASSERT(targetDeclarativeData);
1177 targetDeclarativeData->setPendingBindingBit(bindingTarget, bindingProperty->coreIndex());
1178 }
1179 }
1180
1181 return true;
1182 };
1183 if (!assignBinding(sharedState.data()))
1184 pendingAliasBindings.push_back(assignBinding);
1185 }
1186 return true;
1187 }
1188
1189 if (bindingType == QV4::CompiledData::Binding::Type_Object) {
1190 if (bindingFlags & QV4::CompiledData::Binding::IsOnAssignment) {
1191 // ### determine value source and interceptor casts ahead of time.
1192 QQmlType type = qmlTypeForObject(createdSubObject);
1193 Q_ASSERT(type.isValid());
1194
1195 int valueSourceCast = type.propertyValueSourceCast();
1196 if (valueSourceCast != -1) {
1197 QQmlPropertyValueSource *vs = reinterpret_cast<QQmlPropertyValueSource *>(reinterpret_cast<char *>(createdSubObject) + valueSourceCast);
1198 QObject *target = createdSubObject->parent();
1199 QQmlProperty prop;
1200 if (_valueTypeProperty) {
1201 prop = QQmlPropertyPrivate::restore(target, *_valueTypeProperty,
1202 bindingProperty, context);
1203 } else {
1204 prop = QQmlPropertyPrivate::restore(target, *bindingProperty, nullptr, context);
1205 }
1206 vs->setTarget(prop);
1207 return true;
1208 }
1209 int valueInterceptorCast = type.propertyValueInterceptorCast();
1210 if (valueInterceptorCast != -1) {
1211 QQmlPropertyValueInterceptor *vi = reinterpret_cast<QQmlPropertyValueInterceptor *>(reinterpret_cast<char *>(createdSubObject) + valueInterceptorCast);
1212 QObject *target = createdSubObject->parent();
1213
1214 QQmlPropertyIndex propertyIndex;
1215 if (bindingProperty->isAlias()) {
1216 QQmlPropertyIndex originalIndex(bindingProperty->coreIndex(), _valueTypeProperty ? _valueTypeProperty->coreIndex() : -1);
1217 auto aliasTarget = QQmlPropertyPrivate::findAliasTarget(target, originalIndex);
1218 target = aliasTarget.targetObject;
1219 QQmlData *data = QQmlData::get(target);
1220 if (!data || !data->propertyCache) {
1221 qWarning() << "can't resolve property alias for 'on' assignment";
1222 return false;
1223 }
1224
1225 // we can't have aliasses on subproperties of value types, so:
1226 QQmlPropertyData targetPropertyData = *data->propertyCache->property(aliasTarget.targetIndex.coreIndex());
1227 auto prop = QQmlPropertyPrivate::restore(
1228 target, targetPropertyData, nullptr, context);
1229 vi->setTarget(prop);
1230 propertyIndex = QQmlPropertyPrivate::propertyIndex(prop);
1231 } else {
1232 QQmlProperty prop;
1233 if (_valueTypeProperty) {
1234 prop = QQmlPropertyPrivate::restore(
1235 target, *_valueTypeProperty, bindingProperty, context);
1236 } else {
1237 prop = QQmlPropertyPrivate::restore(
1238 target, *bindingProperty, nullptr, context);
1239 }
1240 vi->setTarget(prop);
1241 propertyIndex = QQmlPropertyPrivate::propertyIndex(prop);
1242 }
1243
1244 QQmlInterceptorMetaObject *mo = QQmlInterceptorMetaObject::get(target);
1245 if (!mo)
1246 mo = new QQmlInterceptorMetaObject(target, QQmlData::get(target)->propertyCache);
1247 mo->registerInterceptor(propertyIndex, vi);
1248 return true;
1249 }
1250 return false;
1251 }
1252
1253 // Assigning object to signal property? ### Qt 7: Remove that functionality
1254 if (compilationUnit->bindingIsSignalHandlerObject(_compiledObjectIndex, bindingIndex)) {
1255 if (!bindingProperty->isFunction()) {
1256 recordError(binding->valueLocation, tr("Cannot assign an object to signal property %1").arg(bindingProperty->name(_qobject)));
1257 return false;
1258 }
1259 QMetaMethod method = QQmlMetaType::defaultMethod(createdSubObject);
1260 if (!method.isValid()) {
1261 recordError(binding->valueLocation, tr("Cannot assign object type %1 with no default method").arg(QString::fromLatin1(createdSubObject->metaObject()->className())));
1262 return false;
1263 }
1264 qCWarning(lcQmlDefaultMethod) << "Assigning an object to a signal handler is deprecated. "
1265 "Instead, create the object, give it an id, and call the desired slot "
1266 "from the signal handler. The object is:" << createdSubObject;
1267
1268 QMetaMethod signalMethod = _qobject->metaObject()->method(bindingProperty->coreIndex());
1269 if (!QMetaObject::checkConnectArgs(signalMethod, method)) {
1270 recordError(binding->valueLocation,
1271 tr("Cannot connect mismatched signal/slot %1 vs %2")
1272 .arg(QString::fromUtf8(method.methodSignature()),
1273 QString::fromUtf8(signalMethod.methodSignature())));
1274 return false;
1275 }
1276
1277 QQmlPropertyPrivate::connect(_qobject, bindingProperty->coreIndex(), createdSubObject, method.methodIndex());
1278 return true;
1279 }
1280
1281 QQmlPropertyData::WriteFlags propertyWriteFlags = QQmlPropertyData::BypassInterceptor |
1282 QQmlPropertyData::RemoveBindingOnAliasWrite;
1283 int propertyWriteStatus = -1;
1284 void *argv[] = { nullptr, nullptr, &propertyWriteStatus, &propertyWriteFlags };
1285
1286 if (const char *iid = QQmlMetaType::interfaceIId(bindingProperty->propType())) {
1287 void *ptr = createdSubObject->qt_metacast(iid);
1288 if (ptr) {
1289 argv[0] = &ptr;
1290 QMetaObject::metacall(_qobject, QMetaObject::WriteProperty, bindingProperty->coreIndex(), argv);
1291 } else {
1292 recordError(binding->location, tr("Cannot assign object to interface property"));
1293 return false;
1294 }
1295 } else if (bindingProperty->propType() == QMetaType::fromType<QVariant>()) {
1296 if (bindingProperty->isVarProperty()) {
1297 QV4::Scope scope(v4);
1298 QV4::ScopedValue wrappedObject(scope, QV4::QObjectWrapper::wrap(engine->handle(), createdSubObject));
1299 _vmeMetaObject->setVMEProperty(bindingProperty->coreIndex(), wrappedObject);
1300 } else {
1301 QVariant value = QVariant::fromValue(createdSubObject);
1302 argv[0] = &value;
1303 QMetaObject::metacall(_qobject, QMetaObject::WriteProperty, bindingProperty->coreIndex(), argv);
1304 }
1305 } else if (bindingProperty->propType() == QMetaType::fromType<QJSValue>()) {
1306 QV4::Scope scope(v4);
1307 QV4::ScopedValue wrappedObject(scope, QV4::QObjectWrapper::wrap(engine->handle(), createdSubObject));
1308 if (bindingProperty->isVarProperty()) {
1309 _vmeMetaObject->setVMEProperty(bindingProperty->coreIndex(), wrappedObject);
1310 } else {
1311 QJSValue value;
1312 QJSValuePrivate::setValue(&value, wrappedObject);
1313 argv[0] = &value;
1314 QMetaObject::metacall(_qobject, QMetaObject::WriteProperty, bindingProperty->coreIndex(), argv);
1315 }
1316 } else if (bindingProperty->propType().flags().testFlag(QMetaType::IsQmlList)) {
1317 Q_ASSERT(_currentList.object);
1318
1319 QObject *itemToAdd = createdSubObject;
1320
1321 QMetaType listItemType = QQmlMetaType::listValueType(bindingProperty->propType());
1322 if (listItemType.isValid()) {
1323 const char *iid = QQmlMetaType::interfaceIId(listItemType);
1324 if (iid)
1325 itemToAdd = static_cast<QObject *>(createdSubObject->qt_metacast(iid));
1326 }
1327
1328 if (_currentList.append)
1329 _currentList.append(&_currentList, itemToAdd);
1330 else {
1331 recordError(binding->location, tr("Cannot assign object to read only list"));
1332 return false;
1333 }
1334 } else if (bindingProperty->propType().flags().testFlag(QMetaType::PointerToQObject)) {
1335 // pointer compatibility was tested in QQmlPropertyValidator at type compile time
1336 argv[0] = &createdSubObject;
1337 QMetaObject::metacall(_qobject, QMetaObject::WriteProperty, bindingProperty->coreIndex(), argv);
1338 } else {
1339 QVariant target = QQmlValueTypeProvider::createValueType(
1340 QVariant::fromValue(createdSubObject), bindingProperty->propType(), v4);
1341 if (target.isValid())
1342 bindingProperty->writeProperty(_qobject, target.data(), propertyWriteFlags);
1343 else
1344 recordError(binding->location, tr("Cannot construct value type from given object"));
1345 }
1346 return true;
1347 }
1348
1349 if (bindingProperty->isQList()) {
1350 recordError(binding->location, tr("Cannot assign primitives to lists"));
1351 return false;
1352 }
1353
1354 setPropertyValue(bindingProperty, binding, foldedNumber);
1355 return true;
1356}
1357
1358void QQmlObjectCreator::setupFunctions()
1359{
1360 QV4::Scope scope(v4);
1361 QV4::ScopedValue function(scope);
1362 QV4::ScopedContext qmlContext(scope, currentQmlContext());
1363
1364 const quint32_le *functionIdx = _compiledObject->functionOffsetTable();
1365 for (quint32 i = 0; i < _compiledObject->nFunctions; ++i, ++functionIdx) {
1366 QV4::Function *runtimeFunction = compilationUnit->runtimeFunctions[*functionIdx];
1367 const QString name = runtimeFunction->name()->toQString();
1368
1369 const QQmlPropertyData *property = _propertyCache->property(name, _qobject, context);
1370 if (!property->isVMEFunction())
1371 continue;
1372
1373 if (runtimeFunction->isGenerator())
1374 function = QV4::GeneratorFunction::create(qmlContext, runtimeFunction);
1375 else
1376 function = QV4::FunctionObject::createScriptFunction(qmlContext, runtimeFunction);
1377 _vmeMetaObject->setVmeMethod(property->coreIndex(), function);
1378 }
1379}
1380
1381void QQmlObjectCreator::recordError(const QV4::CompiledData::Location &location, const QString &description)
1382{
1383 QQmlError error;
1384 error.setUrl(compilationUnit->url());
1385 error.setLine(qmlConvertSourceCoordinate<quint32, int>(location.line()));
1386 error.setColumn(qmlConvertSourceCoordinate<quint32, int>(location.column()));
1387 error.setDescription(description);
1388 errors << error;
1389}
1390
1391void QQmlObjectCreator::registerObjectWithContextById(int objectIndex, QObject *instance) const
1392{
1393 if (const int id = compilationUnit->objectId(objectIndex); id >= 0)
1394 context->setIdValue(id, instance);
1395}
1396
1397QObject *QQmlObjectCreator::createInstance(int index, QObject *parent, bool isContextObject)
1398{
1399 const QV4::CompiledData::Object *obj = compilationUnit->objectAt(index);
1400 Q_TRACE(QQmlObjectCreator_createInstance_entry, compilationUnit.data(), obj, context->url());
1401 QQmlObjectCreationProfiler profiler(sharedState->profiler.profiler, obj);
1402
1403 const bool isImplicitComponent = index >= compilationUnit->objectCount();
1404 const InitFlags flags = (isContextObject ? InitFlag::IsContextObject : InitFlag::None)
1405 | (index == 0 ? InitFlag::IsDocumentRoot : InitFlag::None)
1406 | (isImplicitComponent ? InitFlag::IsImplicitComponent : InitFlag::None);
1407
1408 if (compilationUnit->objectIsComponent(index) || isImplicitComponent) {
1409 Q_TRACE_EXIT(QQmlObjectCreator_createInstance_exit, QStringLiteral("<component>"));
1410 Q_QML_OC_PROFILE(
1411 sharedState->profiler,
1412 profiler.update(
1413 compilationUnit.data(), obj, QStringLiteral("<component>"),
1414 context->url()));
1415 return initializeComponent(
1416 index, obj,
1417 createComponent(engine, compilationUnit.data(), index, parent, context), flags);
1418 }
1419
1420 const QV4::ResolvedTypeReference *typeRef = resolvedType(obj->inheritedTypeNameIndex);
1421 Q_ASSERT(typeRef);
1422 const QQmlType type = typeRef->type();
1423 Q_ASSERT(type.isValid());
1424
1425 Q_TRACE_EXIT(QQmlObjectCreator_createInstance_exit, type.qmlTypeName());
1426 Q_QML_OC_PROFILE(
1427 sharedState->profiler,
1428 profiler.update(compilationUnit.data(), obj, type.qmlTypeName(), context->url()));
1429
1430 if (type.isCompositeSingleton()) {
1431 recordError(
1432 obj->location,
1433 tr("Composite Singleton Type %1 is not creatable")
1434 .arg(stringAt(obj->inheritedTypeNameIndex)));
1435 return nullptr;
1436 }
1437
1438 if (!type.isComposite()) {
1439 if (QObject *instance = type.createWithQQmlData())
1440 return initializeNonComposite(index, obj, typeRef, instance, parent, flags);
1441 recordError(
1442 obj->location,
1443 tr("Unable to create object of type %1").arg(
1444 stringAt(obj->inheritedTypeNameIndex)));
1445 return nullptr;
1446 }
1447
1448 QQmlRefPointer<QV4::ExecutableCompilationUnit> executableCu = typeRef->isSelfReference()
1449 ? compilationUnit
1450 : engine->handle()->executableCompilationUnit(typeRef->compilationUnit());
1451 Q_ASSERT(executableCu);
1452
1453 const bool isInlineComponent = type.isInlineComponent();
1454 const QString inlineComponentName = isInlineComponent ? type.elementName() : QString();
1455 QQmlObjectCreator subCreator(
1456 context, executableCu, inlineComponentName, sharedState.data(),
1457 isContextObject);
1458
1459 if (QObject *instance = isInlineComponent
1460 ? subCreator.create(
1461 executableCu->inlineComponentId(inlineComponentName), nullptr, nullptr,
1462 CreationFlags::InlineComponent)
1463 : subCreator.create()) {
1464 return initializeComposite(index, obj, typeRef, instance, parent, flags);
1465 }
1466
1467 errors += subCreator.errors;
1468 return nullptr;
1469}
1470
1471void QQmlObjectCreator::initializeDData(
1472 const QV4::CompiledData::Object *obj, QObject *instance, QQmlData *ddata, InitFlags flags)
1473{
1474 ddata->lineNumber = obj->location.line();
1475 ddata->columnNumber = obj->location.column();
1476 ddata->setImplicitDestructible();
1477
1478 // inline components are root objects, but their index is != 0, so we need
1479 // an additional check
1480 const bool documentRoot = (flags & InitFlag::IsDocumentRoot)
1481 || ddata->rootObjectInCreation
1482 || obj->hasFlag(QV4::CompiledData::Object::IsInlineComponentRoot);
1483
1484 context->installContext(
1485 ddata, documentRoot ? QQmlContextData::DocumentRoot : QQmlContextData::OrdinaryObject);
1486
1487 // Register the context object in the context early on in order for pending binding
1488 // initialization to find it available.
1489 if ((flags & (InitFlag::IsContextObject | InitFlag::IsImplicitComponent))
1490 == InitFlag::IsContextObject) {
1491 context->setContextObject(instance);
1492 }
1493}
1494
1495void QQmlObjectCreator::initializePropertyCache(
1496 int index, QQmlData *ddata, const QV4::ResolvedTypeReference *typeRef)
1497{
1498 if (!typeRef->isFullyDynamicType()) {
1499 QQmlPropertyCache::ConstPtr cache = propertyCaches->at(index);
1500 Q_ASSERT(!cache.isNull());
1501 ddata->propertyCache = std::move(cache);
1502 }
1503}
1504
1505void QQmlObjectCreator::initializeParent(QObject *instance, QObject *parent)
1506{
1507 if (instance->isWidgetType()) {
1508 if (parent && parent->isWidgetType()) {
1509 QAbstractDeclarativeData::setWidgetParent(instance, parent);
1510 } else {
1511 // No parent! Layouts need to handle this through a default property that
1512 // reparents accordingly. Otherwise the garbage collector will collect.
1513 }
1514 } else if (parent) {
1515 QQml_setParent_noEvent(instance, parent);
1516 }
1517}
1518
1519QObject *QQmlObjectCreator::populateInstanceAndAliasBindings(
1520 int index, QObject *instance, InitFlags flags)
1521{
1522 const auto doPopulate = [&]() {
1523 if (!populateInstance(
1524 index, instance, /*binding target*/instance, /*value type property*/nullptr)) {
1525 // an error occurred, so we can't setup the pending alias bindings
1526 pendingAliasBindings.clear();
1527 return false;
1528 }
1529
1530 if (!flags.testFlag(InitFlag::IsContextObject))
1531 return true;
1532
1533 while (!pendingAliasBindings.empty()) {
1534 for (std::vector<PendingAliasBinding>::iterator it = pendingAliasBindings.begin();
1535 it != pendingAliasBindings.end(); ) {
1536 if ((*it)(sharedState.data()))
1537 it = pendingAliasBindings.erase(it);
1538 else
1539 ++it;
1540 }
1541 }
1542
1543 return true;
1544 };
1545
1546 QObject *scopeObject = instance;
1547 qSwap(_scopeObject, scopeObject);
1548
1549 Q_ASSERT(sharedState->allJavaScriptObjects.canTrack());
1550 sharedState->allJavaScriptObjects.trackObject(v4, instance);
1551
1552 QV4::Scope valueScope(v4);
1553 QV4::QmlContext *qmlContext = static_cast<QV4::QmlContext *>(valueScope.constructUndefined(1));
1554
1555 qSwap(_qmlContext, qmlContext);
1556
1557 const bool ok = doPopulate();
1558
1559 qSwap(_qmlContext, qmlContext);
1560 qSwap(_scopeObject, scopeObject);
1561
1562 return ok ? instance : nullptr;
1563}
1564
1565QObject *QQmlObjectCreator::initializeComponent(
1566 int index, const QV4::CompiledData::Object *obj, QObject *instance, InitFlags flags)
1567{
1568 Q_ASSERT(instance);
1569 Q_ASSERT(obj);
1570
1571 QScopedValueRollback<QQmlObjectCreator*> ocRestore(
1572 QQmlEnginePrivate::get(engine)->activeObjectCreator, this);
1573
1574 // we just created it inside createComponent; so QQmlData::get() without create = true;
1575 initializeDData(obj, instance, QQmlData::get(instance), flags);
1576
1577 if (!flags.testFlag(InitFlag::IsImplicitComponent))
1578 registerObjectWithContextById(index, instance);
1579 return instance;
1580}
1581
1582QObject *QQmlObjectCreator::initializeComposite(
1583 int index, const QV4::CompiledData::Object *obj, const QV4::ResolvedTypeReference *typeRef,
1584 QObject *instance, QObject *parent, InitFlags flags)
1585{
1586 Q_ASSERT(instance);
1587 Q_ASSERT(typeRef);
1588
1589 QScopedValueRollback<QQmlObjectCreator*> ocRestore(
1590 QQmlEnginePrivate::get(engine)->activeObjectCreator, this);
1591
1592 initializeParent(instance, parent);
1593 QQmlData *ddata = QQmlData::get(instance, /*create*/true);
1594 initializeDData(obj, instance, ddata, flags);
1595
1596 initializePropertyCache(index, ddata, typeRef);
1597
1598 return populateInstanceAndAliasBindings(index, instance, flags);
1599}
1600
1601QObject *QQmlObjectCreator::initializeNonComposite(
1602 int index, const QV4::CompiledData::Object *obj, const QV4::ResolvedTypeReference *typeRef,
1603 QObject *instance, QObject *parent, InitFlags flags)
1604{
1605 Q_ASSERT(instance);
1606 Q_ASSERT(obj);
1607 Q_ASSERT(!compilationUnit->objectIsComponent(index));
1608 Q_ASSERT(typeRef);
1609
1610 const QQmlType type = typeRef->type();
1611 Q_ASSERT(type.isValid());
1612 Q_ASSERT(!type.isComposite());
1613
1614 QScopedValueRollback<QQmlObjectCreator*> ocRestore(QQmlEnginePrivate::get(engine)->activeObjectCreator, this);
1615
1616 if (const int finalizerCast = type.finalizerCast(); finalizerCast != -1) {
1617 const auto hook = reinterpret_cast<QQmlFinalizerHook *>(
1618 reinterpret_cast<char *>(instance) + finalizerCast);
1619 sharedState->finalizeHooks.push_back(hook);
1620 }
1621
1622 QQmlData *ddata = QQmlData::get(instance, /*create*/true);
1623 if (sharedState->rootContext && sharedState->rootContext->isRootObjectInCreation()) {
1624 ddata->rootObjectInCreation = true;
1625 sharedState->rootContext->setRootObjectInCreation(false);
1626 }
1627
1628 const size_t instanceIndex = sharedState->allCreatedObjects.size();
1629 sharedState->allCreatedObjects.push_back(instance);
1630
1631 initializeParent(instance, parent);
1632 initializeDData(obj, instance, ddata, flags);
1633
1634 if (const int parserStatusCast = type.parserStatusCast(); parserStatusCast != -1) {
1635 if (QQmlParserStatus *parserStatus = reinterpret_cast<QQmlParserStatus*>(
1636 reinterpret_cast<char *>(instance) + parserStatusCast)) {
1637 parserStatus->classBegin();
1638 // push() the profiler state here, together with the parserStatus, as we'll pop() them
1639 // together, too.
1640 Q_QML_OC_PROFILE(sharedState->profiler, sharedState->profiler.push(obj));
1641 sharedState->allParserStatusCallbacks.push_back({ instanceIndex, parserStatusCast });
1642 }
1643 }
1644
1645 if (QQmlCustomParser *customParser = type.customParser();
1646 customParser && compilationUnit->objectHasCustomParserBindings(index)) {
1647 customParser->engine = QQmlEnginePrivate::get(engine);
1648 customParser->imports = compilationUnit->typeNameCache().data();
1649
1650 QList<const QV4::CompiledData::Binding *> bindings;
1651 const QV4::CompiledData::Object *obj = compilationUnit->objectAt(index);
1652 const QV4::CompiledData::RuntimeBindingIndex *bindingOrder =
1653 compilationUnit->bindingApplicationOrder(index);
1654 for (quint32 k = 0; k < obj->nBindings; ++k) {
1655 const quint32 i = bindingOrder[k];
1656 if (compilationUnit->bindingIsCustomParser(index, i))
1657 bindings << obj->bindingTable() + i;
1658 }
1659 customParser->applyBindings(instance, compilationUnit, bindings);
1660
1661 customParser->engine = nullptr;
1662 customParser->imports = (QQmlTypeNameCache*)nullptr;
1663 }
1664
1665 initializePropertyCache(index, ddata, typeRef);
1666 return populateInstanceAndAliasBindings(index, instance, flags);
1667}
1668
1669/*!
1670 * \internal
1671 * Create a single object at \a objectIndex within an already-existing \a existingContext.
1672 * Unlike create(), this does not allocate a new context — the object is registered as an
1673 * OrdinaryObject in \a existingContext.
1674 */
1675QObject *QQmlObjectCreator::createObjectInContext(
1676 int objectIndex, QObject *parent,
1677 const QQmlRefPointer<QQmlContextData> &existingContext)
1678{
1679 Q_ASSERT(phase == Startup);
1680 phase = CreatingObjects;
1681
1682 context = existingContext;
1683 if (!sharedState->rootContext)
1684 sharedState->rootContext = context;
1685
1686 QV4::Scope scope(v4);
1687 if (topLevelCreator)
1688 sharedState->allJavaScriptObjects = ObjectInCreationGCAnchorList(scope);
1689
1690 QObject *rv = createInstance(objectIndex, parent, /*isContextObject=*/false);
1691 phase = ObjectsCreated;
1692 return rv;
1693}
1694
1695bool QQmlObjectCreator::finalize(QQmlInstantiationInterrupt &interrupt)
1696{
1697 Q_ASSERT(phase == ObjectsCreated || phase == Finalizing);
1698 phase = Finalizing;
1699
1700 QQmlObjectCreatorRecursionWatcher watcher(this);
1701 QScopedValueRollback<QQmlObjectCreator*> ocRestore(QQmlEnginePrivate::get(engine)->activeObjectCreator, this);
1702
1703 /* We install all pending bindings (both plain QML and QProperty), and remove the ones which do not
1704 actually have dependencies.
1705 It is necessary to install the binding so that it runs at least once, which causes it to capture any
1706 dependencies.
1707 We then check for the following conditions:
1708 - Is the binding in an error state?
1709 - Does the binding has any dependencies (from properties)?
1710 - Does it depend on anything in the context, which has not been resolved yet (and thus couldn't be
1711 captured)?
1712 If the answer to all of those questions is "no", it is safe to remove the binding, as there is no
1713 way for it to change its value afterwards from that point on.
1714 The QML preview, however, needs to re-evaluate the binding if its code is changed.
1715 */
1716 const bool removeConstantBindings = !QV4::ExecutionEngine::isPreviewing();
1717
1718 while (!sharedState->allCreatedBindings.empty()) {
1719 QQmlAbstractBinding::Ptr b = sharedState->allCreatedBindings.back();
1720 sharedState->allCreatedBindings.pop_back();
1721 Q_ASSERT(b);
1722 // skip, if b is not added to an object
1723 if (!b->isAddedToObject())
1724 continue;
1725 QQmlData *data = QQmlData::get(b->targetObject());
1726 Q_ASSERT(data);
1727 data->clearPendingBindingBit(b->targetPropertyIndex().coreIndex());
1728 b->setEnabled(true, QQmlPropertyData::BypassInterceptor |
1729 QQmlPropertyData::DontRemoveBinding);
1730 if (removeConstantBindings && b->kind() == QQmlAbstractBinding::QmlBinding) {
1731 QQmlBinding *binding = static_cast<QQmlBinding*>(b.data());
1732 if (!binding->hasError() && !binding->hasDependencies()
1733 && !binding->hasUnresolvedNames()) {
1734 b->removeFromObject();
1735 }
1736 }
1737
1738 if (watcher.hasRecursed() || interrupt.shouldInterrupt())
1739 return false;
1740 }
1741
1742 while (!sharedState->allQPropertyBindings.isEmpty()) {
1743 auto& [target, index, qmlBinding] = sharedState->allQPropertyBindings.first();
1744
1745 QQmlData *data = QQmlData::get(target);
1746 if (!data || !data->hasBindingBit(index)) {
1747 // The target property has been overwritten since we stashed the binding.
1748 sharedState->allQPropertyBindings.pop_front();
1749 continue;
1750 }
1751
1752 QUntypedBindable bindable;
1753 void *argv[] = { &bindable };
1754 // allow interception
1755 target->metaObject()->metacall(target, QMetaObject::BindableProperty, index, argv);
1756 const bool success = bindable.setBinding(qmlBinding);
1757
1758 const auto bindingPrivateRefCount = QPropertyBindingPrivate::get(qmlBinding)->refCount();
1759
1760 // Only pop_front after setting the binding as the bindings are refcounted.
1761 sharedState->allQPropertyBindings.pop_front();
1762
1763 // If the binding was actually not set, it's deleted now.
1764 if (removeConstantBindings && success && bindingPrivateRefCount > 1) {
1765 if (auto priv = QPropertyBindingPrivate::get(qmlBinding); priv->isQmlBinding()) {
1766 const auto qmlBindingBase = static_cast<const QQmlPropertyBindingBase *>(priv);
1767 if (qmlBindingBase->bindingKind()
1768 == QQmlPropertyBindingBase::BindingKind::JavaScript) {
1769 const auto qmlBindingPriv =
1770 static_cast<const QQmlPropertyBinding *>(qmlBindingBase);
1771 const auto jsExpression = qmlBindingPriv->jsExpression();
1772 const bool canRemove = !qmlBinding.error().hasError()
1773 && !qmlBindingPriv->hasDependencies()
1774 && !jsExpression->hasUnresolvedNames();
1775 if (canRemove)
1776 bindable.takeBinding();
1777 }
1778 }
1779 }
1780
1781 if (watcher.hasRecursed() || interrupt.shouldInterrupt())
1782 return false;
1783 }
1784
1785 if (QQmlVME::componentCompleteEnabled()) { // the qml designer does the component complete later
1786 while (!sharedState->allParserStatusCallbacks.empty()) {
1787 QQmlObjectCompletionProfiler profiler(&sharedState->profiler);
1788 const ParserStatus status = sharedState->allParserStatusCallbacks.back();
1789 sharedState->allParserStatusCallbacks.pop_back();
1790
1791 const QQmlGuard<QObject> &instance = sharedState->allCreatedObjects[status.objectIndex];
1792 if (!instance)
1793 continue;
1794
1795 QQmlParserStatus *parserStatus
1796 = reinterpret_cast<QQmlParserStatus *>(
1797 reinterpret_cast<char *>(instance.data()) + status.parserStatusCast);
1798 parserStatus->componentComplete();
1799
1800 if (watcher.hasRecursed() || interrupt.shouldInterrupt())
1801 return false;
1802 }
1803 }
1804
1805 for (QQmlFinalizerHook *hook: std::as_const(sharedState->finalizeHooks)) {
1806 hook->componentFinalized();
1807 if (watcher.hasRecursed())
1808 return false;
1809 }
1810 sharedState->finalizeHooks.clear();
1811
1812 while (sharedState->componentAttached) {
1813 QQmlComponentAttached *a = sharedState->componentAttached;
1814 a->removeFromList();
1815 QQmlData *d = QQmlData::get(a->parent());
1816 Q_ASSERT(d);
1817 Q_ASSERT(d->context);
1818 d->context->addComponentAttached(a);
1819 if (QQmlVME::componentCompleteEnabled())
1820 emit a->completed();
1821
1822 if (watcher.hasRecursed() || interrupt.shouldInterrupt())
1823 return false;
1824 }
1825
1826 phase = Done;
1827
1828 return true;
1829}
1830
1831void QQmlObjectCreator::clear()
1832{
1833 if (phase == Done || phase == Finalizing || phase == Startup)
1834 return;
1835 Q_ASSERT(phase != Startup);
1836
1837 while (!sharedState->allCreatedObjects.empty()) {
1838 auto object = sharedState->allCreatedObjects.back();
1839 sharedState->allCreatedObjects.pop_back();
1840 if (engine->objectOwnership(object) != QQmlEngine::CppOwnership) {
1841 delete object;
1842 }
1843 }
1844
1845 while (sharedState->componentAttached) {
1846 QQmlComponentAttached *a = sharedState->componentAttached;
1847 a->removeFromList();
1848 }
1849
1850 phase = Done;
1851}
1852
1853void QQmlObjectCreator::registerPostHocRequiredProperties(const QV4::CompiledData::Binding *binding)
1854{
1855 const qsizetype oldRequiredPropertiesCount = sharedState->requiredProperties.size();
1856 QSet<QString> postHocRequired;
1857 for (auto it = _compiledObject->requiredPropertyExtraDataBegin(); it != _compiledObject->requiredPropertyExtraDataEnd(); ++it)
1858 postHocRequired.insert(stringAt(it->nameIndex));
1859 bool hadInheritedRequiredProperties = !postHocRequired.empty();
1860
1861 for (int propertyIndex = 0; propertyIndex != _compiledObject->propertyCount(); ++propertyIndex) {
1862 const QV4::CompiledData::Property* property = _compiledObject->propertiesBegin() + propertyIndex;
1863 const QQmlPropertyData *propertyData = _propertyCache->property(_propertyCache->propertyOffset() + propertyIndex);
1864 // only compute stringAt if there's a chance for the lookup to succeed
1865 auto postHocIt = postHocRequired.isEmpty() ? postHocRequired.end() : postHocRequired.find(stringAt(property->nameIndex()));
1866 if (!property->isRequired() && postHocRequired.end() == postHocIt)
1867 continue;
1868 if (postHocIt != postHocRequired.end())
1869 postHocRequired.erase(postHocIt);
1870 if (isContextObject)
1871 sharedState->hadTopLevelRequiredProperties = true;
1872 sharedState->requiredProperties.insert({_qobject, propertyData},
1873 RequiredPropertyInfo {compilationUnit->stringAt(property->nameIndex()), compilationUnit->finalUrl(), property->location, {}});
1874
1875 }
1876
1877 const auto getPropertyCacheRange = [&]() -> std::pair<int, int> {
1878 // the logic in a nutshell: we work with QML instances here. every
1879 // instance has a QQmlType:
1880 // * if QQmlType is valid && not an inline component, it's a C++ type
1881 // * otherwise, it's a QML-defined type (a.k.a. Composite type), where
1882 // invalid type == "comes from another QML document"
1883 //
1884 // 1. if the type we inherit from comes from C++, we must check *all*
1885 // properties in the property cache so far - since we can have
1886 // required properties defined in C++
1887 // 2. otherwise - the type comes from QML, it's enough to check just
1888 // *own* properties in the property cache, because there's a previous
1889 // type in the hierarchy that has checked the C++ properties (via 1.)
1890 // 3. required attached properties are explicitly not supported. to
1891 // achieve that, go through all its properties
1892 // 4. required grouped properties: the group itself is covered by 1.
1893 // required sub-properties are not properly handled (QTBUG-96544), so
1894 // just return the old range here for consistency
1895 QV4::ResolvedTypeReference *typeRef = resolvedType(_compiledObject->inheritedTypeNameIndex);
1896 if (!typeRef) { // inside a binding on attached/grouped property
1897 Q_ASSERT(binding);
1898 if (binding->isAttachedProperty())
1899 return { 0, _propertyCache->propertyCount() }; // 3.
1900 Q_ASSERT(binding->isGroupedProperty());
1901 return { 0, _propertyCache->propertyOffset() + 1 }; // 4.
1902 }
1903 Q_ASSERT(!compilationUnit->objectIsComponent(_compiledObjectIndex));
1904 QQmlType type = typeRef->type();
1905 if (type.isComposite())
1906 return { _propertyCache->propertyOffset(), _propertyCache->propertyCount() }; // 2.
1907 return { 0, _propertyCache->propertyCount() }; // 1.
1908 };
1909 const auto [offset, count] = getPropertyCacheRange();
1910 for (int i = offset; i < count; ++i) {
1911 const QQmlPropertyData *propertyData = _propertyCache->maybeUnresolvedProperty(i);
1912 if (!propertyData)
1913 continue;
1914 // TODO: the property might be a grouped property (in which case we need
1915 // to dive into its sub-properties and check whether there are any
1916 // required elements there) - QTBUG-96544
1917 if (!propertyData->isRequired() && postHocRequired.isEmpty())
1918 continue;
1919 QString name = propertyData->name(_qobject);
1920 const auto postHocIt = postHocRequired.constFind(name);
1921 if (postHocIt == postHocRequired.constEnd()) {
1922 if (!propertyData->isRequired())
1923 continue;
1924 } else {
1925 postHocRequired.erase(postHocIt);
1926 }
1927
1928 if (isContextObject)
1929 sharedState->hadTopLevelRequiredProperties = true;
1930 sharedState->requiredProperties.insert(
1931 {_qobject, propertyData},
1932 RequiredPropertyInfo {
1933 std::move(name), compilationUnit->finalUrl(), _compiledObject->location, {}
1934 });
1935 }
1936
1937 if (binding && binding->isAttachedProperty()
1938 && sharedState->requiredProperties.size() != oldRequiredPropertiesCount) {
1939 recordError(
1940 binding->location,
1941 QLatin1String("Attached property has required properties. This is not supported"));
1942 }
1943
1944 // Note: there's a subtle case with the above logic: if we process a random
1945 // QML-defined leaf type, it could have a required attribute overwrite on an
1946 // *existing* property: `import QtQuick; Text { required text }`. in this
1947 // case, we must add the property to a required list
1948 if (!postHocRequired.isEmpty()) {
1949 // NB: go through [0, offset) range as [offset, count) is already done
1950 for (int i = 0; i < offset; ++i) {
1951 const QQmlPropertyData *propertyData = _propertyCache->maybeUnresolvedProperty(i);
1952 if (!propertyData)
1953 continue;
1954 QString name = propertyData->name(_qobject);
1955 const auto postHocIt = postHocRequired.constFind(name);
1956 if (postHocIt == postHocRequired.constEnd())
1957 continue;
1958 postHocRequired.erase(postHocIt);
1959
1960 if (isContextObject)
1961 sharedState->hadTopLevelRequiredProperties = true;
1962 sharedState->requiredProperties.insert(
1963 {_qobject, propertyData},
1964 RequiredPropertyInfo {
1965 std::move(name), compilationUnit->finalUrl(), _compiledObject->location, {}
1966 });
1967 }
1968 }
1969
1970 if (!postHocRequired.isEmpty() && hadInheritedRequiredProperties)
1971 recordError({}, QLatin1String("Property %1 was marked as required but does not exist").arg(*postHocRequired.begin()));
1972}
1973
1974bool QQmlObjectCreator::populateInstance(int index, QObject *instance, QObject *bindingTarget,
1975 const QQmlPropertyData *valueTypeProperty,
1976 const QV4::CompiledData::Binding *binding)
1977{
1978 Q_ASSERT(instance);
1979 QQmlData *declarativeData = QQmlData::get(instance, /*create*/true);
1980
1981 qSwap(_qobject, instance);
1982 qSwap(_valueTypeProperty, valueTypeProperty);
1983 qSwap(_compiledObjectIndex, index);
1984 const QV4::CompiledData::Object *obj = compilationUnit->objectAt(_compiledObjectIndex);
1985 qSwap(_compiledObject, obj);
1986 qSwap(_ddata, declarativeData);
1987 qSwap(_bindingTarget, bindingTarget);
1988
1989 QV4::Scope valueScope(v4);
1990 QV4::ScopedValue scopeObjectProtector(valueScope);
1991
1992 QQmlPropertyCache::ConstPtr cache = propertyCaches->at(_compiledObjectIndex);
1993
1994 QQmlVMEMetaObject *vmeMetaObject = nullptr;
1995 if (propertyCaches->needsVMEMetaObject(_compiledObjectIndex)) {
1996 Q_ASSERT(!cache.isNull());
1997 // install on _object
1998 vmeMetaObject = new QQmlVMEMetaObject(v4, _qobject, cache, compilationUnit, _compiledObjectIndex);
1999 _ddata->propertyCache = cache;
2000 scopeObjectProtector = _ddata->jsWrapper.value();
2001 } else {
2002 vmeMetaObject = QQmlVMEMetaObject::get(_qobject, v4);
2003 }
2004
2005 registerObjectWithContextById(_compiledObjectIndex, _qobject);
2006
2007 qSwap(_propertyCache, cache);
2008 qSwap(_vmeMetaObject, vmeMetaObject);
2009
2010 // If it's a grouped property object, don't populate CU and object index.
2011 // It might be populated at the actual instantiation point, or the object might not be
2012 // created by QML at all.
2013 if (!stringAt(_compiledObject->inheritedTypeNameIndex).isEmpty()) {
2014 _ddata->compilationUnit = compilationUnit;
2015 _ddata->cuObjectIndex = int(_compiledObjectIndex);
2016 }
2017
2018 // When we are called to apply a deferred binding, we complete deferral here rather than
2019 // initiate it: the deferred bindings are applied right away via ApplyAll below. Registering
2020 // additional deferred data would make no sense.
2021 const bool applyingDeferred =
2022 compilationUnit->objectIsPopulatedByDeferredBinding(_compiledObjectIndex);
2023 if (!applyingDeferred
2024 && compilationUnit->objectHasDeferredBindings(_compiledObjectIndex)) {
2025 _ddata->deferData(_compiledObjectIndex, compilationUnit, context, m_inlineComponentName);
2026 }
2027
2028 registerPostHocRequiredProperties(binding);
2029
2030 if (_compiledObject->nFunctions > 0)
2031 setupFunctions();
2032 setupBindings(applyingDeferred ? BindingMode::ApplyAll : BindingMode::ApplyImmediate);
2033
2034 for (int aliasIndex = 0; aliasIndex != _compiledObject->aliasCount(); ++aliasIndex) {
2035 // Ensure aliasChanged() signals are connected during object creation.
2036 // This is necessary because alias signals may not have been connected
2037 // if the signal handlers are defined and connected in C++ code rather
2038 // than being declared in QML.
2039 _vmeMetaObject->connectAlias(_compiledObject, aliasIndex);
2040 if (!context->isIdValueSet(0)) // TODO: Do we really want 0 here?
2041 continue;
2042 const QQmlPropertyData *aliasProperty =
2043 _propertyCache->property(_vmeMetaObject->aliasOffset() + aliasIndex);
2044 // A read-only alias cannot be used to set the required property. Don't suggest it.
2045 if (!aliasProperty || (!aliasProperty->isWritable() && !aliasProperty->isQList()))
2046 continue;
2047 QObject *target = context->idValue(aliasProperty->aliasTargetObjectId());
2048 if (!target)
2049 continue;
2050 QQmlData *targetDData = QQmlData::get(target, /*create*/false);
2051 if (targetDData == nullptr || targetDData->propertyCache.isNull())
2052 continue;
2053
2054 const int targetPropertyIndex = aliasProperty->aliasTarget();
2055 int coreIndex = QQmlPropertyIndex::fromEncoded(targetPropertyIndex).coreIndex();
2056
2057 const QQmlPropertyData *const targetProperty = targetDData->propertyCache->property(coreIndex);
2058 if (!targetProperty)
2059 continue;
2060 auto it = sharedState->requiredProperties.find({target, targetProperty});
2061 if (it != sharedState->requiredProperties.end()) {
2062 const QV4::CompiledData::Alias* alias = _compiledObject->aliasesBegin() + aliasIndex;
2063 it->aliasesToRequired.push_back(
2064 AliasToRequiredInfo {
2065 compilationUnit->stringAt(alias->nameIndex()),
2066 compilationUnit->finalUrl()
2067 });
2068 }
2069 }
2070
2071 qSwap(_vmeMetaObject, vmeMetaObject);
2072 qSwap(_bindingTarget, bindingTarget);
2073 qSwap(_ddata, declarativeData);
2074 qSwap(_compiledObject, obj);
2075 qSwap(_compiledObjectIndex, index);
2076 qSwap(_valueTypeProperty, valueTypeProperty);
2077 qSwap(_qobject, instance);
2078 qSwap(_propertyCache, cache);
2079
2080 return errors.isEmpty();
2081}
2082
2083/*!
2084 \internal
2085*/
2086QQmlComponent *QQmlObjectCreator::createComponent(
2087 QQmlEngine *engine, QV4::ExecutableCompilationUnit *compilationUnit, int index,
2088 QObject *parent, const QQmlRefPointer<QQmlContextData> &context)
2089{
2090 QQmlComponent *component = new QQmlComponent(engine, compilationUnit, index, parent);
2091 QQmlComponentPrivate::get(component)->setCreationContext(context);
2092 QQmlData *ddata = QQmlData::get(component, /*create*/ true);
2093 Q_ASSERT(ddata);
2094 ddata->compilationUnit = compilationUnit;
2095 ddata->cuObjectIndex = index;
2096 return component;
2097}
2098
2099/*!
2100 \internal
2101 Re-populate bindings, functions and child objects on an existing \a instance
2102 whose VME metaobject chain has already been (re-)created externally.
2103
2104 Unlike initializeInstance(), this does not create a new VME — it uses the one
2105 already installed on the object. It sets up the context, registers the object
2106 by id, installs functions, evaluates bindings (which may create child objects),
2107 and connects aliases.
2108
2109 Used by the QML preview/hot-reload system to rebuild an object's contents
2110 after its VME hierarchy has been reconstructed.
2111*/
2112void QQmlObjectCreator::repopulateBindings(
2113 int index, QObject *instance,
2114 const QQmlRefPointer<QQmlContextData> &instanceContext, InitFlags flags)
2115{
2116 phase = QQmlObjectCreator::ObjectsCreated;
2117
2118 // If the object doesn't exist in the CU, there's nothing to do.
2119 if (compilationUnit->objectCount() <= index)
2120 return;
2121
2122 const auto oldContext = std::exchange(context, instanceContext);
2123 const auto contextGuard = qScopeGuard([&]() {
2124 context = oldContext;
2125 });
2126
2127 auto rootContextGuard = qScopeGuard([&]() {
2128 sharedState->rootContext.reset();
2129 });
2130 if (!sharedState->rootContext)
2131 sharedState->rootContext = context;
2132 else
2133 rootContextGuard.dismiss();
2134
2135 QV4::Scope scope(engine->handle());
2136 auto jsObjectsGuard = qScopeGuard([&]() {
2137 sharedState->allJavaScriptObjects = ObjectInCreationGCAnchorList();
2138 });
2139 if (!sharedState->allJavaScriptObjects.canTrack())
2140 sharedState->allJavaScriptObjects = ObjectInCreationGCAnchorList(scope);
2141 else
2142 jsObjectsGuard.dismiss();
2143
2144 QQmlData *ddata = QQmlData::get(instance, /*create=*/true);
2145 Q_ASSERT(ddata);
2146
2147 QQmlVMEMetaObject *vmeMetaObject = QQmlVMEMetaObject::get(instance, v4);
2148
2149 const QV4::CompiledData::Object *obj = compilationUnit->objectAt(index);
2150
2151 // Set up internal state mirroring populateInstanceAndAliasBindings + populateInstance.
2152 qSwap(_qobject, instance);
2153 qSwap(_compiledObjectIndex, index);
2154 qSwap(_compiledObject, obj);
2155 qSwap(_ddata, ddata);
2156 QObject *bindingTarget = _qobject;
2157 qSwap(_bindingTarget, bindingTarget);
2158 QObject *scopeObject = _qobject;
2159 qSwap(_scopeObject, scopeObject);
2160 const QQmlPropertyData *valueTypeProperty = nullptr;
2161 qSwap(_valueTypeProperty, valueTypeProperty);
2162
2163 Q_ASSERT(sharedState->allJavaScriptObjects.canTrack());
2164 sharedState->allJavaScriptObjects.trackObject(v4, _qobject);
2165
2166 QV4::QmlContext *qmlContext = static_cast<QV4::QmlContext *>(scope.constructUndefined(1));
2167 qSwap(_qmlContext, qmlContext);
2168
2169 QV4::ScopedValue scopeObjectProtector(scope);
2170
2171 QQmlPropertyCache::ConstPtr cache = propertyCaches->at(_compiledObjectIndex);
2172 _ddata->propertyCache = cache;
2173 qSwap(_propertyCache, cache);
2174 qSwap(_vmeMetaObject, vmeMetaObject);
2175
2176 if (compilationUnit->objectId(_compiledObjectIndex) < context->numIdValues())
2177 registerObjectWithContextById(_compiledObjectIndex, _qobject);
2178
2179 _ddata->compilationUnit = compilationUnit;
2180 _ddata->cuObjectIndex = int(_compiledObjectIndex);
2181
2182 if (_compiledObject->nFunctions > 0)
2183 setupFunctions();
2184 setupBindings(BindingMode::ApplyImmediate);
2185
2186 if (flags.testFlag(InitFlag::IsContextObject)) {
2187 while (!pendingAliasBindings.empty()) {
2188 for (auto it = pendingAliasBindings.begin(); it != pendingAliasBindings.end();) {
2189 if ((*it)(sharedState.data()))
2190 it = pendingAliasBindings.erase(it);
2191 else
2192 ++it;
2193 }
2194 }
2195 }
2196
2197 // Restore swapped state.
2198 qSwap(_vmeMetaObject, vmeMetaObject);
2199 qSwap(_propertyCache, cache);
2200 qSwap(_qmlContext, qmlContext);
2201 qSwap(_scopeObject, scopeObject);
2202 qSwap(_valueTypeProperty, valueTypeProperty);
2203 qSwap(_bindingTarget, bindingTarget);
2204 qSwap(_ddata, ddata);
2205 qSwap(_compiledObject, obj);
2206 qSwap(_compiledObjectIndex, index);
2207 qSwap(_qobject, instance);
2208}
2209
2210/*!
2211 * \internal
2212 *
2213 * Install the binding at \a bindingIndex of the compiled object \a index onto
2214 * the already created \a instance (at \a instanceContext), reusing the normal
2215 * binding-setup path. Only that one binding is applied and the \a{instance}'s
2216 * identity (ddata, compilation unit and property cache) is preserved. The
2217 * caller must call finalize() afterwards to enable and evaluate the installed
2218 * binding.
2219 *
2220 * Used by the QML preview's in-place patch to add a binding without rebuilding.
2221 * Returns true if the binding was installed.
2222 */
2223bool QQmlObjectCreator::applyLateBinding(int index, QObject *instance,
2224 const QQmlRefPointer<QQmlContextData> &instanceContext,
2225 int bindingIndex)
2226{
2227 phase = QQmlObjectCreator::ObjectsCreated;
2228
2229 if (compilationUnit->objectCount() <= index)
2230 return false;
2231
2232 const auto oldContext = std::exchange(context, instanceContext);
2233 const auto contextGuard = qScopeGuard([&]() { context = oldContext; });
2234
2235 auto rootContextGuard = qScopeGuard([&]() { sharedState->rootContext.reset(); });
2236 if (!sharedState->rootContext)
2237 sharedState->rootContext = context;
2238 else
2239 rootContextGuard.dismiss();
2240
2241 QV4::Scope scope(engine->handle());
2242 auto jsObjectsGuard = qScopeGuard(
2243 [&]() { sharedState->allJavaScriptObjects = ObjectInCreationGCAnchorList(); });
2244 if (!sharedState->allJavaScriptObjects.canTrack())
2245 sharedState->allJavaScriptObjects = ObjectInCreationGCAnchorList(scope);
2246 else
2247 jsObjectsGuard.dismiss();
2248
2249 QQmlData *ddata = QQmlData::get(instance, /*create=*/true);
2250 Q_ASSERT(ddata);
2251
2252 // Unlike repopulateBindings(), we are patching a binding onto a level of an already-live
2253 // instance and must not disturb its identity: the instance keeps its own (possibly more derived)
2254 // compilation unit and property cache. Snapshot and restore them around the apply.
2255 const QQmlRefPointer<QV4::ExecutableCompilationUnit> savedUnit = ddata->compilationUnit;
2256 const QQmlPropertyCache::ConstPtr savedCache = ddata->propertyCache;
2257 const int savedCuObjectIndex = ddata->cuObjectIndex;
2258 const auto ddataGuard = qScopeGuard([&]() {
2259 ddata->compilationUnit = savedUnit;
2260 ddata->propertyCache = savedCache;
2261 ddata->cuObjectIndex = savedCuObjectIndex;
2262 });
2263
2264 QQmlVMEMetaObject *vmeMetaObject = QQmlVMEMetaObject::get(instance, engine->handle());
2265 const QV4::CompiledData::Object *obj = compilationUnit->objectAt(index);
2266 if (bindingIndex < 0 || uint(bindingIndex) >= obj->nBindings)
2267 return false;
2268
2269 qSwap(_qobject, instance);
2270 qSwap(_compiledObjectIndex, index);
2271 qSwap(_compiledObject, obj);
2272 qSwap(_ddata, ddata);
2273 QObject *bindingTarget = _qobject;
2274 qSwap(_bindingTarget, bindingTarget);
2275 QObject *scopeObject = _qobject;
2276 qSwap(_scopeObject, scopeObject);
2277 const QQmlPropertyData *valueTypeProperty = nullptr;
2278 qSwap(_valueTypeProperty, valueTypeProperty);
2279
2280 Q_ASSERT(sharedState->allJavaScriptObjects.canTrack());
2281 sharedState->allJavaScriptObjects.trackObject(v4, _qobject);
2282
2283 QV4::QmlContext *qmlContext = static_cast<QV4::QmlContext *>(scope.constructUndefined(1));
2284 qSwap(_qmlContext, qmlContext);
2285
2286 QQmlPropertyCache::ConstPtr cache = propertyCaches->at(_compiledObjectIndex);
2287 qSwap(_propertyCache, cache);
2288 qSwap(_vmeMetaObject, vmeMetaObject);
2289
2290 const QV4::CompiledData::Binding *binding = _compiledObject->bindingTable() + bindingIndex;
2291 const QQmlPropertyData *defaultProperty = _compiledObject->indexOfDefaultPropertyOrAlias != -1
2292 ? _propertyCache->parent()->defaultProperty()
2293 : _propertyCache->defaultProperty();
2294 const QQmlPropertyData *property = binding->propertyNameIndex != 0
2295 ? _propertyCache->property(stringAt(binding->propertyNameIndex), _qobject, context)
2296 : defaultProperty;
2297
2298 const bool installed = property && setPropertyBinding(property, binding);
2299
2300 qSwap(_vmeMetaObject, vmeMetaObject);
2301 qSwap(_propertyCache, cache);
2302 qSwap(_qmlContext, qmlContext);
2303 qSwap(_valueTypeProperty, valueTypeProperty);
2304 qSwap(_scopeObject, scopeObject);
2305 qSwap(_bindingTarget, bindingTarget);
2306 qSwap(_ddata, ddata);
2307 qSwap(_compiledObject, obj);
2308 qSwap(_compiledObjectIndex, index);
2309 qSwap(_qobject, instance);
2310
2311 return installed;
2312}
2313
2319
2320void ObjectInCreationGCAnchorList::trackObject(QV4::ExecutionEngine *engine, QObject *instance)
2321{
2322 QV4::Value *wrapper = allocationScope->construct(1, QV4::QObjectWrapper::wrap(engine, instance));
2323 // we have to handle the case where the gc is already running, but the scope is discarded
2324 // before the collector runs again. In that case, rescanning won't help us. Thus, mark the
2325 // object.
2326 QV4::WriteBarrier::markCustom(engine, [wrapper](QV4::MarkStack *ms) {
2327 wrapper->heapObject()->mark(ms);
2328 });
2329}
QT_BEGIN_NAMESPACE Q_STATIC_LOGGING_CATEGORY(lcSynthesizedIterableAccess, "qt.iterable.synthesized", QtWarningMsg)
static QQmlType qmlTypeForObject(QObject *object)
QQmlObjectCreatorRecursionWatcher(QQmlObjectCreator *creator)