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
qqmltypedata.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
5#include <private/qqmlcomponentandaliasresolver_p.h>
6#include <private/qqmlengine_p.h>
7#include <private/qqmlirbuilder_p.h>
8#include <private/qqmlirloader_p.h>
9#include <private/qqmlpropertycachecreator_p.h>
10#include <private/qqmlpropertyvalidator_p.h>
11#include <private/qqmlscriptblob_p.h>
12#include <private/qqmlscriptdata_p.h>
13#include <private/qqmltypecompiler_p.h>
14#include <private/qqmltypedata_p.h>
15#include <private/qqmltypeloaderqmldircontent_p.h>
16
17#include <QtCore/qloggingcategory.h>
18#include <QtCore/qcryptographichash.h>
19
20#include <memory>
21
23
24Q_LOGGING_CATEGORY(lcCycle, "qt.qml.typeresolution.cycle", QtWarningMsg)
25
26QString QQmlTypeData::TypeReference::qualifiedName() const
27{
28 QString result;
29 if (!prefix.isEmpty()) {
30 result = prefix + QLatin1Char('.');
31 }
32 result.append(type.qmlTypeName());
33 return result;
34}
35
36QQmlTypeData::QQmlTypeData(const QUrl &url, QQmlTypeLoader *manager)
37 : QQmlNotifyingBlob(url, QmlFile, manager),
38 m_typesResolved(false), m_implicitImportLoaded(false)
39{
40
41}
42
43QQmlTypeData::~QQmlTypeData()
44{
45 m_scripts.clear();
46 m_compositeSingletons.clear();
47 m_resolvedTypes.clear();
48}
49
50QV4::CompiledData::CompilationUnit *QQmlTypeData::compilationUnit() const
51{
52 return m_compiledData.data();
53}
54
55QQmlType QQmlTypeData::qmlType(const QString &inlineComponentName) const
56{
57 if (inlineComponentName.isEmpty())
58 return m_qmlType;
59 return m_inlineComponentData[inlineComponentName].qmlType;
60}
61
62bool QQmlTypeData::tryLoadFromDiskCache()
63{
64 assertTypeLoaderThread();
65
66 if (!m_backupSourceCode.isCacheable())
67 return false;
68
69 if (!m_typeLoader->readCacheFile())
70 return false;
71
72 auto unit = QQml::makeRefPointer<QV4::CompiledData::CompilationUnit>();
73 {
74 QString error;
75 if (!unit->loadFromDisk(url(), m_backupSourceCode.sourceTimeStamp(), &error)) {
76 qCDebug(DBG_DISK_CACHE) << "Error loading" << urlString() << "from disk cache:" << error;
77 return false;
78 }
79 }
80
81 if (unit->unitData()->flags & QV4::CompiledData::Unit::PendingTypeCompilation) {
82 restoreIR(unit);
83 return true;
84 }
85
86 return loadFromDiskCache(unit);
87}
88
89bool QQmlTypeData::loadFromDiskCache(const QQmlRefPointer<QV4::CompiledData::CompilationUnit> &unit)
90{
91 assertTypeLoaderThread();
92
93 m_compiledData = unit;
94
95 QList<QV4::CompiledData::InlineComponent> ics;
96 for (int i = 0, count = m_compiledData->objectCount(); i < count; ++i) {
97 auto object = m_compiledData->objectAt(i);
98 m_typeReferences.collectFromObject(object);
99 const auto inlineComponentTable = object->inlineComponentTable();
100 for (auto i = 0; i != object->nInlineComponents; ++i) {
101 ics.push_back(inlineComponentTable[i]);
102 }
103 }
104
105 m_importCache->setBaseUrl(finalUrl(), finalUrlString());
106
107 // For remote URLs, we don't delay the loading of the implicit import
108 // because the loading probably requires an asynchronous fetch of the
109 // qmldir (so we can't load it just in time).
110 if (!finalUrl().scheme().isEmpty()) {
111 QUrl qmldirUrl = finalUrl().resolved(QUrl(QLatin1String("qmldir")));
112 if (!QQmlImports::isLocal(qmldirUrl)) {
113 if (!loadImplicitImport())
114 return false;
115
116 // find the implicit import
117 for (quint32 i = 0, count = m_compiledData->importCount(); i < count; ++i) {
118 const QV4::CompiledData::Import *import = m_compiledData->importAt(i);
119 if (m_compiledData->stringAt(import->uriIndex) == QLatin1String(".")
120 && import->qualifierIndex == 0
121 && !import->version.hasMajorVersion()
122 && !import->version.hasMinorVersion()) {
123 QList<QQmlError> errors;
124 auto pendingImport = std::make_shared<PendingImport>(
125 this, import, QQmlImports::ImportNoFlag);
126 pendingImport->precedence = QQmlImportInstance::Implicit;
127 if (!fetchQmldir(qmldirUrl, std::move(pendingImport), 1, &errors)) {
128 setError(errors);
129 return false;
130 }
131 break;
132 }
133 }
134 }
135 }
136
137 for (int i = 0, count = m_compiledData->importCount(); i < count; ++i) {
138 const QV4::CompiledData::Import *import = m_compiledData->importAt(i);
139 QList<QQmlError> errors;
140 if (!addImport(import, {}, &errors)) {
141 Q_ASSERT(errors.size());
142 QQmlError error(errors.takeFirst());
143 error.setUrl(m_importCache->baseUrl());
144 error.setLine(qmlConvertSourceCoordinate<quint32, int>(import->location.line()));
145 error.setColumn(qmlConvertSourceCoordinate<quint32, int>(import->location.column()));
146 errors.prepend(error); // put it back on the list after filling out information.
147 setError(errors);
148 return false;
149 }
150 }
151
152 for (auto&& ic: ics) {
153 QString const nameString = m_compiledData->stringAt(ic.nameIndex);
154 auto importUrl = finalUrl();
155 importUrl.setFragment(nameString);
156 auto import = new QQmlImportInstance();
157 m_importCache->addInlineComponentImport(import, nameString, importUrl);
158 }
159
160 return true;
161}
162
163template<>
164void QQmlComponentAndAliasResolver<QV4::CompiledData::CompilationUnit>::allocateNamedObjects(
165 const QV4::CompiledData::Object *object) const
166{
167 Q_UNUSED(object);
168}
169
170template<>
171bool QQmlComponentAndAliasResolver<QV4::CompiledData::CompilationUnit>::markAsComponent(int index) const
172{
173 return m_compiler->objectAt(index)->hasFlag(QV4::CompiledData::Object::IsComponent);
174}
175
176template<>
177void QQmlComponentAndAliasResolver<QV4::CompiledData::CompilationUnit>::setObjectId(int index) const
178{
179 Q_UNUSED(index)
180 // we cannot sanity-check the index here because bindings are sorted in a different order
181 // in the CU vs the IR.
182}
183
184template<>
185void QQmlComponentAndAliasResolver<QV4::CompiledData::CompilationUnit>::resolveGeneralizedGroupProperty(
186 const CompiledObject &component, CompiledBinding *binding)
187{
188 // We cannot make it fail here. It might be a custom-parsed property
189 for (int i = 0, count = component.namedObjectsInComponentCount(); i < count; ++i) {
190 const int candidateIndex = component.namedObjectsInComponentTable()[i];
191 if (m_compiler->objectAt(candidateIndex)->idNameIndex == binding->propertyNameIndex) {
192 m_propertyCaches->set(binding->value.objectIndex, m_propertyCaches->at(candidateIndex));
193 return;
194 }
195 }
196}
197
199
200template<>
201typename QQmlComponentAndAliasResolver<QV4::CompiledData::CompilationUnit>::AliasResolutionResult
202QQmlComponentAndAliasResolver<QV4::CompiledData::CompilationUnit>::resolveAliasesInObject(
203 const CompiledObject &component, int objectIndex,
204 QQmlPropertyCacheAliasCreator<QV4::CompiledData::CompilationUnit> *aliasCacheCreator,
205 QQmlError *error)
206{
207 const CompiledObject *obj = m_compiler->objectAt(objectIndex);
208 int aliasIndex = 0;
209 const auto doAppendAlias = [&](const QV4::CompiledData::Alias *alias, int encodedIndex,
210 int resolvedTargetObjectId) {
211 return appendAliasToPropertyCache(
212 &component, alias, objectIndex, aliasIndex++, encodedIndex,
213 resolvedTargetObjectId, aliasCacheCreator, error);
214 };
215
216 const auto handleDeepAlias = [&](
217 const QV4::CompiledData::Alias *alias, const QQmlPropertyCache::ConstPtr &propertyCache,
218 int coreIndex, QStringView subProperty, int resolvedTargetObjectId)
219 {
220 const QQmlPropertyResolver resolver = QQmlPropertyResolver(propertyCache);
221 const QQmlPropertyData *actualProperty = resolver.property(subProperty.toString());
222 if (!actualProperty)
223 return DeepAliasResult::NoProperty;
224
225 if (doAppendAlias(
226 alias, QQmlPropertyIndex(coreIndex, actualProperty->coreIndex()).toEncoded(),
227 resolvedTargetObjectId)) {
228 return DeepAliasResult::Success;
229 }
230
231 return DeepAliasResult::CannotAppend;
232 };
233
234 for (auto alias = obj->aliasesBegin(), end = obj->aliasesEnd(); alias != end; ++alias) {
235 if (resolvedAliases.contains(alias)) {
236 ++aliasIndex;
237 continue;
238 }
239
240 int targetObjectIndex = -1;
241 for (int i = 0, end = component.namedObjectsInComponentCount(); i < end; ++i) {
242 const int candidateIndex = component.namedObjectsInComponentTable()[i];
243 if (m_compiler->objectAt(candidateIndex)->idNameIndex == alias->idIndex()) {
244 targetObjectIndex = candidateIndex;
245 break;
246 }
247 }
248 if (targetObjectIndex == -1) {
249 *error = qQmlCompileError(
250 alias->referenceLocation(),
251 tr("Invalid alias reference. Unable to find id \"%1\"")
252 .arg(stringAt(alias->idIndex())));
253 break;
254 }
255 const QV4::CompiledData::Object *targetObject = m_compiler->objectAt(targetObjectIndex);
256 const int resolvedTargetObjectId = targetObject->objectId();
257
258 QStringView property;
259 QStringView subProperty;
260
261 const QString aliasPropertyValue = stringAt(alias->propertyNameIndex());
262 const int propertySeparator = aliasPropertyValue.indexOf(QLatin1Char('.'));
263 if (propertySeparator != -1) {
264 property = QStringView{aliasPropertyValue}.left(propertySeparator);
265 subProperty = QStringView{aliasPropertyValue}.mid(propertySeparator + 1);
266 } else {
267 property = QStringView(aliasPropertyValue);
268 }
269
270 if (property.isEmpty()) {
271 if (doAppendAlias(alias, -1, resolvedTargetObjectId))
272 continue;
273 return SomeAliasesResolved;
274 }
275
276 Q_ASSERT(!property.isEmpty());
277 QQmlPropertyCache::ConstPtr targetCache = m_propertyCaches->at(targetObjectIndex);
278 Q_ASSERT(targetCache);
279
280 const QQmlPropertyResolver resolver(targetCache);
281 const QQmlPropertyData *targetProperty = resolver.property(property.toString());
282 if (!targetProperty)
283 return SomeAliasesResolved;
284
285 const int coreIndex = targetProperty->coreIndex();
286 if (subProperty.isEmpty()) {
287 if (doAppendAlias(
288 alias, QQmlPropertyIndex(coreIndex).toEncoded(), resolvedTargetObjectId)) {
289 continue;
290 }
291 return SomeAliasesResolved;
292 }
293
294 if (const QMetaObject *valueTypeMetaObject
295 = QQmlMetaType::metaObjectForValueType(targetProperty->propType())) {
296 const int valueTypeIndex = valueTypeMetaObject->indexOfProperty(
297 subProperty.toString().toUtf8().constData());
298 if (valueTypeIndex == -1)
299 return SomeAliasesResolved;
300
301 if (doAppendAlias(
302 alias, QQmlPropertyIndex(coreIndex, valueTypeIndex).toEncoded(),
303 resolvedTargetObjectId)) {
304 continue;
305 }
306
307 return SomeAliasesResolved;
308 }
309
310 Q_ASSERT(subProperty.at(0).isLower());
311
312 bool foundDeepAliasInBindings = false;
313 for (auto it = targetObject->bindingsBegin(); it != targetObject->bindingsEnd(); ++it) {
314 if (m_compiler->stringAt(it->propertyNameIndex) != property)
315 continue;
316
317 switch (handleDeepAlias(
318 alias, m_propertyCaches->at(it->value.objectIndex), coreIndex, subProperty,
319 resolvedTargetObjectId)) {
320 case DeepAliasResult::NoProperty:
321 continue;
322 case DeepAliasResult::CannotAppend:
323 return SomeAliasesResolved;
324 case DeepAliasResult::Success:
325 foundDeepAliasInBindings = true;
326 break;
327 }
328
329 break;
330 }
331
332 if (foundDeepAliasInBindings)
333 continue;
334
335 const QQmlPropertyCache::ConstPtr typeCache
336 = QQmlMetaType::propertyCacheForType(targetProperty->propType());
337 if (!typeCache)
338 return SomeAliasesResolved;
339
340 switch (handleDeepAlias(alias, typeCache, coreIndex, subProperty, resolvedTargetObjectId)) {
341 case DeepAliasResult::NoProperty:
342 case DeepAliasResult::CannotAppend:
343 return SomeAliasesResolved;
344 case DeepAliasResult::Success:
345 break;
346 }
347 }
348
349 return AllAliasesResolved;
350}
351
352QQmlError QQmlTypeData::createTypeAndPropertyCaches(
353 const QQmlRefPointer<QQmlTypeNameCache> &typeNameCache,
354 const QV4::CompiledData::ResolvedTypeReferenceMap &resolvedTypeCache)
355{
356 assertTypeLoaderThread();
357
358 Q_ASSERT(m_compiledData);
359 m_compiledData->typeNameCache = typeNameCache;
360 m_compiledData->resolvedTypes = resolvedTypeCache;
361 m_compiledData->inlineComponentData = m_inlineComponentData;
362 m_compiledData->qmlType = m_qmlType;
363
364 QQmlPendingGroupPropertyBindings pendingGroupPropertyBindings;
365
366 {
367 QQmlPropertyCacheCreator<QV4::CompiledData::CompilationUnit> propertyCacheCreator(
368 &m_compiledData->propertyCaches, &pendingGroupPropertyBindings, m_typeLoader,
369 m_compiledData.data(), m_importCache.data(), typeClassName());
370
371 QQmlError error = propertyCacheCreator.verifyNoICCycle();
372 if (error.isValid())
373 return error;
374
375 QQmlPropertyCacheCreatorBase::IncrementalResult result;
376 do {
377 result = propertyCacheCreator.buildMetaObjectsIncrementally();
378 if (result.error.isValid()) {
379 return result.error;
380 } else {
381 QQmlComponentAndAliasResolver resolver(
382 m_compiledData.data(), &m_compiledData->propertyCaches);
383 if (const QQmlError error = resolver.resolve(result.processedRoot);
384 error.isValid()) {
385 return error;
386 }
387 pendingGroupPropertyBindings.resolveMissingPropertyCaches(
388 &m_compiledData->propertyCaches);
389 pendingGroupPropertyBindings.clear(); // anything that can be processed is now processed
390 }
391
392 } while (result.canResume);
393 }
394
395 pendingGroupPropertyBindings.resolveMissingPropertyCaches(&m_compiledData->propertyCaches);
396 return QQmlError();
397}
398
399// local helper function for inline components
400namespace {
401using InlineComponentData = QV4::CompiledData::InlineComponentData;
402
403template<typename ObjectContainer>
404void setupICs(
405 const ObjectContainer &container, QHash<QString, InlineComponentData> *icData,
406 const QUrl &baseUrl,
407 const QQmlRefPointer<QV4::CompiledData::CompilationUnit> &compilationUnit) {
408 Q_ASSERT(icData->empty());
409 for (int i = 0; i != container->objectCount(); ++i) {
410 auto root = container->objectAt(i);
411 for (auto it = root->inlineComponentsBegin(); it != root->inlineComponentsEnd(); ++it) {
412 // We cannot re-use a previously finalized inline component type here. We need our own.
413 // We can and should re-use speculative type references, though.
414 InlineComponentData icDatum(
415 QQmlMetaType::findOrCreateFactualInlineComponentType(
416 baseUrl, container->stringAt(it->nameIndex), compilationUnit),
417 int(it->objectIndex), int(it->nameIndex));
418
419 icData->insert(container->stringAt(it->nameIndex), icDatum);
420 }
421 }
422};
423}
424
425bool QQmlTypeData::checkScripts()
426{
427 // Check all script dependencies for errors
428 for (int ii = 0; ii < m_scripts.size(); ++ii) {
429 const ScriptReference &script = m_scripts.at(ii);
430 Q_ASSERT(script.script->isCompleteOrError());
431 if (script.script->isError()) {
432 createError(
433 script,
434 QQmlTypeLoader::tr("Script %1 unavailable").arg(script.script->urlString()));
435 return false;
436 }
437 }
438 return true;
439}
440
441void QQmlTypeData::createError(const TypeReference &type, const QString &message)
442{
443 createError(type, message, type.typeData ? type.typeData->errors() : QList<QQmlError>());
444}
445
446void QQmlTypeData::createError(const ScriptReference &script, const QString &message)
447{
448 createError(script, message, script.script ? script.script->errors() : QList<QQmlError>());
449}
450
451bool QQmlTypeData::checkDependencies()
452{
453 // Check all type dependencies for errors
454 for (auto it = std::as_const(m_resolvedTypes).begin(), end = std::as_const(m_resolvedTypes).end();
455 it != end; ++it) {
456 const TypeReference &type = *it;
457 Q_ASSERT(!type.typeData
458 || type.typeData->isCompleteOrError()
459 || type.type.isInlineComponentType());
460
461 if (type.typeData && type.typeData->isError()) {
462 const QString &typeName = stringAt(it.key());
463 createError(type, QQmlTypeLoader::tr("Type %1 unavailable").arg(typeName));
464 return false;
465 }
466
467 if (!type.selfReference && type.type.isInlineComponentType()) {
468 const QString icName = type.type.elementName();
469 Q_ASSERT(!icName.isEmpty());
470
471 // We have a CU here. Check if the inline component exists.
472 if (type.typeData && type.typeData->compilationUnit()->inlineComponentId(icName) >= 0)
473 return true;
474
475 const QString typeName = stringAt(it.key());
476 const qsizetype lastDot = typeName.lastIndexOf(u'.');
477 createError(
478 type,
479 QQmlTypeLoader::tr("Type %1 has no inline component type called %2")
480 .arg(QStringView{typeName}.left(lastDot), icName));
481 return false;
482 }
483 }
484
485 return true;
486}
487
488bool QQmlTypeData::checkCompositeSingletons()
489{
490 // Check all composite singleton type dependencies for errors
491 for (int ii = 0; ii < m_compositeSingletons.size(); ++ii) {
492 const TypeReference &type = m_compositeSingletons.at(ii);
493 Q_ASSERT(!type.typeData || type.typeData->isCompleteOrError());
494 if (type.typeData && type.typeData->isError()) {
495 QString typeName = type.type.qmlTypeName();
496 createError(type, QQmlTypeLoader::tr("Type %1 unavailable").arg(typeName));
497 return false;
498 }
499 }
500
501 return true;
502}
503
504void QQmlTypeData::createQQmlType()
505{
506 if (QQmlPropertyCacheCreatorBase::canCreateClassNameTypeByUrl(finalUrl())) {
507 const bool isSingleton = m_document
508 ? m_document.data()->isSingleton()
509 : (m_compiledData->unitData()->flags & QV4::CompiledData::Unit::IsSingleton);
510 m_qmlType = QQmlMetaType::findCompositeType(
511 url(), m_compiledData, isSingleton
512 ? QQmlMetaType::Singleton
513 : QQmlMetaType::NonSingleton);
514 m_typeClassName = QByteArray(m_qmlType.typeId().name()).chopped(1);
515 }
516}
517
518bool QQmlTypeData::rebuildFromSource()
519{
520 // Clear and re-build everything.
521
522 m_typeReferences.clear();
523 m_scripts.clear();
524 m_namespaces.clear();
525 m_compositeSingletons.clear();
526
527 m_resolvedTypes.clear();
528 m_typesResolved = false;
529
530 m_qmlType = QQmlType();
531 m_typeClassName.clear();
532
533 m_inlineComponentData.clear();
534 m_compiledData.reset();
535
536 m_implicitImportLoaded = false;
537
538 m_importCache.adopt(new QQmlImports);
539 m_unresolvedImports.clear();
540
541 if (!loadFromSource())
542 return false;
543
544 continueLoadFromIR();
545
546 if (!resolveTypes())
547 return false;
548
549 if (!checkScripts())
550 return false;
551
552 if (!checkDependencies())
553 return false;
554
555 if (!checkCompositeSingletons())
556 return false;
557
558 createQQmlType();
559
560 setupICs(m_document, &m_inlineComponentData, finalUrl(), m_compiledData);
561 return true;
562}
563
564void QQmlTypeData::done()
565{
566 assertTypeLoaderThread();
567
568 auto cleanup = qScopeGuard([this]{
569 m_backupSourceCode = SourceCodeData();
570 m_document.reset();
571 m_typeReferences.clear();
572 if (isError()) {
573 const auto encounteredErrors = errors();
574 for (const QQmlError &e : encounteredErrors)
575 qCDebug(DBG_DISK_CACHE) << e.toString();
576 m_compiledData.reset();
577 // Clear resolved types, scripts, and composite singletons to break
578 // potential circular references (e.g., A depends on B, B depends on A)
579 m_resolvedTypes.clear();
580 m_compositeSingletons.clear();
581 m_scripts.clear();
582 }
583 });
584
585 if (isError())
586 return;
587
588 if (!checkScripts())
589 return;
590
591 if (!checkDependencies())
592 return;
593
594 if (!checkCompositeSingletons())
595 return;
596
597 createQQmlType();
598
599 if (m_document)
600 setupICs(m_document, &m_inlineComponentData, finalUrl(), m_compiledData);
601 else
602 setupICs(m_compiledData, &m_inlineComponentData, finalUrl(), m_compiledData);
603
604 QV4::CompiledData::ResolvedTypeReferenceMap resolvedTypeCache;
605 QQmlRefPointer<QQmlTypeNameCache> typeNameCache;
606
607 // If we've pulled the CU from the memory cache, we don't need to do any verification.
608 const bool verifyCaches = !m_compiledData
609 || (m_compiledData->resolvedTypes.isEmpty() && !m_compiledData->typeNameCache);
610
611 if (verifyCaches) {
612 QQmlError error = buildTypeResolutionCaches(&typeNameCache, &resolvedTypeCache);
613 if (error.isValid()) {
614 setError(error);
615 qDeleteAll(resolvedTypeCache);
616 return;
617 }
618 }
619
620 const auto dependencyHasher = [&resolvedTypeCache, this]() {
621 return typeLoader()->hashDependencies(&resolvedTypeCache, m_compositeSingletons);
622 };
623
624 // verify if any dependencies changed if we're using a cache
625 if (m_document.isNull() && verifyCaches) {
626 const QQmlError error = createTypeAndPropertyCaches(typeNameCache, resolvedTypeCache);
627 if (error.isValid() || !m_compiledData->verifyChecksum(dependencyHasher)) {
628
629 if (error.isValid()) {
630 qCDebug(DBG_DISK_CACHE)
631 << "Failed to create property caches for"
632 << m_compiledData->fileName()
633 << "because" << error.description();
634 } else {
635 qCDebug(DBG_DISK_CACHE)
636 << "Checksum mismatch for cached version of"
637 << m_compiledData->fileName();
638 }
639
640 resolvedTypeCache.clear();
641 typeNameCache.reset();
642
643 if (!rebuildFromSource())
644 return;
645
646 const QQmlError error = buildTypeResolutionCaches(&typeNameCache, &resolvedTypeCache);
647 if (error.isValid()) {
648 setError(error);
649 qDeleteAll(resolvedTypeCache);
650 return;
651 }
652 }
653 }
654
655 if (!m_document.isNull()) {
656 Q_ASSERT(verifyCaches);
657 // Compile component
658 compile(typeNameCache, &resolvedTypeCache, dependencyHasher);
659 if (isError())
660 return;
661 }
662
663 {
664 m_compiledData->inlineComponentData = m_inlineComponentData;
665 {
666 // Sanity check property bindings
667 QQmlPropertyValidator validator(typeLoader(), m_importCache.data(), m_compiledData);
668 QList<QQmlError> errors = validator.validate();
669 if (!errors.isEmpty()) {
670 setError(errors);
671 return;
672 }
673 }
674
675 m_compiledData->finalizeCompositeType(qmlType());
676 }
677
678 {
679 QQmlType type = QQmlMetaType::qmlType(finalUrl());
680 if (m_compiledData && m_compiledData->unitData()->flags & QV4::CompiledData::Unit::IsSingleton) {
681 if (!type.isValid()) {
682 QQmlError error;
683 error.setDescription(QQmlTypeLoader::tr("No matching type found, pragma Singleton files cannot be used by QQmlComponent."));
684 setError(error);
685 return;
686 } else if (!type.isCompositeSingleton()) {
687 QQmlError error;
688 error.setDescription(QQmlTypeLoader::tr("pragma Singleton used with a non composite singleton type %1").arg(type.qmlTypeName()));
689 setError(error);
690 return;
691 }
692 } else {
693 // If the type is CompositeSingleton but there was no pragma Singleton in the
694 // QML file, lets report an error.
695 if (type.isValid() && type.isCompositeSingleton()) {
696 QString typeName = type.qmlTypeName();
697 setError(QQmlTypeLoader::tr("qmldir defines type as singleton, but no pragma Singleton found in type %1.").arg(typeName));
698 return;
699 }
700 }
701 }
702
703 {
704 // Collect imported scripts
705 m_compiledData->dependentScripts.reserve(m_scripts.size());
706 for (int scriptIndex = 0; scriptIndex < m_scripts.size(); ++scriptIndex) {
707 const QQmlTypeData::ScriptReference &script = m_scripts.at(scriptIndex);
708
709 QStringView qualifier(script.qualifier);
710 QString enclosingNamespace;
711
712 const int lastDotIndex = qualifier.lastIndexOf(QLatin1Char('.'));
713 if (lastDotIndex != -1) {
714 enclosingNamespace = qualifier.left(lastDotIndex).toString();
715 qualifier = qualifier.mid(lastDotIndex+1);
716 }
717
718 m_compiledData->typeNameCache->add(
719 qualifier.toString(), scriptIndex, enclosingNamespace);
720 QQmlRefPointer<QQmlScriptData> scriptData = script.script->scriptData();
721 m_compiledData->dependentScripts << scriptData;
722 }
723 }
724}
725
726bool QQmlTypeData::loadImplicitImport()
727{
728 assertTypeLoaderThread();
729
730 m_implicitImportLoaded = true; // Even if we hit an error, count as loaded (we'd just keep hitting the error)
731
732 m_importCache->setBaseUrl(finalUrl(), finalUrlString());
733
734 // For local urls, add an implicit import "." as most overridden lookup.
735 // This will also trigger the loading of the qmldir and the import of any native
736 // types from available plugins.
737 QList<QQmlError> implicitImportErrors;
738 QString localQmldir;
739 m_importCache->addImplicitImport(typeLoader(), &localQmldir, &implicitImportErrors);
740
741 // When loading with QQmlImports::ImportImplicit, the imports are _appended_ to the namespace
742 // in the order they are loaded. Therefore, the addImplicitImport above gets the highest
743 // precedence. This is in contrast to normal priority imports. Those are _prepended_ in the
744 // order they are loaded.
745 if (!localQmldir.isEmpty()) {
746 const QQmlTypeLoaderQmldirContent qmldir = typeLoader()->qmldirContent(localQmldir);
747 const QList<QQmlDirParser::Import> moduleImports
748 = QQmlMetaType::moduleImports(qmldir.typeNamespace(), QTypeRevision())
749 + qmldir.imports();
750 loadDependentImports(moduleImports, QString(), QTypeRevision(),
751 QQmlImportInstance::Implicit + 1, QQmlImports::ImportNoFlag,
752 &implicitImportErrors);
753 }
754
755 if (!implicitImportErrors.isEmpty()) {
756 setError(implicitImportErrors);
757 return false;
758 }
759
760 return true;
761}
762
763void QQmlTypeData::dataReceived(const SourceCodeData &data)
764{
765 assertTypeLoaderThread();
766
767 m_backupSourceCode = data;
768
769 if (tryLoadFromDiskCache())
770 return;
771
772 if (isError())
773 return;
774
775 if (!m_backupSourceCode.exists() || m_backupSourceCode.isEmpty()) {
776 if (m_cachedUnitStatus == QQmlMetaType::CachedUnitLookupError::VersionMismatch)
777 setError(QQmlTypeLoader::tr("File was compiled ahead of time with an incompatible version of Qt and the original file cannot be found. Please recompile"));
778 else if (!m_backupSourceCode.exists())
779 setError(QQmlTypeLoader::tr("No such file or directory"));
780 else
781 setError(QQmlTypeLoader::tr("File is empty"));
782 return;
783 }
784
785 if (!loadFromSource())
786 return;
787
788 continueLoadFromIR();
789}
790
791void QQmlTypeData::initializeFromCachedUnit(const QQmlPrivate::CachedQmlUnit *unit)
792{
793 assertTypeLoaderThread();
794
795 if (unit->qmlData->qmlUnit()->nObjects == 0) {
796 setError(QQmlTypeLoader::tr("Cached QML Unit has no objects"));
797 return;
798 }
799
800 m_document.reset(
801 new QmlIR::Document(urlString(), finalUrlString(), m_typeLoader->isDebugging()));
802 QQmlIRLoader loader(unit->qmlData, m_document.data());
803 loader.load();
804 m_document->javaScriptCompilationUnit
805 = QQmlRefPointer<QV4::CompiledData::CompilationUnit>(
806 new QV4::CompiledData::CompilationUnit(unit->qmlData, unit->aotCompiledFunctions),
807 QQmlRefPointer<QV4::CompiledData::CompilationUnit>::Adopt);
808 continueLoadFromIR();
809}
810
811bool QQmlTypeData::loadFromSource()
812{
813 assertTypeLoaderThread();
814
815 m_document.reset(
816 new QmlIR::Document(urlString(), finalUrlString(), m_typeLoader->isDebugging()));
817 m_document->jsModule.sourceTimeStamp = m_backupSourceCode.sourceTimeStamp();
818 QmlIR::IRBuilder compiler;
819
820 QString sourceError;
821 const QString source = m_backupSourceCode.readAll(&sourceError);
822 if (!sourceError.isEmpty()) {
823 setError(sourceError);
824 return false;
825 }
826
827 if (!compiler.generateFromQml(source, finalUrlString(), m_document.data())) {
828 QList<QQmlError> errors;
829 errors.reserve(compiler.errors.size());
830 for (const QQmlJS::DiagnosticMessage &msg : std::as_const(compiler.errors)) {
831 QQmlError e;
832 e.setUrl(url());
833 e.setLine(qmlConvertSourceCoordinate<quint32, int>(msg.loc.startLine));
834 e.setColumn(qmlConvertSourceCoordinate<quint32, int>(msg.loc.startColumn));
835 e.setDescription(msg.message);
836 errors << e;
837 }
838 setError(errors);
839 return false;
840 }
841 return true;
842}
843
844void QQmlTypeData::restoreIR(const QQmlRefPointer<QV4::CompiledData::CompilationUnit> &unit)
845{
846 assertTypeLoaderThread();
847
848 m_document.reset(
849 new QmlIR::Document(urlString(), finalUrlString(), m_typeLoader->isDebugging()));
850 QQmlIRLoader loader(unit->unitData(), m_document.data());
851 loader.load();
852 m_document->javaScriptCompilationUnit = unit;
853 continueLoadFromIR();
854}
855
856void QQmlTypeData::continueLoadFromIR()
857{
858 assertTypeLoaderThread();
859
860 for (auto const& object: std::as_const(m_document->objects)) {
861 for (auto it = object->inlineComponentsBegin(); it != object->inlineComponentsEnd(); ++it) {
862 QString const nameString = m_document->stringAt(it->nameIndex);
863 auto importUrl = finalUrl();
864 importUrl.setFragment(nameString);
865 auto import = new QQmlImportInstance(); // Note: The cache takes ownership of the QQmlImportInstance
866 m_importCache->addInlineComponentImport(import, nameString, importUrl);
867 }
868 }
869
870 m_typeReferences.collectFromObjects(m_document->objects.constBegin(), m_document->objects.constEnd());
871 m_importCache->setBaseUrl(finalUrl(), finalUrlString());
872
873 // For remote URLs, we don't delay the loading of the implicit import
874 // because the loading probably requires an asynchronous fetch of the
875 // qmldir (so we can't load it just in time).
876 if (!finalUrl().scheme().isEmpty()) {
877 QUrl qmldirUrl = finalUrl().resolved(QUrl(QLatin1String("qmldir")));
878 if (!QQmlImports::isLocal(qmldirUrl)) {
879 if (!loadImplicitImport())
880 return;
881 // This qmldir is for the implicit import
882 auto implicitImport = std::make_shared<PendingImport>();
883 implicitImport->uri = QLatin1String(".");
884 implicitImport->version = QTypeRevision();
885 QList<QQmlError> errors;
886
887 if (!fetchQmldir(qmldirUrl, implicitImport, 1, &errors)) {
888 setError(errors);
889 return;
890 }
891 }
892 }
893
894 QList<QQmlError> errors;
895
896 for (const QV4::CompiledData::Import *import : std::as_const(m_document->imports)) {
897 if (!addImport(import, {}, &errors)) {
898 Q_ASSERT(errors.size());
899
900 // We're only interested in the chronoligically last error. The previous
901 // errors might be from unsuccessfully trying to load a module from the
902 // resource file system.
903 QQmlError error = errors.first();
904 error.setUrl(m_importCache->baseUrl());
905 error.setLine(qmlConvertSourceCoordinate<quint32, int>(import->location.line()));
906 error.setColumn(qmlConvertSourceCoordinate<quint32, int>(import->location.column()));
907 setError(error);
908 return;
909 }
910 }
911}
912
913void QQmlTypeData::allDependenciesDone()
914{
915 assertTypeLoaderThread();
916
917 QQmlTypeLoader::Blob::allDependenciesDone();
918
919 if (!m_typesResolved)
920 resolveTypes();
921}
922
923QString QQmlTypeData::stringAt(int index) const
924{
925 if (m_compiledData)
926 return m_compiledData->stringAt(index);
927 return m_document->jsGenerator.stringTable.stringForIndex(index);
928}
929
930void QQmlTypeData::compile(const QQmlRefPointer<QQmlTypeNameCache> &typeNameCache,
931 QV4::CompiledData::ResolvedTypeReferenceMap *resolvedTypeCache,
932 const QV4::CompiledData::DependentTypesHasher &dependencyHasher)
933{
934 assertTypeLoaderThread();
935
936 Q_ASSERT(m_compiledData.isNull());
937
938 const bool typeRecompilation = m_document
939 && m_document->javaScriptCompilationUnit
940 && m_document->javaScriptCompilationUnit->unitData()
941 && (m_document->javaScriptCompilationUnit->unitData()->flags
942 & QV4::CompiledData::Unit::PendingTypeCompilation);
943
944 QQmlTypeCompiler compiler(
945 typeLoader(), this, m_document.data(), resolvedTypeCache, dependencyHasher);
946 auto compilationUnit = compiler.compile();
947 if (!compilationUnit) {
948 qDeleteAll(*resolvedTypeCache);
949 resolvedTypeCache->clear();
950 setError(compiler.compilationErrors());
951 return;
952 }
953
954 const bool trySaveToDisk = m_typeLoader->writeCacheFile() && !typeRecompilation;
955 if (trySaveToDisk) {
956 QString errorString;
957 if (compilationUnit->saveToDisk(url(), &errorString)) {
958 QString error;
959 if (!compilationUnit->loadFromDisk(url(), m_backupSourceCode.sourceTimeStamp(), &error)) {
960 // ignore error, keep using the in-memory compilation unit.
961 }
962 } else {
963 qCDebug(DBG_DISK_CACHE) << "Error saving cached version of"
964 << compilationUnit->fileName() << "to disk:" << errorString;
965 }
966 }
967
968 m_compiledData = std::move(compilationUnit);
969 m_compiledData->typeNameCache = typeNameCache;
970 m_compiledData->resolvedTypes = *resolvedTypeCache;
971 m_compiledData->propertyCaches = std::move(*compiler.propertyCaches());
972 Q_ASSERT(m_compiledData->propertyCaches.count()
973 >= static_cast<int>(m_compiledData->objectCount()));
974}
975
976bool QQmlTypeData::resolveTypes()
977{
978 assertTypeLoaderThread();
979
980 Q_ASSERT(!m_typesResolved);
981
982 // Check that all imports were resolved
983 QList<QQmlError> errors;
984 auto it = m_unresolvedImports.constBegin(), end = m_unresolvedImports.constEnd();
985 for ( ; it != end; ++it) {
986 const PendingImportPtr &import = *it;
987 if (import->priority != 0)
988 continue;
989
990 // If the import was potentially remote and all the network requests have failed,
991 // we now know that there is no qmldir. We can register its types.
992 if (registerPendingTypes(import))
993 continue;
994
995 // This import was not resolved
996 QQmlError error;
997 error.setDescription(QQmlTypeLoader::tr("module \"%1\" is not installed").arg(import->uri));
998 error.setUrl(m_importCache->baseUrl());
999 error.setLine(qmlConvertSourceCoordinate<quint32, int>(
1000 import->location.line()));
1001 error.setColumn(qmlConvertSourceCoordinate<quint32, int>(
1002 import->location.column()));
1003 errors.prepend(error);
1004 }
1005
1006 if (errors.size()) {
1007 setError(errors);
1008 return false;
1009 }
1010
1011 // Load the implicit import since it may have additional scripts.
1012 if (!m_implicitImportLoaded && !loadImplicitImport())
1013 return false;
1014
1015 // Add any imported scripts to our resolved set
1016 const auto resolvedScripts = m_importCache->resolvedScripts();
1017 for (const QQmlImports::ScriptReference &script : resolvedScripts) {
1018 QQmlRefPointer<QQmlScriptBlob> blob
1019 = typeLoader()->getScript(script.location, script.fileName);
1020 addDependency(blob.data());
1021
1022 ScriptReference ref;
1023 //ref.location = ...
1024 if (!script.qualifier.isEmpty())
1025 {
1026 ref.qualifier = script.qualifier + QLatin1Char('.') + script.nameSpace;
1027 // Add a reference to the enclosing namespace
1028 m_namespaces.insert(script.qualifier);
1029 } else {
1030 ref.qualifier = script.nameSpace;
1031 }
1032
1033 ref.script = blob;
1034 m_scripts << ref;
1035 }
1036
1037 // Lets handle resolved composite singleton types
1038 const auto resolvedCompositeSingletons = m_importCache->resolvedCompositeSingletons();
1039 for (const QQmlImports::CompositeSingletonReference &csRef : resolvedCompositeSingletons) {
1040 TypeReference ref;
1041 QString typeName;
1042 if (!csRef.prefix.isEmpty()) {
1043 typeName = csRef.prefix + QLatin1Char('.') + csRef.typeName;
1044 // Add a reference to the enclosing namespace
1045 m_namespaces.insert(csRef.prefix);
1046 } else {
1047 typeName = csRef.typeName;
1048 }
1049
1050 QTypeRevision version = csRef.version;
1051 if (!resolveType(typeName, version, ref, -1, -1, true, QQmlType::CompositeSingletonType))
1052 return false;
1053
1054 if (ref.type.isCompositeSingleton()) {
1055 ref.typeData = typeLoader()->getType(ref.type.sourceUrl());
1056 if (ref.typeData->isWaiting() || m_waitingOnMe.contains(ref.typeData.data())) {
1057 qCDebug(lcCycle) << "Possible cyclic dependency detected between"
1058 << ref.typeData->urlString() << "and" << urlString();
1059 continue;
1060 }
1061 addDependency(ref.typeData.data());
1062 ref.prefix = csRef.prefix;
1063
1064 m_compositeSingletons << ref;
1065 }
1066 }
1067
1068 for (auto unresolvedRef = m_typeReferences.constBegin(), end = m_typeReferences.constEnd();
1069 unresolvedRef != end; ++unresolvedRef) {
1070
1071 TypeReference ref; // resolved reference
1072
1073 const bool reportErrors = unresolvedRef->errorWhenNotFound;
1074
1075 QTypeRevision version;
1076
1077 const QString name = stringAt(unresolvedRef.key());
1078
1079 bool *selfReferenceDetection = unresolvedRef->needsCreation ? nullptr : &ref.selfReference;
1080
1081 if (!resolveType(name, version, ref, unresolvedRef->location.line(),
1082 unresolvedRef->location.column(), reportErrors,
1083 QQmlType::AnyRegistrationType, selfReferenceDetection) && reportErrors)
1084 return false;
1085
1086 if (ref.selfReference) {
1087 // nothing to do
1088 } else if (ref.type.isComposite()) {
1089 ref.typeData = typeLoader()->getType(ref.type.sourceUrl());
1090 addDependency(ref.typeData.data());
1091 } else if (ref.type.isInlineComponentType()) {
1092 QUrl containingTypeUrl = ref.type.sourceUrl();
1093 Q_ASSERT(!containingTypeUrl.isEmpty());
1094 if (QQmlMetaType::equalBaseUrls(finalUrl(), containingTypeUrl)) {
1095 ref.selfReference = true;
1096 } else {
1097 containingTypeUrl.setFragment(QString());
1098 auto typeData = typeLoader()->getType(containingTypeUrl);
1099 Q_ASSERT(typeData.data() != this);
1100 ref.typeData = typeData;
1101 addDependency(typeData.data());
1102 }
1103 }
1104
1105 ref.version = version;
1106 ref.location = unresolvedRef->location;
1107 ref.needsCreation = unresolvedRef->needsCreation;
1108 m_resolvedTypes.insert(unresolvedRef.key(), ref);
1109 }
1110
1111 m_typesResolved = true;
1112 return true;
1113}
1114
1115QQmlError QQmlTypeData::buildTypeResolutionCaches(
1116 QQmlRefPointer<QQmlTypeNameCache> *typeNameCache,
1117 QV4::CompiledData::ResolvedTypeReferenceMap *resolvedTypeCache) const
1118{
1119 assertTypeLoaderThread();
1120
1121 typeNameCache->adopt(new QQmlTypeNameCache(m_importCache));
1122
1123 for (const QString &ns: m_namespaces)
1124 (*typeNameCache)->add(ns);
1125
1126 // Add any Composite Singletons that were used to the import cache
1127 for (const QQmlTypeData::TypeReference &singleton: m_compositeSingletons)
1128 (*typeNameCache)->add(singleton.type.qmlTypeName(), singleton.type.sourceUrl(), singleton.prefix);
1129
1130 m_importCache->populateCache(typeNameCache->data());
1131
1132 for (auto resolvedType = m_resolvedTypes.constBegin(), end = m_resolvedTypes.constEnd(); resolvedType != end; ++resolvedType) {
1133 auto ref = std::make_unique<QV4::ResolvedTypeReference>();
1134 QQmlType qmlType = resolvedType->type;
1135 ref->setType(qmlType);
1136 ref->setIsSelfReference(resolvedType->selfReference);
1137 if (resolvedType->typeData) {
1138 if (resolvedType->needsCreation && qmlType.isCompositeSingleton()) {
1139 return qQmlCompileError(resolvedType->location, tr("Composite Singleton Type %1 is not creatable.").arg(qmlType.qmlTypeName()));
1140 }
1141 const auto compilationUnit = resolvedType->typeData->compilationUnit();
1142 if (qmlType.isInlineComponentType()) {
1143 // Inline component which is part of an already resolved type
1144 QString icName = qmlType.elementName();
1145 Q_ASSERT(!icName.isEmpty());
1146
1147 ref->setTypePropertyCache(compilationUnit->propertyCaches.at(
1148 compilationUnit->inlineComponentId(icName)));
1149 Q_ASSERT(ref->type().isInlineComponentType());
1150 } else {
1151 ref->setTypePropertyCache(compilationUnit->rootPropertyCache());
1152 }
1153 if (!resolvedType->selfReference)
1154 ref->setCompilationUnit(compilationUnit);
1155 } else if (qmlType.isInlineComponentType()) {
1156 // Inline component.
1157 // If it's from a different file we have a typeData and can't get here.
1158 // If it's defined in the same file we're currently compiling, we don't want to use it.
1159 // We're going to fill in the property caches later after all.
1160 Q_ASSERT(resolvedType->selfReference);
1161 Q_ASSERT(ref->isSelfReference());
1162 } else if (qmlType.isValid() && !resolvedType->selfReference) {
1163 Q_ASSERT(ref->type().isValid());
1164
1165 if (resolvedType->needsCreation && !qmlType.isCreatable()) {
1166 QString reason = qmlType.noCreationReason();
1167 if (reason.isEmpty())
1168 reason = tr("Element is not creatable.");
1169 return qQmlCompileError(resolvedType->location, reason);
1170 }
1171
1172 if (qmlType.containsRevisionedAttributes()) {
1173 // It can only have (revisioned) properties or methods if it has a metaobject
1174 Q_ASSERT(qmlType.metaObject());
1175 ref->setTypePropertyCache(
1176 QQmlMetaType::propertyCache(qmlType, resolvedType->version));
1177 }
1178 }
1179 ref->setVersion(resolvedType->version);
1180 ref->doDynamicTypeCheck();
1181 resolvedTypeCache->insert(resolvedType.key(), ref.release());
1182 }
1183 QQmlError noError;
1184 return noError;
1185}
1186
1187bool QQmlTypeData::resolveType(const QString &typeName, QTypeRevision &version,
1188 TypeReference &ref, int lineNumber, int columnNumber,
1189 bool reportErrors, QQmlType::RegistrationType registrationType,
1190 bool *typeRecursionDetected)
1191{
1192 assertTypeLoaderThread();
1193
1194 QQmlImportNamespace *typeNamespace = nullptr;
1195 QList<QQmlError> errors;
1196
1197 bool typeFound = m_importCache->resolveType(
1198 typeLoader(), typeName, &ref.type, &version, &typeNamespace, &errors, registrationType,
1199 typeRecursionDetected);
1200 if (!typeNamespace && !typeFound && !m_implicitImportLoaded) {
1201 // Lazy loading of implicit import
1202 if (loadImplicitImport()) {
1203 // Try again to find the type
1204 errors.clear();
1205 typeFound = m_importCache->resolveType(
1206 typeLoader(), typeName, &ref.type, &version, &typeNamespace, &errors,
1207 registrationType, typeRecursionDetected);
1208 } else {
1209 return false; //loadImplicitImport() hit an error, and called setError already
1210 }
1211 }
1212
1213 if ((!typeFound || typeNamespace) && reportErrors) {
1214 // Known to not be a type:
1215 // - known to be a namespace (Namespace {})
1216 // - type with unknown namespace (UnknownNamespace.SomeType {})
1217 QQmlError error;
1218 if (typeNamespace) {
1219 error.setDescription(QQmlTypeLoader::tr("Namespace %1 cannot be used as a type").arg(typeName));
1220 } else {
1221 if (errors.size()) {
1222 error = errors.takeFirst();
1223 } else {
1224 // this should not be possible!
1225 // Description should come from error provided by addImport() function.
1226 error.setDescription(QQmlTypeLoader::tr("Unreported error adding script import to import database"));
1227 }
1228 error.setUrl(m_importCache->baseUrl());
1229 error.setDescription(QQmlTypeLoader::tr("%1 %2").arg(typeName, error.description()));
1230 }
1231
1232 if (lineNumber != -1)
1233 error.setLine(lineNumber);
1234 if (columnNumber != -1)
1235 error.setColumn(columnNumber);
1236
1237 errors.prepend(error);
1238 setError(errors);
1239 return false;
1240 }
1241
1242 return true;
1243}
1244
1245void QQmlTypeData::scriptImported(
1246 const QQmlRefPointer<QQmlScriptBlob> &blob, const QV4::CompiledData::Location &location,
1247 const QString &nameSpace, const QString &qualifier)
1248{
1249 assertTypeLoaderThread();
1250
1251 ScriptReference ref;
1252 ref.script = blob;
1253 ref.location = location;
1254 ref.qualifier = qualifier.isEmpty() ? nameSpace : qualifier + QLatin1Char('.') + nameSpace;
1255
1256 m_scripts << ref;
1257}
1258
1259QT_END_NAMESPACE
Q_LOGGING_CATEGORY(lcEventDispatcher, "qt.eventdispatcher")
DeepAliasResult