148QQmlJSImportVisitor::QQmlJSImportVisitor(QQmlJSImporter *importer, QQmlJSLogger *logger,
149 const QString &implicitImportDirectory,
150 const QStringList &qmldirFiles)
151 : m_implicitImportDirectory(implicitImportDirectory),
152 m_qmldirFiles(qmldirFiles),
153 m_exportedRootScope(QQmlJSScope::resetForReparse(importer->importFile(logger->filePath()))),
154 m_importer(importer),
156 m_rootScopeImports(QQmlJS::ContextualTypes(
157 QQmlJS::ContextualTypes::QML, { }, { },
158 importer->builtinInternalNames().contextualTypes().arrayType()),
164 m_exportedRootScope->setScopeType(QQmlSA::ScopeType::QMLScope);
165 m_exportedRootScope->setBaseTypeName(QQmlJSImporter::s_inProcessMarker);
166 m_exportedRootScope->setFilePath(m_logger->filePath());
167 m_exportedRootScope->setIsComposite(
true);
170
171
172
173
174
175 auto globalScope = QQmlJSScope::create();
176 globalScope->setInternalName(u"global"_s);
177 globalScope->setScopeType(QQmlSA::ScopeType::JSFunctionScope);
179 QQmlJSScope::JavaScriptIdentifier globalJavaScript = {
180 QQmlJSScope::JavaScriptIdentifier::LexicalScoped, QQmlJS::SourceLocation(), std::nullopt,
184 QV4::Compiler::Codegen::forEachGlobalName([&](QLatin1StringView globalName) {
185 globalScope->insertJSIdentifier(globalName, globalJavaScript);
188 m_globalScope = globalScope;
189 m_currentScope = globalScope;
192QQmlJSImportVisitor::~QQmlJSImportVisitor() =
default;
194void QQmlJSImportVisitor::populateCurrentScope(
195 QQmlJSScope::ScopeType type,
const QString &name,
const QQmlJS::SourceLocation &location)
197 m_currentScope->setScopeType(type);
198 m_currentScope->setIsComposite(
true);
199 m_currentScope->setFilePath(m_logger->filePath());
200 m_currentScope->setSourceLocation(location);
201 setScopeName(m_currentScope, type, name);
202 m_scopesByIrLocation.insert({ location.startLine, location.startColumn }, m_currentScope);
205void QQmlJSImportVisitor::enterRootScope(QQmlJSScope::ScopeType type,
const QString &name,
const QQmlJS::SourceLocation &location)
207 Q_ASSERT(m_currentScope == m_globalScope);
208 QQmlJSScope::reparent(m_currentScope, m_exportedRootScope);
209 m_currentScope = m_exportedRootScope;
210 populateCurrentScope(type, name, location);
213void QQmlJSImportVisitor::enterEnvironment(QQmlJSScope::ScopeType type,
const QString &name,
214 const QQmlJS::SourceLocation &location)
216 QQmlJSScope::Ptr newScope = QQmlJSScope::create();
217 QQmlJSScope::reparent(m_currentScope, newScope);
218 m_currentScope = std::move(newScope);
219 populateCurrentScope(type, name, location);
222bool QQmlJSImportVisitor::enterEnvironmentNonUnique(QQmlJSScope::ScopeType type,
224 const QQmlJS::SourceLocation &location)
226 Q_ASSERT(type == QQmlSA::ScopeType::GroupedPropertyScope
227 || type == QQmlSA::ScopeType::AttachedPropertyScope);
229 const auto pred = [&](
const QQmlJSScope::ConstPtr &s) {
232 return s->internalName() == name;
234 const auto scopes = m_currentScope->childScopes();
237 auto it = std::find_if(scopes.begin(), scopes.end(), pred);
238 if (it == scopes.end()) {
240 enterEnvironment(type, name, location);
244 m_scopesByIrLocation.insert({ location.startLine, location.startColumn }, *it);
245 m_currentScope = *it;
249void QQmlJSImportVisitor::leaveEnvironment()
251 m_currentScope = m_currentScope->parentScope();
254void QQmlJSImportVisitor::warnUnresolvedType(
const QQmlJSScope::ConstPtr &type)
const
256 m_logger->log(QStringLiteral(
"Type %1 is used but it is not resolved")
257 .arg(QQmlJSUtils::getScopeName(type, type->scopeType())),
258 qmlUnresolvedType, type->sourceLocation());
261void QQmlJSImportVisitor::warnMissingPropertyForBinding(
262 const QString &property,
const QQmlJS::SourceLocation &location,
263 const std::optional<QQmlJSFixSuggestion> &fixSuggestion)
265 m_logger->log(QStringLiteral(
"Could not find property \"%1\".").arg(property),
266 qmlMissingProperty, location,
true,
true, fixSuggestion);
274QQmlJSImportVisitor::AliasPropertyResolution
275QQmlJSImportVisitor::resolveAliasProperty(
const QQmlJSScope::Ptr &object,
276 const QQmlJSMetaProperty &property)
278 AliasPropertyResolution result = Resolved;
279 QStringList components = property.aliasExpression().split(u'.');
280 QQmlJSMetaProperty targetProperty;
282 bool foundProperty =
false;
283 bool hasWarnedAlready =
false;
286 QQmlJSScope::ConstPtr type = m_scopesById.scope(components.takeFirst(), object);
287 QQmlJSScope::ConstPtr typeScope;
288 if (!type.isNull()) {
289 foundProperty =
true;
296 while (type && !components.isEmpty()) {
297 const QString name = components.takeFirst();
299 if (!checkTypeResolved(type)) {
300 hasWarnedAlready =
true;
305 if (!type->hasProperty(name)) {
306 foundProperty =
false;
311 const auto target = type->property(name);
312 if (!target.type()) {
313 if (target.isAlias()) {
314 result = NeedsRequeue;
318 hasWarnedAlready = QQmlJSScope::ownerOfProperty(type, name).scope->filePath()
319 == m_exportedRootScope->filePath();
323 type = target.type();
324 targetProperty = target;
329 if (result == NeedsRequeue)
331 if (!hasWarnedAlready) {
333 m_logger->log(QStringLiteral(
"Cannot deduce type of alias \"%1\"")
334 .arg(property.propertyName()),
335 qmlMissingType, property.sourceLocation());
338 QStringLiteral(
"Cannot resolve alias \"%1\"").arg(property.propertyName()),
339 qmlUnresolvedAlias, property.sourceLocation());
343 Q_ASSERT(property.index() >= 0);
344 object->addOwnProperty(property);
347 QQmlJSMetaProperty newProperty = property;
348 newProperty.setType(type);
350 newProperty.setIsList(targetProperty.isList());
351 newProperty.setIsWritable(targetProperty.isWritable());
352 newProperty.setIsFinal(targetProperty.isFinal());
353 newProperty.setIsPointer(targetProperty.isPointer());
355 const bool onlyId = !property.aliasExpression().contains(u'.');
357 newProperty.setAliasTargetScope(type);
358 newProperty.setAliasTargetName(QStringLiteral(
"id-only-alias"));
360 const auto &ownerScope =
361 QQmlJSScope::ownerOfProperty(typeScope, targetProperty.propertyName()).scope;
362 newProperty.setAliasTargetScope(ownerScope);
363 newProperty.setAliasTargetName(targetProperty.propertyName());
366 if (
const QString internalName = type->internalName(); !internalName.isEmpty())
367 newProperty.setTypeName(internalName);
369 Q_ASSERT(newProperty.index() >= 0);
370 object->addOwnProperty(newProperty);
371 m_aliasDefinitions.append({ object, property.propertyName() });
376void QQmlJSImportVisitor::resolveAliases()
378 QQueue<QQmlJSScope::Ptr> objects;
379 objects.enqueue(m_exportedRootScope);
381 qsizetype lastRequeueLength = std::numeric_limits<qsizetype>::max();
382 QQueue<QQmlJSScope::Ptr> requeue;
383 QDuplicateTracker<std::pair<QQmlJSScope::Ptr, QQmlJSMetaProperty>> alreadyResolvedAliases;
385 bool processingRequeue =
false;
387 while (!objects.isEmpty()) {
388 const QQmlJSScope::Ptr object = objects.dequeue();
389 const auto properties = object->ownProperties();
391 bool doRequeue =
false;
392 for (
const auto &property : properties) {
393 if (!property.isAlias() || !property.type().isNull()
394 || alreadyResolvedAliases.contains({ object, property })) {
397 if (resolveAliasProperty(object, property) == NeedsRequeue) {
400 Q_UNUSED(alreadyResolvedAliases.hasSeen({ object, property }));
404 if (!processingRequeue) {
405 const auto childScopes = object->childScopes();
406 for (
const auto &childScope : childScopes)
407 objects.enqueue(childScope);
411 requeue.enqueue(object);
413 if (objects.isEmpty() && requeue.size() < lastRequeueLength) {
414 processingRequeue =
true;
415 lastRequeueLength = requeue.size();
416 objects.swap(requeue);
420 while (!requeue.isEmpty()) {
421 const QQmlJSScope::Ptr object = requeue.dequeue();
422 const auto properties = object->ownProperties();
423 for (
const auto &property : properties) {
424 if (!property.isAlias() || !property.type().isNull()
425 || alreadyResolvedAliases.contains({ object, property })) {
428 m_logger->log(QStringLiteral(
"Alias \"%1\" is part of an alias cycle")
429 .arg(property.propertyName()),
430 qmlAliasCycle, property.sourceLocation());
435void QQmlJSImportVisitor::resolveGroupedProperties()
437 QQueue<QQmlJSScope::Ptr> objects;
438 objects.enqueue(m_exportedRootScope);
440 while (!objects.isEmpty()) {
441 const QQmlJSScope::Ptr object = objects.dequeue();
442 const auto childScopes = object->childScopes();
443 for (
const auto &childScope : childScopes) {
444 if (mayBeUnresolvedGroupedProperty(childScope)) {
445 const QString name = childScope->internalName();
446 if (object->isNameDeferred(name)) {
447 const QQmlJSScope::ConstPtr deferred = m_scopesById.scope(name, childScope);
448 if (!deferred.isNull()) {
449 QQmlJSScope::resolveGroup(childScope, deferred,
450 m_rootScopeImports.contextualTypes(),
453 }
else if (
const QQmlJSScope::ConstPtr propType = object->property(name).type()) {
454 QQmlJSScope::resolveGroup(childScope, propType,
455 m_rootScopeImports.contextualTypes(), usedTypes());
458 objects.enqueue(childScope);
463QString QQmlJSImportVisitor::implicitImportDirectory(
const QString &localFile,
464 const QQmlJSResourceFileMapper *mapper)
467 const auto resource = mapper->entry(
468 QQmlJSResourceFileMapper::localFileFilter(localFile));
469 if (resource.isValid()) {
470 return resource.resourcePath.contains(u'/')
471 ? (u':' + resource.resourcePath.left(
472 resource.resourcePath.lastIndexOf(u'/') + 1))
473 : QStringLiteral(
":/");
477 return QFileInfo(localFile).canonicalPath() + u'/';
480void QQmlJSImportVisitor::processImportWarnings(
481 const QString &what,
const QList<QQmlJS::DiagnosticMessage> &warnings,
482 const QQmlJS::SourceLocation &srcLocation)
484 if (warnings.isEmpty())
487 QList<QQmlJS::DiagnosticMessage> importWarnings = warnings;
490 auto fileSelectorWarningsIt = std::partition(importWarnings.begin(), importWarnings.end(),
491 [](
const QQmlJS::DiagnosticMessage &message) {
492 return message.type != QtMsgType::QtInfoMsg;
494 if (fileSelectorWarningsIt != importWarnings.end()) {
495 m_logger->log(QStringLiteral(
"Warnings occurred while importing %1:").arg(what), qmlImportFileSelector,
497 m_logger->processMessages(QSpan(fileSelectorWarningsIt, importWarnings.end()),
498 qmlImportFileSelector, srcLocation);
501 if (fileSelectorWarningsIt == importWarnings.begin())
504 m_logger->log(QStringLiteral(
"Warnings occurred while importing %1:").arg(what), qmlImport,
506 m_logger->processMessages(QSpan(importWarnings.begin(), fileSelectorWarningsIt), qmlImport,
510void QQmlJSImportVisitor::importBaseModules()
512 Q_ASSERT(m_rootScopeImports.isEmpty());
513 m_rootScopeImports = m_importer->importHardCodedBuiltins();
515
516
517
518
519
520 m_rootScopeImports.setCurrentFileSelector(
521 QQmlJSUtils::fileSelectorFor(m_exportedRootScope));
523 const QQmlJS::SourceLocation invalidLoc;
524 const auto types = m_rootScopeImports.types();
525 for (
auto it = types.keyBegin(), end = types.keyEnd(); it != end; it++)
526 addImportWithLocation(*it, invalidLoc,
false);
528 if (!m_qmldirFiles.isEmpty())
529 m_rootScopeImports.addWarnings(m_importer->importQmldirs(m_qmldirFiles));
533 if (!m_logger->filePath().endsWith(u".qmltypes"_s)) {
534 auto precedence = quint8(QQmlJS::PrecedenceValues::ImplicitImport);
535 auto implicitImport = m_importer->importDirectory(m_implicitImportDirectory, precedence);
536 m_importer->registerVersionedImports(implicitImport);
537 m_rootScopeImports.add(std::move(implicitImport));
542 if (
const QQmlJSResourceFileMapper *mapper = m_importer->resourceFileMapper()) {
543 const QStringList resourcePaths = mapper->resourcePaths(QQmlJSResourceFileMapper::Filter {
544 m_logger->filePath(), QStringList(), QQmlJSResourceFileMapper::Resource });
545 for (
const QString &path : resourcePaths) {
546 const qsizetype lastSlash = path.lastIndexOf(QLatin1Char(
'/'));
549 auto precedence = quint8(QQmlJS::PrecedenceValues::ImplicitImport);
550 auto resourceImport =
551 m_importer->importDirectory(path.first(lastSlash), precedence);
552 m_importer->registerVersionedImports(resourceImport);
553 m_rootScopeImports.add(std::move(resourceImport));
558 processImportWarnings(QStringLiteral(
"base modules"), m_rootScopeImports.warnings());
561bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiProgram *)
565 if (
auto elementName = QFileInfo(m_logger->filePath()).baseName();
566 !elementName.isEmpty() && elementName[0].isUpper()) {
567 auto precedence = quint8(QQmlJS::PrecedenceValues::ImplicitImport);
568 m_rootScopeImports.setType(elementName,
569 { m_exportedRootScope, QTypeRevision{ }, precedence });
575void QQmlJSImportVisitor::endVisit(UiProgram *)
577 for (
const auto &scope : std::as_const(m_objectBindingScopes)) {
578 breakInheritanceCycles(scope);
579 checkDeprecation(scope);
580 checkForComponentTypeWithProperties(scope);
583 for (
const auto &scope : std::as_const(m_objectDefinitionScopes)) {
584 if (m_pendingDefaultProperties.contains(scope))
586 breakInheritanceCycles(scope);
587 checkDeprecation(scope);
588 checkForComponentTypeWithProperties(scope);
591 const auto &keys = m_pendingDefaultProperties.keys();
592 for (
const auto &scope : keys) {
593 breakInheritanceCycles(scope);
594 checkDeprecation(scope);
595 checkForComponentTypeWithProperties(scope);
599 resolveGroupedProperties();
601 checkGroupedAndAttachedScopes();
604 processDefaultProperties();
605 processPropertyTypes();
606 processMethodTypes();
607 processPropertyBindings();
608 processPropertyBindingObjects();
609 checkRequiredProperties();
611 populateRuntimeFunctionIndicesForDocument();
616 ExpressionStatement *expr = cast<ExpressionStatement *>(statement);
618 if (!statement || !expr->expression)
621 switch (expr->expression->kind) {
622 case Node::Kind_StringLiteral:
623 return cast<StringLiteral *>(expr->expression)->value.toString();
624 case Node::Kind_NumericLiteral:
625 return cast<NumericLiteral *>(expr->expression)->value;
631QList<QQmlJSAnnotation> QQmlJSImportVisitor::parseAnnotations(QQmlJS::AST::UiAnnotationList *list)
634 QList<QQmlJSAnnotation> annotationList;
636 for (UiAnnotationList *item = list; item !=
nullptr; item = item->next) {
637 UiAnnotation *annotation = item->annotation;
639 QQmlJSAnnotation qqmljsAnnotation;
640 qqmljsAnnotation.name = buildName(annotation->qualifiedTypeNameId);
642 for (UiObjectMemberList *memberItem = annotation->initializer->members; memberItem !=
nullptr; memberItem = memberItem->next) {
643 switch (memberItem->member->kind) {
644 case Node::Kind_UiScriptBinding: {
645 auto *scriptBinding = QQmlJS::AST::cast<UiScriptBinding*>(memberItem->member);
646 qqmljsAnnotation.bindings[buildName(scriptBinding->qualifiedId)]
647 = bindingToVariant(scriptBinding->statement);
656 annotationList.append(qqmljsAnnotation);
659 return annotationList;
662void QQmlJSImportVisitor::setAllBindings()
664 using Key = std::pair<QQmlJSScope::ConstPtr, QString>;
665 QHash<Key, QQmlJS::SourceLocation> foundBindings;
667 for (
auto it = m_bindings.cbegin(); it != m_bindings.cend(); ++it) {
669 const QQmlJSScope::Ptr type = it->owner;
670 if (!checkTypeResolved(type))
679 if (!type->isFullyResolved())
681 auto binding = it->create();
682 if (!binding.isValid())
684 type->addOwnPropertyBinding(binding, it->specifier);
687 if (binding.hasInterceptor() || binding.hasValueSource())
689 const QString propertyName = binding.propertyName();
690 QQmlJSMetaProperty property = type->property(propertyName);
693
694
695
696
697
698 if (!property.isValid())
702 if (property.isList())
705 const Key key = std::make_pair(type, propertyName);
706 auto sourceLocationIt = foundBindings.constFind(key);
707 if (sourceLocationIt == foundBindings.constEnd()) {
708 foundBindings.insert(key, binding.sourceLocation());
712 const QQmlJS::SourceLocation location = binding.sourceLocation();
713 m_logger->log(
"Duplicate binding on property '%1'"_L1.arg(propertyName),
714 qmlDuplicatePropertyBinding, location);
715 m_logger->log(
"Note: previous binding on '%1' here"_L1.arg(propertyName),
716 qmlDuplicatePropertyBinding, *sourceLocationIt,
true,
true, {},
721void QQmlJSImportVisitor::processDefaultProperties()
723 for (
auto it = m_pendingDefaultProperties.constBegin();
724 it != m_pendingDefaultProperties.constEnd(); ++it) {
725 QQmlJSScope::ConstPtr parentScope = it.key();
728 if (checkCustomParser(parentScope))
731 if (!checkTypeResolved(parentScope))
735
736
737
738
739
740
741
742
743
745 parentScope = parentScope->baseType();
747 const QString defaultPropertyName =
748 parentScope ? parentScope->defaultPropertyName() : QString();
750 if (defaultPropertyName.isEmpty()) {
753 bool isComponent =
false;
754 for (QQmlJSScope::ConstPtr s = parentScope; s; s = s->baseType()) {
755 if (s->internalName() == QStringLiteral(
"QQmlComponent")) {
761 if (!isComponent && checkTypeResolved(parentScope)) {
762 m_logger->log(QStringLiteral(
"Cannot assign to non-existent default property"),
763 qmlMissingProperty, it.value().constFirst()->sourceLocation());
769 const QQmlJSMetaProperty defaultProp = parentScope->property(defaultPropertyName);
770 auto propType = defaultProp.type();
771 const auto handleUnresolvedDefaultProperty = [&](
const QQmlJSScope::ConstPtr &) {
773 m_logger->log(QStringLiteral(
"Property \"%1\" has incomplete type \"%2\". You may be "
774 "missing an import.")
775 .arg(defaultPropertyName)
776 .arg(defaultProp.typeName()),
777 qmlUnresolvedType, it.value().constFirst()->sourceLocation());
780 const auto assignToUnknownProperty = [&]() {
783 for (
const QQmlJSScope::Ptr &scope : std::as_const(*it))
784 scope->setAssignedToUnknownProperty(
true);
787 if (propType.isNull()) {
788 if (checkTypeResolved(parentScope)
789 && QQmlJSScope::ownerOfProperty(parentScope, defaultPropertyName).scope->filePath()
790 != m_exportedRootScope->filePath()) {
791 handleUnresolvedDefaultProperty(propType);
793 assignToUnknownProperty();
797 if (it.value().size() > 1
798 && !defaultProp.isList()
799 && !propType->isListProperty()) {
801 QStringLiteral(
"Cannot assign multiple objects to a default non-list property"),
802 qmlNonListProperty, it.value().constFirst()->sourceLocation());
805 if (!checkTypeResolved(propType, handleUnresolvedDefaultProperty)) {
806 assignToUnknownProperty();
810 for (
const QQmlJSScope::Ptr &scope : std::as_const(*it)) {
811 if (!checkTypeResolved(scope))
816 if (propType->canAssign(scope)) {
817 scope->setIsWrappedInImplicitComponent(
818 causesImplicitComponentWrapping(defaultProp, scope));
822 m_logger->log(QStringLiteral(
"Cannot assign to default property of incompatible type"),
823 qmlIncompatibleType, scope->sourceLocation());
828void QQmlJSImportVisitor::processPropertyTypes()
830 for (
const PendingPropertyType &type : std::as_const(m_pendingPropertyTypes)) {
831 Q_ASSERT(type.scope->hasOwnProperty(type.name));
833 auto property = type.scope->ownProperty(type.name);
835 if (
const auto propertyType = QQmlJSScope::findType(
836 property.typeName(), m_rootScopeImports.contextualTypes()).scope) {
837 property.setType(property.isList() ? propertyType->listType() : propertyType);
838 type.scope->addOwnProperty(property);
840 QString msg = property.typeName() +
' '_L1 + wasNotFound;
841 if (property.typeName() ==
"list"_L1)
842 msg +=
" list is not a type. It requires an element type argument (eg. list<int>)"_L1;
843 m_logger->log(msg, qmlImport, type.location);
848void QQmlJSImportVisitor::processMethodTypes()
850 const auto isEnumUsedAsType = [&](QStringView typeName,
const QQmlJS::SourceLocation &loc) {
851 if (typeName ==
"enum"_L1) {
855 const auto split = typeName.tokenize(u'.').toContainer<QVarLengthArray<QStringView, 4>>();
856 if (split.size() != 2)
859 const QStringView scopeName = split[0];
860 const QStringView enumName = split[1];
862 if (
auto scope = QQmlJSScope::findType(scopeName.toString(),
863 m_rootScopeImports.contextualTypes()).scope) {
864 if (scope->enumeration(enumName.toString()).isValid()) {
866 "QML enumerations are not types. Use int, or use double if the enum's underlying type does not fit into int."_L1,
867 qmlEnumsAreNotTypes, loc);
874 for (
const auto &method : std::as_const(m_pendingMethodTypeAnnotations)) {
875 for (
auto [it, end] = method.scope->mutableOwnMethodsRange(method.methodName); it != end; ++it) {
876 const auto [parameterBegin, parameterEnd] = it->mutableParametersRange();
877 for (
auto parameter = parameterBegin; parameter != parameterEnd; ++parameter) {
878 const int parameterIndex = parameter - parameterBegin;
879 if (isEnumUsedAsType(parameter->typeName(), method.locations[parameterIndex]))
881 if (
const auto parameterType = QQmlJSScope::findType(
882 parameter->typeName(), m_rootScopeImports.contextualTypes()).scope) {
883 parameter->setType({ parameterType });
886 u"\"%1\" was not found for the type of parameter \"%2\" in method \"%3\"."_s
887 .arg(parameter->typeName(), parameter->name(), it->methodName()),
888 qmlUnresolvedType, method.locations[parameter - parameterBegin]);
892 if (isEnumUsedAsType(it->returnTypeName(), method.locations.last()))
894 if (
const auto returnType = QQmlJSScope::findType(
895 it->returnTypeName(), m_rootScopeImports.contextualTypes()).scope) {
896 it->setReturnType({ returnType });
898 m_logger->log(u"\"%1\" was not found for the return type of method \"%2\"."_s.arg(
899 it->returnTypeName(), it->methodName()),
900 qmlUnresolvedType, method.locations.last());
908
909
910
911
912
913
914
918 for (QStringView propertyName: possiblyGroupedProperty.tokenize(u".")) {
919 property = scope->property(propertyName.toString());
920 if (property.isValid())
921 scope = property.type();
928void QQmlJSImportVisitor::processPropertyBindingObjects()
930 QSet<std::pair<QQmlJSScope::Ptr, QString>> foundLiterals;
938 QSet<std::pair<QQmlJSScope::Ptr, QString>> visited;
939 for (
const PendingPropertyObjectBinding &objectBinding :
940 std::as_const(m_pendingPropertyObjectBindings)) {
942 const auto uniqueBindingId = std::make_pair(objectBinding.scope, objectBinding.name);
943 if (visited.contains(uniqueBindingId))
945 visited.insert(uniqueBindingId);
947 auto [existingBindingsBegin, existingBindingsEnd] =
948 uniqueBindingId.first->ownPropertyBindings(uniqueBindingId.second);
949 const bool hasLiteralBindings =
950 std::any_of(existingBindingsBegin, existingBindingsEnd,
951 [](
const QQmlJSMetaPropertyBinding &x) {
return x.hasLiteral(); });
952 if (hasLiteralBindings)
953 foundLiterals.insert(uniqueBindingId);
957 QSet<std::pair<QQmlJSScope::Ptr, QString>> foundObjects;
958 QSet<std::pair<QQmlJSScope::Ptr, QString>> foundInterceptors;
959 QSet<std::pair<QQmlJSScope::Ptr, QString>> foundValueSources;
961 for (
const PendingPropertyObjectBinding &objectBinding :
962 std::as_const(m_pendingPropertyObjectBindings)) {
963 const QString propertyName = objectBinding.name;
964 QQmlJSScope::Ptr childScope = objectBinding.childScope;
966 const auto assignToUnknownProperty = [&]() {
969 childScope->setAssignedToUnknownProperty(
true);
973 if (!checkTypeResolved(objectBinding.scope)) {
974 assignToUnknownProperty();
978 QQmlJSMetaProperty property = resolveProperty(propertyName, objectBinding.scope);
980 if (!property.isValid()) {
981 warnMissingPropertyForBinding(propertyName, objectBinding.location);
984 const auto handleUnresolvedProperty = [&](
const QQmlJSScope::ConstPtr &) {
986 m_logger->log(QStringLiteral(
"Property \"%1\" has incomplete type \"%2\". You may be "
987 "missing an import.")
989 .arg(property.typeName()),
990 qmlUnresolvedType, objectBinding.location);
993 if (property.type().isNull()) {
994 assignToUnknownProperty();
995 if (checkTypeResolved(objectBinding.scope)
996 && QQmlJSScope::ownerOfProperty(objectBinding.scope, propertyName).scope->filePath()
997 != m_exportedRootScope->filePath()) {
1000 handleUnresolvedProperty(property.type());
1006 if (!checkTypeResolved(property.type(), handleUnresolvedProperty)) {
1007 assignToUnknownProperty();
1009 }
else if (!checkTypeResolved(childScope)) {
1013 if (!objectBinding.onToken && !property.type()->canAssign(childScope)) {
1014 m_logger->log(QStringLiteral(
"Cannot assign object of type %1 to %2")
1015 .arg(QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope))
1016 .arg(property.typeName()),
1017 qmlIncompatibleType, childScope->sourceLocation());
1021 childScope->setIsWrappedInImplicitComponent(
1022 causesImplicitComponentWrapping(property, childScope));
1025 const auto uniqueBindingId = std::make_pair(objectBinding.scope, objectBinding.name);
1026 const QString typeName = QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope);
1028 auto isConditionalBinding = [&]() ->
bool {
1030
1031
1032
1033
1034 return childScope->hasOwnPropertyBindings(u"enabled"_s)
1035 || childScope->hasOwnPropertyBindings(u"when"_s)
1036 || childScope->hasOwnPropertyBindings(u"running"_s);
1039 if (objectBinding.onToken) {
1040 if (childScope->hasInterface(QStringLiteral(
"QQmlPropertyValueInterceptor"))) {
1041 if (foundInterceptors.contains(uniqueBindingId)) {
1042 if (!isConditionalBinding()) {
1043 m_logger->log(QStringLiteral(
"Duplicate interceptor on property \"%1\"")
1045 qmlDuplicatePropertyBinding, objectBinding.location);
1048 foundInterceptors.insert(uniqueBindingId);
1050 }
else if (childScope->hasInterface(QStringLiteral(
"QQmlPropertyValueSource"))) {
1051 if (foundValueSources.contains(uniqueBindingId)) {
1052 if (!isConditionalBinding()) {
1053 m_logger->log(QStringLiteral(
"Duplicate value source on property \"%1\"")
1055 qmlDuplicatePropertyBinding, objectBinding.location);
1057 }
else if (foundObjects.contains(uniqueBindingId)
1058 || foundLiterals.contains(uniqueBindingId)) {
1059 if (!isConditionalBinding()) {
1060 m_logger->log(QStringLiteral(
"Cannot combine value source and binding on "
1063 qmlDuplicatePropertyBinding, objectBinding.location);
1066 foundValueSources.insert(uniqueBindingId);
1069 m_logger->log(QStringLiteral(
"On-binding for property \"%1\" has wrong type \"%2\"")
1072 qmlIncompatibleType, objectBinding.location);
1075 if (foundValueSources.contains(uniqueBindingId)) {
1076 if (!isConditionalBinding()) {
1078 QStringLiteral(
"Cannot combine value source and binding on property \"%1\"")
1080 qmlDuplicatePropertyBinding, objectBinding.location);
1083 foundObjects.insert(uniqueBindingId);
1091 QList<QQmlJSScope::ConstPtr> descendants;
1092 std::vector<QQmlJSScope::ConstPtr> toVisit;
1094 toVisit.push_back(scope);
1095 while (!toVisit.empty()) {
1096 const QQmlJSScope::ConstPtr s = toVisit.back();
1102 toVisit.insert(toVisit.end(), s->childScopesBegin(), s->childScopesEnd());
1109void QQmlJSImportVisitor::populatePropertyAliases()
1111 for (
const auto &alias : std::as_const(m_aliasDefinitions)) {
1112 const auto &[aliasScope, aliasName] = alias;
1113 if (aliasScope.isNull())
1116 auto property = aliasScope->ownProperty(aliasName);
1117 if (!property.isValid() || !property.aliasTargetScope())
1120 Property target(property.aliasTargetScope(), property.aliasTargetName());
1123 m_propertyAliases[target].append(alias);
1124 property = target.scope->property(target.name);
1125 target = Property(property.aliasTargetScope(), property.aliasTargetName());
1126 }
while (property.isAlias() && target.scope);
1130void QQmlJSImportVisitor::checkRequiredProperties()
1132 for (
const auto &required : std::as_const(m_requiredProperties)) {
1133 if (!required.scope->hasProperty(required.name)) {
1135 QStringLiteral(
"Property \"%1\" was marked as required but does not exist.")
1136 .arg(required.name),
1137 qmlRequired, required.location);
1141 const auto compType = m_rootScopeImports.type(u"Component"_s).scope;
1142 const auto isComponentRoot = [&](
const QQmlJSScope::ConstPtr &requiredScope) {
1143 if (requiredScope->isWrappedInImplicitComponent())
1145 if (
const auto s = requiredScope->parentScope(); s && s->baseType() == compType)
1150 const auto scopeRequiresProperty = [&](
const QQmlJSScope::ConstPtr &requiredScope,
1151 const QString &propName,
1152 const QQmlJSScope::ConstPtr &descendant) {
1153 if (!requiredScope->isPropertyLocallyRequired(propName))
1157 return QQmlJSScope::ownerOfProperty(requiredScope, propName).scope
1158 == QQmlJSScope::ownerOfProperty(descendant, propName).scope;
1161 const auto requiredHasBinding = [](
const QList<QQmlJSScope::ConstPtr> &scopesToSearch,
1162 const QQmlJSScope::ConstPtr &owner,
1163 const QString &propName) {
1164 for (
const auto &scope : scopesToSearch) {
1165 if (scope->property(propName).isAlias())
1167 const auto &[begin, end] = scope->ownPropertyBindings(propName);
1168 for (
auto it = begin; it != end; ++it) {
1170 const bool isRelevantBinding = QQmlSA::isRegularBindingType(it->bindingType())
1171 || it->bindingType() == QQmlSA::BindingType::Interceptor
1172 || it->bindingType() == QQmlSA::BindingType::ValueSource;
1173 if (!isRelevantBinding)
1175 if (QQmlJSScope::ownerOfProperty(scope, propName).scope == owner)
1183 const auto requiredUsedInRootAlias = [&](
const QQmlJSScope::ConstPtr &requiredScope,
1184 const QString &propName) {
1185 const Property target(requiredScope, propName);
1188 const auto allAliasesToTargetIt = m_propertyAliases.constFind(target);
1189 if (allAliasesToTargetIt == m_propertyAliases.constEnd())
1196 allAliasesToTargetIt->constBegin(), allAliasesToTargetIt->constEnd(),
1197 [](
const Property &property) {
return property.scope->isFileRootComponent(); });
1200 const auto requiredSetThroughAlias = [&](
const QList<QQmlJSScope::ConstPtr> &scopesToSearch,
1201 const QQmlJSScope::ConstPtr &requiredScope,
1202 const QString &propName) {
1203 const auto &propertyDefScope = QQmlJSScope::ownerOfProperty(requiredScope, propName);
1204 const auto &propertyAliases = m_propertyAliases[{ propertyDefScope.scope, propName }];
1205 for (
const auto &alias : propertyAliases) {
1206 for (
const auto &s : scopesToSearch) {
1207 if (s->hasOwnPropertyBindings(alias.name))
1214 const auto warn = [
this](
const QQmlJSScope::ConstPtr &prevRequiredScope,
1215 const QString &propName,
const QQmlJSScope::ConstPtr &defScope,
1216 const QQmlJSScope::ConstPtr &requiredScope,
1217 const QQmlJSScope::ConstPtr &descendant) {
1218 const auto &propertyScope = QQmlJSScope::ownerOfProperty(requiredScope, propName).scope;
1219 const QString propertyScopeName = !propertyScope.isNull()
1220 ? QQmlJSUtils::getScopeName(propertyScope, QQmlSA::ScopeType::QMLScope)
1223 std::optional<QQmlJSFixSuggestion> suggestion;
1225 QString message = QStringLiteral(
"Component is missing required property %1 from %2")
1227 .arg(propertyScopeName);
1228 if (requiredScope != descendant) {
1229 const QString requiredScopeName = prevRequiredScope
1230 ? QQmlJSUtils::getScopeName(prevRequiredScope, QQmlSA::ScopeType::QMLScope)
1233 if (!prevRequiredScope.isNull()) {
1234 if (
auto sourceScope = prevRequiredScope->baseType()) {
1235 suggestion = QQmlJSFixSuggestion{
1236 "%1:%2:%3: Property marked as required in %4."_L1
1237 .arg(sourceScope->filePath())
1238 .arg(sourceScope->sourceLocation().startLine)
1239 .arg(sourceScope->sourceLocation().startColumn)
1240 .arg(requiredScopeName),
1241 sourceScope->sourceLocation()
1245 if (sourceScope->isComposite())
1246 suggestion->setFilename(sourceScope->filePath());
1249 message +=
" (marked as required by %1)"_L1.arg(requiredScopeName);
1253 m_logger->log(message, qmlRequired, defScope->sourceLocation(),
true,
true, suggestion);
1256 populatePropertyAliases();
1258 for (
const auto &[_, defScope] : m_scopesByIrLocation.asKeyValueRange()) {
1259 if (defScope->isFileRootComponent() || defScope->isInlineComponent()
1260 || defScope->componentRootStatus() != QQmlJSScope::IsComponentRoot::No
1261 || defScope->scopeType() != QQmlSA::ScopeType::QMLScope) {
1265 QList<QQmlJSScope::ConstPtr> scopesToSearch;
1266 for (QQmlJSScope::ConstPtr scope = defScope; scope; scope = scope->baseType()) {
1267 const auto descendants = QList<QQmlJSScope::ConstPtr>()
1268 << scope << qmlScopeDescendants(scope);
1269 for (
const QQmlJSScope::ConstPtr &descendant : std::as_const(descendants)) {
1272 if (descendant != scope && descendant->isInlineComponent())
1274 scopesToSearch << descendant;
1275 const auto ownProperties = descendant->ownProperties();
1276 for (
auto propertyIt = ownProperties.constBegin();
1277 propertyIt != ownProperties.constEnd(); ++propertyIt) {
1278 const QString propName = propertyIt.key();
1279 if (descendant->hasOwnPropertyBindings(propName))
1282 QQmlJSScope::ConstPtr prevRequiredScope;
1283 for (
const QQmlJSScope::ConstPtr &requiredScope : std::as_const(scopesToSearch)) {
1286 if (isComponentRoot(requiredScope))
1289 if (!scopeRequiresProperty(requiredScope, propName, descendant)) {
1290 prevRequiredScope = requiredScope;
1294 if (requiredHasBinding(scopesToSearch, descendant, propName))
1297 if (requiredUsedInRootAlias(requiredScope, propName))
1300 if (requiredSetThroughAlias(scopesToSearch, requiredScope, propName))
1303 warn(prevRequiredScope, propName, defScope, requiredScope, descendant);
1304 prevRequiredScope = requiredScope;
1312void QQmlJSImportVisitor::processPropertyBindings()
1314 for (
auto it = m_propertyBindings.constBegin(); it != m_propertyBindings.constEnd(); ++it) {
1315 QQmlJSScope::Ptr scope = it.key();
1316 for (
auto &[visibilityScope, location, name] : it.value()) {
1317 if (!scope->hasProperty(name) && !m_logger->isDisabled()) {
1321 if (checkCustomParser(scope))
1325 std::optional<QQmlJSFixSuggestion> fixSuggestion;
1327 for (QQmlJSScope::ConstPtr baseScope = scope; !baseScope.isNull();
1328 baseScope = baseScope->baseType()) {
1329 if (
auto suggestion = QQmlJSUtils::didYouMean(
1330 name, baseScope->ownProperties().keys(), m_logger->filePath(), location);
1331 suggestion.has_value()) {
1332 fixSuggestion = suggestion;
1337 if (checkTypeResolved(scope))
1338 warnMissingPropertyForBinding(name, location, fixSuggestion);
1342 const auto property = scope->property(name);
1343 if (!property.type()) {
1344 m_logger->log(QStringLiteral(
"No type found for property \"%1\". This may be due "
1345 "to a missing import statement or incomplete "
1348 qmlMissingType, location);
1351 const auto &annotations = property.annotations();
1353 const auto deprecationAnn =
1354 std::find_if(annotations.cbegin(), annotations.cend(),
1355 [](
const QQmlJSAnnotation &ann) {
return ann.isDeprecation(); });
1357 if (deprecationAnn != annotations.cend()) {
1358 const auto deprecation = deprecationAnn->deprecation();
1360 QString message = QStringLiteral(
"Binding on deprecated property \"%1\"")
1361 .arg(property.propertyName());
1363 if (!deprecation.reason.isEmpty())
1364 message.append(QStringLiteral(
" (Reason: %1)").arg(deprecation.reason));
1366 m_logger->log(message, qmlDeprecated, location);
1372void QQmlJSImportVisitor::checkSignal(
1373 const QQmlJSScope::ConstPtr &signalScope,
const QQmlJS::SourceLocation &location,
1374 const QString &handlerName,
const QStringList &handlerParameters)
1376 const auto signal = QQmlSignalNames::handlerNameToSignalName(handlerName);
1378 std::optional<QQmlJSMetaMethod> signalMethod;
1379 const auto setSignalMethod = [&](
const QQmlJSScope::ConstPtr &scope,
const QString &name) {
1380 const auto methods = scope->methods(name, QQmlJSMetaMethodType::Signal);
1381 if (!methods.isEmpty())
1382 signalMethod = methods[0];
1385 if (signal.has_value()) {
1386 if (signalScope->hasMethod(*signal)) {
1387 setSignalMethod(signalScope, *signal);
1388 }
else if (
auto p = QQmlJSUtils::propertyFromChangedHandler(signalScope, handlerName)) {
1393 if (
auto notify = p->notify(); !notify.isEmpty()) {
1394 setSignalMethod(signalScope, notify);
1396 Q_ASSERT(!p->bindable().isEmpty());
1397 signalMethod = QQmlJSMetaMethod {};
1402 if (!signalMethod.has_value()) {
1407 if (signalScope->baseTypeName() == QStringLiteral(
"Connections")) {
1409 u"Implicitly defining \"%1\" as signal handler in Connections is deprecated. "
1410 u"Create a function instead: \"function %2(%3) { ... }\"."_s.arg(
1411 handlerName, handlerName, handlerParameters.join(u", ")),
1412 qmlUnqualified, location,
true,
true);
1416 auto baseType = QQmlJSScope::nonCompositeBaseType(signalScope);
1417 if (baseType && baseType->hasCustomParser())
1421 QStringLiteral(
"no matching signal found for handler \"%1\"").arg(handlerName),
1422 qmlUnqualified, location,
true,
true);
1426 const auto signalParameters = signalMethod->parameters();
1427 QHash<QString, qsizetype> parameterNameIndexes;
1429 for (
int i = 0, end = signalParameters.size(); i < end; i++) {
1430 auto &p = signalParameters[i];
1431 parameterNameIndexes[p.name()] = i;
1433 auto signalName = [&]() {
1435 return u" called %1"_s.arg(*signal);
1438 auto type = p.type();
1441 "Type %1 of parameter %2 in signal%3 was not found, but is required to compile "
1442 "%4."_L1.arg(p.typeName(), p.name(), signalName(), handlerName),
1443 qmlSignalParameters, location);
1447 if (type->isComposite())
1455 auto parameterName = [&]() {
1456 if (p.name().isEmpty())
1458 return u" called %1"_s.arg(p.name());
1460 switch (type->accessSemantics()) {
1461 case QQmlJSScope::AccessSemantics::Reference:
1463 m_logger->log(QStringLiteral(
"Type %1 of parameter%2 in signal%3 should be "
1464 "passed by pointer to be able to compile %4. ")
1465 .arg(p.typeName(), parameterName(), signalName(),
1467 qmlSignalParameters, location);
1469 case QQmlJSScope::AccessSemantics::Value:
1470 case QQmlJSScope::AccessSemantics::Sequence:
1474 "Type %1 of parameter%2 in signal%3 should be passed by "
1475 "value or const reference to be able to compile %4. ")
1476 .arg(p.typeName(), parameterName(), signalName(),
1478 qmlSignalParameters, location);
1480 case QQmlJSScope::AccessSemantics::None:
1482 QStringLiteral(
"Type %1 of parameter%2 in signal%3 required by the "
1483 "compilation of %4 cannot be used. ")
1484 .arg(p.typeName(), parameterName(), signalName(), handlerName),
1485 qmlSignalParameters, location);
1490 if (handlerParameters.size() > signalParameters.size()) {
1491 m_logger->log(QStringLiteral(
"Signal handler for \"%2\" has more formal"
1492 " parameters than the signal it handles.")
1494 qmlSignalParameters, location);
1498 for (qsizetype i = 0, end = handlerParameters.size(); i < end; i++) {
1499 const QStringView handlerParameter = handlerParameters.at(i);
1500 auto it = parameterNameIndexes.constFind(handlerParameter.toString());
1501 if (it == parameterNameIndexes.constEnd())
1503 const qsizetype j = *it;
1508 m_logger->log(QStringLiteral(
"Parameter %1 to signal handler for \"%2\""
1509 " is called \"%3\". The signal has a parameter"
1510 " of the same name in position %4.")
1512 .arg(handlerName, handlerParameter)
1514 qmlSignalParameters, location);
1518void QQmlJSImportVisitor::addDefaultProperties()
1520 QQmlJSScope::ConstPtr parentScope = m_currentScope->parentScope();
1521 if (m_currentScope == m_exportedRootScope || parentScope->isArrayScope()
1522 || m_currentScope->isInlineComponent())
1525 m_pendingDefaultProperties[m_currentScope->parentScope()] << m_currentScope;
1527 if (checkCustomParser(parentScope))
1531
1532
1533
1534
1535
1536
1537
1538
1539
1541 parentScope = parentScope->baseType();
1543 const QString defaultPropertyName =
1544 parentScope ? parentScope->defaultPropertyName() : QString();
1546 if (defaultPropertyName.isEmpty())
1551 QQmlJSMetaPropertyBinding binding(m_currentScope->sourceLocation(), defaultPropertyName);
1552 binding.setObject(QQmlJSUtils::getScopeName(m_currentScope, QQmlSA::ScopeType::QMLScope),
1553 QQmlJSScope::ConstPtr(m_currentScope));
1554 m_bindings.append(UnfinishedBinding { m_currentScope->parentScope(), [=]() {
return binding; },
1555 QQmlJSScope::UnnamedPropertyTarget });
1558void QQmlJSImportVisitor::breakInheritanceCycles(
const QQmlJSScope::Ptr &originalScope)
1560 QList<QQmlJSScope::ConstPtr> scopes;
1561 for (QQmlJSScope::ConstPtr scope = originalScope; scope;) {
1562 if (scopes.contains(scope)) {
1563 QString inheritenceCycle;
1564 for (
const auto &seen : std::as_const(scopes)) {
1565 inheritenceCycle.append(seen->baseTypeName());
1566 inheritenceCycle.append(QLatin1String(
" -> "));
1568 inheritenceCycle.append(scopes.first()->baseTypeName());
1570 const QString message = QStringLiteral(
"%1 is part of an inheritance cycle: %2")
1571 .arg(originalScope->baseTypeName(), inheritenceCycle);
1572 m_logger->log(message, qmlInheritanceCycle, scope->sourceLocation());
1573 originalScope->clearBaseType();
1574 originalScope->setBaseTypeError(message);
1578 scopes.append(scope);
1580 const auto newScope = scope->baseType();
1581 if (newScope.isNull()) {
1582 const QString error = scope->baseTypeError();
1583 const QString name = scope->baseTypeName();
1584 if (!error.isEmpty()) {
1585 m_logger->log(error, qmlImport, scope->sourceLocation(),
true,
true);
1586 }
else if (!name.isEmpty() && !m_unresolvedTypes.hasSeen(scope)
1587 && !m_logger->isDisabled()) {
1588 m_logger->log(name +
' '_L1 + wasNotFound +
' '_L1, qmlImport,
1589 scope->sourceLocation(),
true,
true,
1590 QQmlJSUtils::didYouMean(
1591 scope->baseTypeName(), m_rootScopeImports.types().keys(),
1592 m_logger->filePath(), scope->sourceLocation()));
1600void QQmlJSImportVisitor::checkDeprecation(
const QQmlJSScope::ConstPtr &originalScope)
1602 for (QQmlJSScope::ConstPtr scope = originalScope; scope; scope = scope->baseType()) {
1603 for (
const QQmlJSAnnotation &annotation : scope->annotations()) {
1604 if (annotation.isDeprecation()) {
1605 QQQmlJSDeprecation deprecation = annotation.deprecation();
1608 QStringLiteral(
"Type \"%1\" is deprecated").arg(scope->internalName());
1610 if (!deprecation.reason.isEmpty())
1611 message.append(QStringLiteral(
" (Reason: %1)").arg(deprecation.reason));
1613 m_logger->log(message, qmlDeprecated, originalScope->sourceLocation());
1619void QQmlJSImportVisitor::checkForComponentTypeWithProperties(
const QQmlJSScope::ConstPtr &scope)
1621 const QQmlJSScope::ConstPtr base = scope->baseType();
1628 if (base->isComposite())
1631 if (base->internalName() !=
"QQmlComponent"_L1)
1634 const auto ownProperties = scope->ownProperties();
1635 for (
const auto &property : ownProperties) {
1636 m_logger->log(
"Component objects cannot declare new properties."_L1,
1637 qmlSyntax, property.sourceLocation());
1641bool QQmlJSImportVisitor::checkCustomParser(
const QQmlJSScope::ConstPtr &scope)
1643 return scope->isInCustomParserParent();
1646void QQmlJSImportVisitor::flushPendingSignalParameters()
1648 const QQmlJSMetaSignalHandler handler = m_signalHandlers[m_pendingSignalHandler];
1649 for (
const QString ¶meter : handler.signalParameters) {
1650 safeInsertJSIdentifier(m_currentScope, parameter,
1651 { QQmlJSScope::JavaScriptIdentifier::Injected,
1652 m_pendingSignalHandler, std::nullopt,
false });
1654 m_pendingSignalHandler = QQmlJS::SourceLocation();
1658
1659
1660
1661
1662
1663
1664QQmlJSMetaMethod::RelativeFunctionIndex
1665QQmlJSImportVisitor::addFunctionOrExpression(
const QQmlJSScope::ConstPtr &scope,
1666 const QString &name)
1668 auto &array = m_functionsAndExpressions[scope];
1669 array.emplaceBack(name);
1676 for (
const auto &function : std::as_const(m_functionStack))
1677 m_innerFunctions[function]++;
1678 m_functionStack.push({ scope, name });
1680 return QQmlJSMetaMethod::RelativeFunctionIndex {
int(array.size() - 1) };
1684
1685
1686
1687
1688
1689
1690
1691
1692void QQmlJSImportVisitor::forgetFunctionExpression(
const QString &name)
1694 auto nameToVerify = name.isEmpty() ? u"<anon>"_s : name;
1695 Q_UNUSED(nameToVerify);
1696 Q_ASSERT(!m_functionStack.isEmpty());
1697 Q_ASSERT(m_functionStack.top().name == nameToVerify);
1698 m_functionStack.pop();
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713int QQmlJSImportVisitor::synthesizeCompilationUnitRuntimeFunctionIndices(
1714 const QQmlJSScope::Ptr &scope,
int count)
const
1716 const auto suitableScope = [](
const QQmlJSScope::Ptr &scope) {
1717 const auto type = scope->scopeType();
1718 return type == QQmlSA::ScopeType::QMLScope
1719 || type == QQmlSA::ScopeType::GroupedPropertyScope
1720 || type == QQmlSA::ScopeType::AttachedPropertyScope;
1723 if (!suitableScope(scope))
1726 auto it = m_functionsAndExpressions.constFind(scope);
1727 if (it == m_functionsAndExpressions.cend())
1730 const auto &functionsAndExpressions = *it;
1731 for (
const QString &functionOrExpression : functionsAndExpressions) {
1732 scope->addOwnRuntimeFunctionIndex(
1733 static_cast<QQmlJSMetaMethod::AbsoluteFunctionIndex>(count));
1750 count += m_innerFunctions.value({ scope, functionOrExpression }, 0);
1756void QQmlJSImportVisitor::populateRuntimeFunctionIndicesForDocument()
const
1759 const auto synthesize = [&](
const QQmlJSScope::Ptr ¤t) {
1760 count = synthesizeCompilationUnitRuntimeFunctionIndices(current, count);
1762 QQmlJSUtils::traverseFollowingQmlIrObjectStructure(m_exportedRootScope, synthesize);
1765bool QQmlJSImportVisitor::visit(QQmlJS::AST::ExpressionStatement *ast)
1767 if (m_pendingSignalHandler.isValid()) {
1768 enterEnvironment(QQmlSA::ScopeType::SignalHandlerFunctionScope, u"signalhandler"_s,
1769 ast->firstSourceLocation());
1770 flushPendingSignalParameters();
1775void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ExpressionStatement *)
1777 if (m_currentScope->scopeType() == QQmlSA::ScopeType::SignalHandlerFunctionScope) {
1784 const QQmlJS::SourceLocation &srcLocation);
1787 QQmlJSLogger *logger)
1789 QStringView namespaceName{ superType };
1790 namespaceName = namespaceName.first(namespaceName.indexOf(u'.'));
1791 logger->log(u"Namespace '%1' of '%2' must start with an upper case letter."_s.arg(namespaceName)
1793 qmlUncreatableType, location,
true,
true);
1796bool QQmlJSImportVisitor::visit(UiObjectDefinition *definition)
1798 const QString superType = buildName(definition->qualifiedTypeNameId);
1800 const bool isRoot = !rootScopeIsValid();
1801 Q_ASSERT(!superType.isEmpty());
1808 const qsizetype indexOfTypeName = superType.lastIndexOf(u'.');
1809 const bool looksLikeGroupedProperty = !superType.front().isUpper();
1811 if (indexOfTypeName != -1 && looksLikeGroupedProperty) {
1812 logLowerCaseImport(superType, definition->qualifiedTypeNameId->identifierToken,
1816 if (!looksLikeGroupedProperty) {
1818 enterEnvironment(QQmlSA::ScopeType::QMLScope, superType,
1819 definition->firstSourceLocation());
1821 enterRootScope(QQmlSA::ScopeType::QMLScope, superType,
1822 definition->firstSourceLocation());
1823 m_currentScope->setIsRootFileComponentFlag(
true);
1826 const QTypeRevision revision = m_currentScope->baseTypeRevision();
1827 if (
auto base = m_currentScope->baseType(); base) {
1828 if (isRoot && base->internalName() == u"QQmlComponent") {
1829 m_logger->log(u"Qml top level type cannot be 'Component'."_s, qmlTopLevelComponent,
1830 definition->qualifiedTypeNameId->identifierToken,
true,
true);
1832 if (base->isSingleton() && m_currentScope->isComposite()) {
1833 m_logger->log(u"Singleton Type %1 is not creatable."_s.arg(
1834 m_currentScope->baseTypeName()),
1835 qmlUncreatableType, definition->qualifiedTypeNameId->identifierToken,
1838 }
else if (!base->isCreatable()) {
1840 m_logger->log(u"Type %1 is not creatable."_s.arg(m_currentScope->baseTypeName()),
1841 qmlUncreatableType, definition->qualifiedTypeNameId->identifierToken,
1845 if (m_nextIsInlineComponent) {
1846 Q_ASSERT(std::holds_alternative<InlineComponentNameType>(m_currentRootName));
1847 const QString &name = std::get<InlineComponentNameType>(m_currentRootName);
1848 m_currentScope->setIsInlineComponent(
true);
1849 m_currentScope->setInlineComponentName(name);
1850 m_currentScope->setOwnModuleName(m_exportedRootScope->moduleName());
1851 auto precedence = quint8(QQmlJS::PrecedenceValues::InlineComponent);
1852 m_rootScopeImports.setType(name, { m_currentScope, revision, precedence });
1853 m_nextIsInlineComponent =
false;
1856 addDefaultProperties();
1857 Q_ASSERT(m_currentScope->scopeType() == QQmlSA::ScopeType::QMLScope);
1858 m_qmlTypes.append(m_currentScope);
1860 m_objectDefinitionScopes << m_currentScope;
1862 enterEnvironmentNonUnique(QQmlSA::ScopeType::GroupedPropertyScope, superType,
1863 definition->firstSourceLocation());
1864 m_bindings.append(createNonUniqueScopeBinding(m_currentScope, superType,
1865 definition->firstSourceLocation()));
1866 QQmlJSScope::resolveTypes(m_currentScope, m_rootScopeImports.contextualTypes(),
1870 m_currentScope->setAnnotations(parseAnnotations(definition->annotations));
1875void QQmlJSImportVisitor::endVisit(UiObjectDefinition *)
1877 QQmlJSScope::resolveTypes(m_currentScope, m_rootScopeImports.contextualTypes(), usedTypes());
1881bool QQmlJSImportVisitor::visit(UiInlineComponent *component)
1883 if (!std::holds_alternative<RootDocumentNameType>(m_currentRootName)) {
1884 m_logger->log(u"Nested inline components are not supported"_s, qmlSyntax,
1885 component->firstSourceLocation());
1889 const auto it = m_seenInlineComponents.constFind(component->name);
1890 if (it != m_seenInlineComponents.cend()) {
1891 m_logger->log(
"Duplicate inline component '%1'"_L1.arg(it.key()),
1892 qmlDuplicateInlineComponent, component->firstSourceLocation());
1893 m_logger->log(
"Note: previous component named '%1' here"_L1.arg(it.key()),
1894 qmlDuplicateInlineComponent, it.value(),
true,
true, {},
1895 component->firstSourceLocation().startLine);
1897 m_seenInlineComponents[component->name] = component->firstSourceLocation();
1900 m_nextIsInlineComponent =
true;
1901 m_currentRootName = component->name.toString();
1905void QQmlJSImportVisitor::endVisit(UiInlineComponent *component)
1907 m_currentRootName = RootDocumentNameType();
1908 if (m_nextIsInlineComponent) {
1909 m_logger->log(u"Inline component declaration must be followed by a typename"_s,
1910 qmlSyntax, component->firstSourceLocation());
1912 m_nextIsInlineComponent =
false;
1915bool QQmlJSImportVisitor::visit(UiPublicMember *publicMember)
1917 switch (publicMember->type) {
1918 case UiPublicMember::Signal: {
1919 const QString signalName = publicMember->name.toString();
1920 UiParameterList *param = publicMember->parameters;
1921 QQmlJSMetaMethod method;
1922 method.setMethodType(QQmlJSMetaMethodType::Signal);
1923 method.setReturnTypeName(QStringLiteral(
"void"));
1924 method.setMethodName(signalName);
1925 method.setSourceLocation(combine(publicMember->firstSourceLocation(),
1926 publicMember->lastSourceLocation()));
1927 method.setMethodIndex(
1928 QQmlJSMetaMethod::RelativeFunctionIndex(m_currentScope->ownMethods().size()));
1930 method.addParameter(
1931 QQmlJSMetaParameter(
1932 param->name.toString(),
1933 param->type ? param->type->toString() : QString()
1935 param = param->next;
1937 m_currentScope->addOwnMethod(method);
1940 case UiPublicMember::Property: {
1941 const QString propertyName = publicMember->name.toString();
1942 QString typeName = buildName(publicMember->memberType);
1943 if (typeName.contains(u'.') && typeName.front().isLower()) {
1944 logLowerCaseImport(typeName, publicMember->typeToken, m_logger);
1948 const bool isAlias = (typeName == u"alias"_s);
1950 auto tryParseAlias = [&]() {
1952 if (!publicMember->statement) {
1953 m_logger->log(QStringLiteral(
"Invalid alias expression - an initializer is needed."),
1954 qmlSyntax, publicMember->memberType->firstSourceLocation());
1957 const auto expression = cast<ExpressionStatement *>(publicMember->statement);
1958 auto node = expression ? expression->expression :
nullptr;
1959 auto fex = cast<FieldMemberExpression *>(node);
1962 aliasExpr.prepend(u'.' + fex->name.toString());
1963 fex = cast<FieldMemberExpression *>(node);
1966 if (
const auto idExpression = cast<IdentifierExpression *>(node)) {
1967 aliasExpr.prepend(idExpression->name.toString());
1971 m_logger->log(QStringLiteral(
"Invalid alias expression. Only IDs and field "
1972 "member expressions can be aliased."),
1973 qmlSyntax, publicMember->statement->firstSourceLocation());
1978 QQmlJSMetaProperty prop;
1979 prop.setPropertyName(propertyName);
1980 prop.setIsList(publicMember->typeModifier == QLatin1String(
"list"));
1981 prop.setIsWritable(!publicMember->isReadonly());
1982 prop.setIsFinal(publicMember->isFinal());
1983 prop.setIsVirtual(publicMember->isVirtual());
1984 prop.setIsOverride(publicMember->isOverride());
1985 prop.setAliasExpression(aliasExpr);
1986 prop.setSourceLocation(
1987 combine(publicMember->firstSourceLocation(), publicMember->colonToken));
1989 isAlias ? QQmlJSScope::ConstPtr() : m_rootScopeImports.type(typeName).scope;
1991 const auto factory = type.factory();
1993 prop.setType(prop.isList() ? (factory ? QQmlJSScope::Ptr{ } : type->listType()) : type);
1994 const QString internalName = factory ? factory->internalName() : type->internalName();
1995 prop.setTypeName(internalName.isEmpty() ? typeName : internalName);
2001 Q_ASSERT(type.factory() == factory);
2002 }
else if (!isAlias) {
2003 m_pendingPropertyTypes << PendingPropertyType { m_currentScope, prop.propertyName(),
2004 publicMember->firstSourceLocation() };
2005 prop.setTypeName(typeName);
2007 prop.setAnnotations(parseAnnotations(publicMember->annotations));
2008 if (publicMember->isDefaultMember())
2009 m_currentScope->setOwnDefaultPropertyName(propertyName);
2010 prop.setIndex(m_currentScope->ownProperties().size());
2011 m_currentScope->addOwnProperty(prop);
2013 QQmlJSMetaMethod method(
2014 QQmlSignalNames::propertyNameToChangedSignalName(propertyName), u"void"_s);
2015 method.setMethodType(QQmlJSMetaMethodType::Signal);
2016 method.setIsImplicitQmlPropertyChangeSignal(
true);
2017 method.setMethodIndex(
2018 QQmlJSMetaMethod::RelativeFunctionIndex(m_currentScope->ownMethods().size()));
2019 m_currentScope->addOwnMethod(method);
2021 if (publicMember->isRequired())
2022 m_currentScope->setPropertyLocallyRequired(prop.propertyName(),
true);
2024 BindingExpressionParseResult parseResult = BindingExpressionParseResult::Invalid;
2028 parseBindingExpression(publicMember->name.toString(), publicMember->statement,
2034 if (parseResult == BindingExpressionParseResult::Script) {
2035 Q_ASSERT(!m_savedBindingOuterScope);
2036 m_savedBindingOuterScope = m_currentScope;
2037 enterEnvironment(QQmlSA::ScopeType::BindingFunctionScope, QStringLiteral(
"binding"),
2038 publicMember->statement->firstSourceLocation());
2048void QQmlJSImportVisitor::endVisit(UiPublicMember *publicMember)
2050 if (m_savedBindingOuterScope) {
2051 m_currentScope = m_savedBindingOuterScope;
2052 m_savedBindingOuterScope = {};
2054 forgetFunctionExpression(publicMember->name.toString());
2058bool QQmlJSImportVisitor::visit(UiRequired *required)
2060 const QString name = required->name.toString();
2062 m_requiredProperties << RequiredProperty { m_currentScope, name,
2063 required->firstSourceLocation() };
2065 m_currentScope->setPropertyLocallyRequired(name,
true);
2069void QQmlJSImportVisitor::visitFunctionExpressionHelper(QQmlJS::AST::FunctionExpression *fexpr)
2071 using namespace QQmlJS::AST;
2072 auto name = fexpr->name.toString();
2073 if (!name.isEmpty()) {
2074 QQmlJSMetaMethod method(name);
2075 method.setMethodType(QQmlJSMetaMethodType::Method);
2076 method.setSourceLocation(combine(fexpr->firstSourceLocation(), fexpr->lastSourceLocation()));
2078 if (!m_pendingMethodAnnotations.isEmpty()) {
2079 method.setAnnotations(m_pendingMethodAnnotations);
2080 m_pendingMethodAnnotations.clear();
2084 const bool parseTypes = m_scopesById.signaturesAreEnforced();
2086 bool formalsFullyTyped = parseTypes;
2087 bool anyFormalTyped =
false;
2088 PendingMethodTypeAnnotations pending{ m_currentScope, name, {} };
2091 for (
auto formals = fexpr->formals; formals; formals = formals->next) {
2092 PatternElement *e = formals->element;
2095 if (e->typeAnnotation && (e->bindingTarget || e->initializer))
2096 m_logger->log(
"Type annotations on default parameters are not supported"_L1,
2098 combine(e->firstSourceLocation(), e->lastSourceLocation()));
2101 if (
const auto *formals = parseTypes ? fexpr->formals :
nullptr) {
2102 const auto parameters = formals->formals();
2103 for (
const auto ¶meter : parameters) {
2104 const QString type = parameter.typeAnnotation
2105 ? parameter.typeAnnotation->type->toString()
2107 if (type.isEmpty()) {
2108 formalsFullyTyped =
false;
2109 method.addParameter(QQmlJSMetaParameter(parameter.id, QStringLiteral(
"var")));
2110 pending.locations.emplace_back();
2112 anyFormalTyped =
true;
2113 method.addParameter(QQmlJSMetaParameter(parameter.id, type));
2114 pending.locations.append(
2115 combine(parameter.typeAnnotation->firstSourceLocation(),
2116 parameter.typeAnnotation->lastSourceLocation()));
2122 method.setIsJavaScriptFunction(!formalsFullyTyped);
2128 if (parseTypes && fexpr->typeAnnotation) {
2129 method.setReturnTypeName(fexpr->typeAnnotation->type->toString());
2130 pending.locations.append(combine(fexpr->typeAnnotation->firstSourceLocation(),
2131 fexpr->typeAnnotation->lastSourceLocation()));
2132 }
else if (anyFormalTyped) {
2133 method.setReturnTypeName(QStringLiteral(
"void"));
2135 method.setReturnTypeName(QStringLiteral(
"var"));
2138 const auto &locs = pending.locations;
2139 if (std::any_of(locs.cbegin(), locs.cend(), [](
const auto &loc) {
return loc.isValid(); }))
2140 m_pendingMethodTypeAnnotations << pending;
2142 method.setCompiledFunctionIndex(addFunctionOrExpression(m_currentScope, method.methodName()));
2143 method.setMethodIndex(
2144 QQmlJSMetaMethod::RelativeFunctionIndex(m_currentScope->ownMethods().size()));
2146 if (m_currentScope->scopeType() != QQmlSA::ScopeType::QMLScope) {
2148 const QQmlJS::SourceLocation functionLocation = fexpr->identifierToken.isValid()
2149 ? fexpr->identifierToken
2150 : fexpr->functionToken;
2151 safeInsertJSIdentifier(m_currentScope, name,
2152 { QQmlJSScope::JavaScriptIdentifier::LexicalScoped,
2153 functionLocation, method.returnTypeName(),
2156 m_currentScope->addOwnMethod(method);
2158 enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, name, fexpr->firstSourceLocation());
2160 addFunctionOrExpression(m_currentScope, QStringLiteral(
"<anon>"));
2161 enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, QStringLiteral(
"<anon>"),
2162 fexpr->firstSourceLocation());
2166bool QQmlJSImportVisitor::visit(QQmlJS::AST::FunctionExpression *fexpr)
2168 visitFunctionExpressionHelper(fexpr);
2172void QQmlJSImportVisitor::endVisit(QQmlJS::AST::FunctionExpression *fexpr)
2174 forgetFunctionExpression(fexpr->name.toString());
2178bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiSourceElement *srcElement)
2180 m_pendingMethodAnnotations = parseAnnotations(srcElement->annotations);
2184bool QQmlJSImportVisitor::visit(QQmlJS::AST::FunctionDeclaration *fdecl)
2186 if (!fdecl->name.isEmpty()) {
2187 const QString name = fdecl->name.toString();
2188 if (
auto previousDeclaration = m_currentScope->ownJSIdentifier(name)) {
2189 m_logger->log(
"Identifier '%1' has already been declared"_L1.arg(name), qmlSyntax,
2190 fdecl->identifierToken);
2191 m_logger->log(
"Note: previous declaration of '%1' here"_L1.arg(name), qmlSyntax,
2192 previousDeclaration->location);
2195 visitFunctionExpressionHelper(fdecl);
2199void QQmlJSImportVisitor::endVisit(QQmlJS::AST::FunctionDeclaration *fdecl)
2201 forgetFunctionExpression(fdecl->name.toString());
2205bool QQmlJSImportVisitor::visit(QQmlJS::AST::ClassExpression *ast)
2207 QQmlJSMetaProperty prop;
2208 prop.setPropertyName(ast->name.toString());
2209 m_currentScope->addOwnProperty(prop);
2210 enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, ast->name.toString(),
2211 ast->firstSourceLocation());
2215void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ClassExpression *)
2221 QQmlJS::AST::ArgumentList *args)
2223 QStringView contextString;
2224 QStringView mainString;
2225 QStringView commentString;
2226 auto registerContextString = [&](QStringView string) {
2227 contextString = string;
2230 auto registerMainString = [&](QStringView string) {
2231 mainString = string;
2234 auto registerCommentString = [&](QStringView string) {
2235 commentString = string;
2238 auto finalizeBinding = [&](QV4::CompiledData::Binding::Type type,
2239 QV4::CompiledData::TranslationData data) {
2240 if (type == QV4::CompiledData::Binding::Type_Translation) {
2241 binding.setTranslation(mainString, commentString, contextString, data.number);
2242 }
else if (type == QV4::CompiledData::Binding::Type_TranslationById) {
2243 binding.setTranslationId(mainString, data.number);
2245 binding.setStringLiteral(mainString);
2248 QmlIR::tryGeneratingTranslationBindingBase(
2250 registerMainString, registerCommentString, registerContextString, finalizeBinding);
2253QQmlJSImportVisitor::BindingExpressionParseResult
2254QQmlJSImportVisitor::parseBindingExpression(
2255 const QString &name,
const QQmlJS::AST::Statement *statement,
2256 const UiPublicMember *associatedPropertyDefinition)
2258 if (statement ==
nullptr)
2259 return BindingExpressionParseResult::Invalid;
2261 const auto *exprStatement = cast<
const ExpressionStatement *>(statement);
2263 if (exprStatement ==
nullptr) {
2264 QQmlJS::SourceLocation location = statement->firstSourceLocation();
2266 if (
const auto *block = cast<
const Block *>(statement); block && block->statements) {
2267 location = block->statements->firstSourceLocation();
2270 QQmlJSMetaPropertyBinding binding(location, name);
2271 binding.setScriptBinding(addFunctionOrExpression(m_currentScope, name),
2272 QQmlSA::ScriptBindingKind::PropertyBinding, ScriptValue_Function);
2273 m_bindings.append(UnfinishedBinding {
2275 [binding = std::move(binding)]() {
return binding; }
2277 return BindingExpressionParseResult::Script;
2280 auto expr = exprStatement->expression;
2281 QQmlJSMetaPropertyBinding binding(
2282 combine(expr->firstSourceLocation(), expr->lastSourceLocation()),
2285 ScriptBindingValueType scriptBindingValuetype = ScriptValue_Unknown;
2287 switch (expr->kind) {
2288 case Node::Kind_TrueLiteral:
2289 binding.setBoolLiteral(
true);
2291 case Node::Kind_FalseLiteral:
2292 binding.setBoolLiteral(
false);
2294 case Node::Kind_NullExpression:
2295 binding.setNullLiteral();
2297 case Node::Kind_IdentifierExpression: {
2298 auto idExpr = QQmlJS::AST::cast<QQmlJS::AST::IdentifierExpression *>(expr);
2300 if (idExpr->name == u"undefined")
2301 scriptBindingValuetype = ScriptValue_Undefined;
2304 case Node::Kind_FunctionDeclaration:
2305 case Node::Kind_FunctionExpression:
2306 case Node::Kind_Block: {
2307 scriptBindingValuetype = ScriptValue_Function;
2310 case Node::Kind_NumericLiteral:
2311 binding.setNumberLiteral(cast<NumericLiteral *>(expr)->value);
2313 case Node::Kind_StringLiteral:
2314 binding.setStringLiteral(cast<StringLiteral *>(expr)->value);
2316 case Node::Kind_RegExpLiteral:
2317 binding.setRegexpLiteral(cast<RegExpLiteral *>(expr)->pattern);
2319 case Node::Kind_TemplateLiteral: {
2320 auto templateLit = QQmlJS::AST::cast<QQmlJS::AST::TemplateLiteral *>(expr);
2321 Q_ASSERT(templateLit);
2322 if (templateLit->hasNoSubstitution) {
2323 binding.setStringLiteral(templateLit->value);
2325 binding.setScriptBinding(addFunctionOrExpression(m_currentScope, name),
2326 QQmlSA::ScriptBindingKind::PropertyBinding);
2327 for (QQmlJS::AST::TemplateLiteral *l = templateLit; l; l = l->next) {
2328 if (QQmlJS::AST::ExpressionNode *expression = l->expression)
2329 expression->accept(
this);
2335 if (QQmlJS::AST::UnaryMinusExpression *unaryMinus = QQmlJS::AST::cast<QQmlJS::AST::UnaryMinusExpression *>(expr)) {
2336 if (QQmlJS::AST::NumericLiteral *lit = QQmlJS::AST::cast<QQmlJS::AST::NumericLiteral *>(unaryMinus->expression))
2337 binding.setNumberLiteral(-lit->value);
2338 }
else if (QQmlJS::AST::CallExpression *call = QQmlJS::AST::cast<QQmlJS::AST::CallExpression *>(expr)) {
2339 if (QQmlJS::AST::IdentifierExpression *base = QQmlJS::AST::cast<QQmlJS::AST::IdentifierExpression *>(call->base))
2340 handleTranslationBinding(binding, base->name, call->arguments);
2345 if (!binding.isValid()) {
2347 binding.setScriptBinding(addFunctionOrExpression(m_currentScope, name),
2348 QQmlSA::ScriptBindingKind::PropertyBinding,
2349 scriptBindingValuetype);
2351 m_bindings.append(UnfinishedBinding { m_currentScope, [=]() {
return binding; } });
2354 if (binding.bindingType() == QQmlSA::BindingType::Translation
2355 || binding.bindingType() == QQmlSA::BindingType::TranslationById) {
2356 return BindingExpressionParseResult::Translation;
2358 if (!QQmlJSMetaPropertyBinding::isLiteralBinding(binding.bindingType()))
2359 return BindingExpressionParseResult::Script;
2361 if (associatedPropertyDefinition)
2362 handleLiteralBinding(binding, associatedPropertyDefinition);
2364 return BindingExpressionParseResult::Literal;
2367bool QQmlJSImportVisitor::isImportPrefix(QString prefix)
const
2369 if (prefix.isEmpty() || !prefix.front().isUpper())
2372 return m_rootScopeImports.isNullType(prefix);
2375void QQmlJSImportVisitor::handleIdDeclaration(QQmlJS::AST::UiScriptBinding *scriptBinding)
2377 if (m_currentScope->scopeType() != QQmlJSScope::ScopeType::QMLScope) {
2378 m_logger->log(u"id declarations are only allowed in objects"_s, qmlSyntax,
2379 scriptBinding->statement->firstSourceLocation());
2382 const auto *statement = cast<ExpressionStatement *>(scriptBinding->statement);
2384 m_logger->log(u"id must be followed by an identifier"_s, qmlSyntax,
2385 scriptBinding->statement->firstSourceLocation());
2388 const QString name = [&]() {
2389 if (
const auto *idExpression = cast<IdentifierExpression *>(statement->expression))
2390 return idExpression->name.toString();
2391 else if (
const auto *idString = cast<StringLiteral *>(statement->expression)) {
2392 m_logger->log(u"ids do not need quotation marks"_s, qmlSyntaxIdQuotation,
2393 idString->firstSourceLocation());
2394 return idString->value.toString();
2396 m_logger->log(u"Failed to parse id"_s, qmlSyntax,
2397 statement->expression->firstSourceLocation());
2401 if (!name.isEmpty() && !name.front().isLower() && name.front() != u'_') {
2402 m_logger->log(u"Id must start with a lower case letter or an '_'"_s, qmlSyntax,
2403 statement->expression->firstSourceLocation());
2406 m_currentScope->setIdSourceLocation(combine(scriptBinding->statement->firstSourceLocation(),
2407 scriptBinding->statement->lastSourceLocation()));
2408 if (m_scopesById.existsAnywhereInDocument(name)) {
2411 breakInheritanceCycles(m_currentScope);
2412 m_scopesById.possibleScopes(
2413 name, m_currentScope, QQmlJSScopesByIdOption::Default,
2414 [&](
const QQmlJSScope::ConstPtr &otherScopeWithID,
2415 QQmlJSScopesById::Confidence confidence) {
2417 Q_UNUSED(confidence);
2419 auto otherLocation = otherScopeWithID->sourceLocation();
2423 m_logger->log(u"Found a duplicated id. id %1 was first declared at %2:%3"_s.arg(
2424 name, QString::number(otherLocation.startLine),
2425 QString::number(otherLocation.startColumn)),
2426 qmlSyntaxDuplicateIds,
2427 scriptBinding->firstSourceLocation());
2428 return QQmlJSScopesById::CallbackResult::ContinueSearch;
2431 if (!name.isEmpty())
2432 m_scopesById.insert(name, m_currentScope);
2435void QQmlJSImportVisitor::handleLiteralBinding(
const QQmlJSMetaPropertyBinding &binding,
2436 const UiPublicMember *associatedPropertyDefinition)
2440 Q_UNUSED(associatedPropertyDefinition);
2444
2445
2446
2447
2448
2451 const QQmlJS::SourceLocation &srcLocation)
2453 const auto createBinding = [=]() {
2454 const QQmlJSScope::ScopeType type = scope->scopeType();
2461 const auto propertyBindings = scope->parentScope()->ownPropertyBindings(name);
2462 const bool alreadyHasBinding =
std::any_of(propertyBindings.first, propertyBindings.second,
2463 [&](
const QQmlJSMetaPropertyBinding &binding) {
2464 return binding.bindingType() == bindingType;
2466 if (alreadyHasBinding)
2467 return QQmlJSMetaPropertyBinding(QQmlJS::SourceLocation {});
2470 if (type == QQmlSA::ScopeType::GroupedPropertyScope)
2471 binding.setGroupBinding(
static_cast<QSharedPointer<QQmlJSScope>>(scope));
2473 binding.setAttachedBinding(
static_cast<QSharedPointer<QQmlJSScope>>(scope));
2476 return { scope->parentScope(), createBinding };
2479bool QQmlJSImportVisitor::visit(UiScriptBinding *scriptBinding)
2481 Q_ASSERT(!m_savedBindingOuterScope);
2482 Q_ASSERT(!m_thisScriptBindingIsJavaScript);
2483 m_savedBindingOuterScope = m_currentScope;
2484 const auto id = scriptBinding->qualifiedId;
2485 if (!id->next && id->name == QLatin1String(
"id")) {
2486 handleIdDeclaration(scriptBinding);
2493 for (; group->next; group = group->next) {
2494 const QString name = group->name.toString();
2498 if (group == id && isImportPrefix(name)) {
2499 prefix = name + u'.';
2503 const bool isAttachedProperty = name.front().isUpper();
2504 if (isAttachedProperty) {
2506 enterEnvironmentNonUnique(QQmlSA::ScopeType::AttachedPropertyScope, prefix + name,
2507 group->firstSourceLocation());
2510 enterEnvironmentNonUnique(QQmlSA::ScopeType::GroupedPropertyScope, prefix + name,
2511 group->firstSourceLocation());
2513 m_bindings.append(createNonUniqueScopeBinding(m_currentScope, prefix + name,
2514 group->firstSourceLocation()));
2519 const auto name = group->name.toString();
2523 const auto signal = QQmlSignalNames::handlerNameToSignalName(name);
2525 if (!signal.has_value() || m_currentScope->hasProperty(name)) {
2526 m_propertyBindings[m_currentScope].append(
2527 { m_savedBindingOuterScope, group->firstSourceLocation(), name });
2529 auto result = parseBindingExpression(name, scriptBinding->statement);
2530 m_thisScriptBindingIsJavaScript = (result == BindingExpressionParseResult::Script);
2532 const auto statement = scriptBinding->statement;
2533 QStringList signalParameters;
2535 if (ExpressionStatement *expr = cast<ExpressionStatement *>(statement)) {
2536 if (FunctionExpression *func = expr->expression->asFunctionDefinition()) {
2537 for (FormalParameterList *formal = func->formals; formal; formal = formal->next)
2538 signalParameters << formal->element->bindingIdentifier.toString();
2542 QQmlJSMetaMethod scopeSignal;
2543 const auto methods = m_currentScope->methods(*signal, QQmlJSMetaMethodType::Signal);
2544 if (!methods.isEmpty())
2545 scopeSignal = methods[0];
2547 const auto firstSourceLocation = statement->firstSourceLocation();
2548 bool hasMultilineStatementBody =
2549 statement->lastSourceLocation().startLine > firstSourceLocation.startLine;
2550 m_pendingSignalHandler = firstSourceLocation;
2551 m_signalHandlers.insert(firstSourceLocation,
2552 { scopeSignal.parameterNames(), hasMultilineStatementBody });
2556 const auto index = addFunctionOrExpression(m_currentScope, name);
2557 const auto createBinding = [
2559 scope = m_currentScope,
2560 signalName = *signal,
2563 firstSourceLocation,
2564 groupLocation = group->firstSourceLocation(),
2565 signalParameters]() {
2567 Q_ASSERT(scope->isFullyResolved());
2568 QQmlSA::ScriptBindingKind kind = QQmlSA::ScriptBindingKind::Invalid;
2569 const auto methods = scope->methods(signalName, QQmlJSMetaMethodType::Signal);
2570 if (!methods.isEmpty()) {
2571 kind = QQmlSA::ScriptBindingKind::SignalHandler;
2572 checkSignal(scope, groupLocation, name, signalParameters);
2573 }
else if (QQmlJSUtils::propertyFromChangedHandler(scope, name).has_value()) {
2574 kind = QQmlSA::ScriptBindingKind::ChangeHandler;
2575 checkSignal(scope, groupLocation, name, signalParameters);
2576 }
else if (scope->hasProperty(name)) {
2579 kind = QQmlSA::ScriptBindingKind::PropertyBinding;
2580 m_signalHandlers.remove(firstSourceLocation);
2583 checkSignal(scope, groupLocation, name, signalParameters);
2586 QQmlJSMetaPropertyBinding binding(firstSourceLocation, name);
2587 binding.setScriptBinding(index, kind, ScriptValue_Function);
2590 m_bindings.append(UnfinishedBinding { m_currentScope, createBinding });
2591 m_thisScriptBindingIsJavaScript =
true;
2597 while (m_currentScope->scopeType() == QQmlSA::ScopeType::GroupedPropertyScope
2598 || m_currentScope->scopeType() == QQmlSA::ScopeType::AttachedPropertyScope) {
2603 enterEnvironment(QQmlSA::ScopeType::SignalHandlerFunctionScope,
2605 scriptBinding->statement->firstSourceLocation());
2607 enterEnvironment(QQmlSA::ScopeType::BindingFunctionScope,
2609 scriptBinding->statement->firstSourceLocation());
2615void QQmlJSImportVisitor::endVisit(UiScriptBinding *)
2617 if (m_savedBindingOuterScope) {
2618 m_currentScope = m_savedBindingOuterScope;
2619 m_savedBindingOuterScope = {};
2625 if (m_thisScriptBindingIsJavaScript) {
2626 m_thisScriptBindingIsJavaScript =
false;
2627 Q_ASSERT(!m_functionStack.isEmpty());
2628 m_functionStack.pop();
2632bool QQmlJSImportVisitor::visit(UiArrayBinding *arrayBinding)
2634 createAttachedAndGroupedScopes(arrayBinding->qualifiedId);
2635 enterEnvironment(QQmlSA::ScopeType::QMLScope, buildName(arrayBinding->qualifiedId),
2636 arrayBinding->firstSourceLocation());
2637 m_currentScope->setIsArrayScope(
true);
2641void QQmlJSImportVisitor::endVisit(UiArrayBinding *arrayBinding)
2648 const auto children = m_currentScope->childScopes();
2651 const int scopesEnteredCounter = openAttachedAndGroupedScopes(arrayBinding->qualifiedId);
2652 auto guard = qScopeGuard([
this, scopesEnteredCounter]() {
2653 for (
int i = 0; i < scopesEnteredCounter; ++i)
2657 if (checkCustomParser(m_currentScope)) {
2663 auto group = arrayBinding->qualifiedId;
2664 for (; group->next; group = group->next) { }
2665 const QString propertyName = group->name.toString();
2668 for (
auto element = arrayBinding->members; element; element = element->next, ++i) {
2669 const auto &type = children[i];
2670 if ((type->scopeType() != QQmlSA::ScopeType::QMLScope)) {
2671 m_logger->log(u"Declaring an object which is not a Qml object"
2672 " as a list member."_s, qmlSyntax, element->firstSourceLocation());
2675 m_pendingPropertyObjectBindings
2676 << PendingPropertyObjectBinding { m_currentScope, type, propertyName,
2677 element->firstSourceLocation(),
false };
2678 QQmlJSMetaPropertyBinding binding(element->firstSourceLocation(), propertyName);
2679 binding.setObject(QQmlJSUtils::getScopeName(type, QQmlSA::ScopeType::QMLScope),
2680 QQmlJSScope::ConstPtr(type));
2681 m_bindings.append(UnfinishedBinding {
2683 [binding = std::move(binding)]() {
return binding; },
2684 QQmlJSScope::ListPropertyTarget
2689bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiEnumDeclaration *uied)
2691 QQmlJSMetaEnum qmlEnum(uied->name.toString());
2692 qmlEnum.setIsQml(
true);
2693 qmlEnum.setLineNumber(uied->enumToken.startLine);
2694 for (
const auto *member = uied->members; member; member = member->next) {
2695 qmlEnum.addKey(member->member.toString());
2696 qmlEnum.addValue(
int(member->value));
2698 m_currentScope->addOwnEnumeration(qmlEnum);
2702QList<QQmlJS::DiagnosticMessage> QQmlJSImportVisitor::importFromHost(
2703 const QString &path,
const QString &prefix,
const QQmlJS::SourceLocation &location)
2705 QFileInfo fileInfo(path);
2706 if (!fileInfo.exists()) {
2707 m_logger->log(
"File or directory you are trying to import does not exist: %1."_L1.arg(path),
2708 qmlImport, location);
2712 if (fileInfo.isFile()) {
2713 const auto scope = m_importer->importFile(path);
2714 const QString actualPrefix = prefix.isEmpty() ? scope->internalName() : prefix;
2715 auto precedence = quint8(QQmlJS::PrecedenceValues::Default);
2716 m_rootScopeImports.setType(actualPrefix, { scope, QTypeRevision(), precedence });
2717 addImportWithLocation(actualPrefix, location,
false);
2721 if (fileInfo.isDir()) {
2722 auto precedence = quint8(QQmlJS::PrecedenceValues::Default);
2723 auto scopes = m_importer->importDirectory(path, precedence, prefix);
2724 m_importer->registerVersionedImports(scopes);
2725 const auto types = scopes.types();
2726 const auto warnings = scopes.warnings();
2727 m_rootScopeImports.add(std::move(scopes));
2728 for (
auto it = types.keyBegin(), end = types.keyEnd(); it != end; it++)
2729 addImportWithLocation(*it, location, !warnings.isEmpty());
2734 "%1 is neither a file nor a directory. Are sure the import path is correct?"_L1.arg(
2736 qmlImport, location);
2740QList<QQmlJS::DiagnosticMessage> QQmlJSImportVisitor::importFromQrc(
2741 const QString &path,
const QString &prefix,
const QQmlJS::SourceLocation &location)
2743 Q_ASSERT(path.startsWith(u':'));
2744 const QQmlJSResourceFileMapper *mapper = m_importer->resourceFileMapper();
2748 const auto pathNoColon = QStringView(path).mid(1);
2749 if (mapper->isFile(pathNoColon)) {
2750 const auto entry = m_importer->resourceFileMapper()->entry(
2751 QQmlJSResourceFileMapper::resourceFileFilter(pathNoColon.toString()));
2752 const auto scope = m_importer->importFile(entry.filePath);
2753 const QString actualPrefix =
2754 prefix.isEmpty() ? QFileInfo(entry.resourcePath).baseName() : prefix;
2755 auto precedence = quint8(QQmlJS::PrecedenceValues::Default);
2756 m_rootScopeImports.setType(actualPrefix, { scope, QTypeRevision(), precedence });
2757 addImportWithLocation(actualPrefix, location,
false);
2761 auto scopes = m_importer->importDirectory(path, quint8(QQmlJS::PrecedenceValues::Default), prefix);
2762 m_importer->registerVersionedImports(scopes);
2763 const auto types = scopes.types();
2764 const auto warnings = scopes.warnings();
2765 m_rootScopeImports.add(std::move(scopes));
2766 for (
auto it = types.keyBegin(), end = types.keyEnd(); it != end; it++)
2767 addImportWithLocation(*it, location, !warnings.isEmpty());
2771bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiImport *import)
2774 QString prefix = QLatin1String(
"");
2775 if (import->asToken.isValid()) {
2776 prefix += import->importId;
2777 if (!import->importId.isEmpty() && !import->importId.front().isUpper()) {
2778 m_logger->log(u"Import qualifier '%1' must start with a capital letter."_s.arg(
2780 qmlImport, import->importIdToken,
true,
true);
2782 m_seenModuleQualifiers.append(prefix);
2785 const QString filename = import->fileName.toString();
2786 if (!filename.isEmpty()) {
2787 const QUrl url(filename);
2788 const QString scheme = url.scheme();
2789 const QQmlJS::SourceLocation importLocation = import->firstSourceLocation();
2790 if (scheme ==
""_L1) {
2791 QFileInfo fileInfo(url.path());
2792 QString absolute = fileInfo.isRelative()
2793 ? QDir::cleanPath(QDir(m_implicitImportDirectory).filePath(filename))
2795 auto warnings = absolute.startsWith(u':')
2796 ? importFromQrc(absolute, prefix, importLocation)
2797 : importFromHost(absolute, prefix, importLocation);
2798 processImportWarnings(
"path \"%1\""_L1.arg(url.path()), warnings, importLocation);
2800 }
else if (scheme ==
"file"_L1) {
2801 auto warnings = importFromHost(url.path(), prefix, importLocation);
2802 processImportWarnings(
"URL \"%1\""_L1.arg(url.path()), warnings, importLocation);
2804 }
else if (scheme ==
"qrc"_L1) {
2805 auto warnings = importFromQrc(
":"_L1 + url.path(), prefix, importLocation);
2806 processImportWarnings(
"URL \"%1\""_L1.arg(url.path()), warnings, importLocation);
2809 m_logger->log(
"Unknown import syntax. Imports can be paths, qrc urls or file urls"_L1,
2810 qmlImport, import->firstSourceLocation());
2814 const QString path = buildName(import->importUri);
2816 QStringList staticModulesProvided;
2818 auto imported = m_importer->importModule(
2819 path, quint8(QQmlJS::PrecedenceValues::Default), prefix,
2820 import->version ? import->version->version : QTypeRevision(), &staticModulesProvided);
2821 m_importer->registerVersionedImports(imported);
2822 const auto types = imported.types();
2823 const auto warnings = imported.warnings();
2824 m_rootScopeImports.add(std::move(imported));
2825 for (
auto it = types.keyBegin(), end = types.keyEnd(); it != end; it++)
2826 addImportWithLocation(*it, import->firstSourceLocation(), !warnings.isEmpty());
2828 if (prefix.isEmpty()) {
2829 for (
const QString &staticModule : std::as_const(staticModulesProvided))
2830 addStaticImportWithLocation(path, import->firstSourceLocation(), path != staticModule);
2833 processImportWarnings(
2834 QStringLiteral(
"module \"%1\"").arg(path), warnings, import->firstSourceLocation());
2838#if QT_VERSION >= QT_VERSION_CHECK(6
, 6
, 0
)
2840void handlePragmaValues(QQmlJS::AST::UiPragma *pragma, F &&assign)
2842 for (
const QQmlJS::AST::UiPragmaValueList *v = pragma->values; v; v = v->next)
2847void handlePragmaValues(QQmlJS::AST::UiPragma *pragma, F &&assign)
2849 assign(pragma->value);
2853bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiPragma *pragma)
2855 if (pragma->name == u"Strict"_s) {
2860 if (!m_logger->wasCategoryChanged(qmlCompiler))
2861 m_logger->setCategorySeverity(qmlCompiler, QQmlJS::WarningSeverity::Warning);
2862 }
else if (pragma->name == u"ComponentBehavior") {
2863 handlePragmaValues(pragma, [
this, pragma](QStringView value) {
2864 if (value == u"Bound") {
2865 m_scopesById.setComponentsAreBound(
true);
2866 }
else if (value == u"Unbound") {
2867 m_scopesById.setComponentsAreBound(
false);
2869 m_logger->log(u"Unknown argument \"%1\" to pragma ComponentBehavior"_s.arg(value),
2870 qmlSyntax, pragma->firstSourceLocation());
2873 }
else if (pragma->name == u"FunctionSignatureBehavior") {
2874 handlePragmaValues(pragma, [
this, pragma](QStringView value) {
2875 if (value == u"Enforced") {
2876 m_scopesById.setSignaturesAreEnforced(
true);
2877 }
else if (value == u"Ignored") {
2878 m_scopesById.setSignaturesAreEnforced(
false);
2881 u"Unknown argument \"%1\" to pragma FunctionSignatureBehavior"_s.arg(value),
2882 qmlSyntax, pragma->firstSourceLocation());
2885 }
else if (pragma->name == u"ValueTypeBehavior") {
2886 handlePragmaValues(pragma, [
this, pragma](QStringView value) {
2887 if (value == u"Copy") {
2889 }
else if (value == u"Reference") {
2891 }
else if (value == u"Addressable") {
2892 m_scopesById.setValueTypesAreAddressable(
true);
2893 }
else if (value == u"Inaddressable") {
2894 m_scopesById.setValueTypesAreAddressable(
false);
2895 }
else if (value == u"Assertable") {
2896 m_scopesById.setValueTypesAreAssertable(
true);
2897 }
else if (value == u"Inassertable") {
2898 m_scopesById.setValueTypesAreAssertable(
false);
2900 m_logger->log(u"Unknown argument \"%1\" to pragma ValueTypeBehavior"_s.arg(value),
2901 qmlSyntax, pragma->firstSourceLocation());
2909void QQmlJSImportVisitor::throwRecursionDepthError()
2911 m_logger->log(QStringLiteral(
"Maximum statement or expression depth exceeded"),
2912 qmlRecursionDepthErrors, QQmlJS::SourceLocation());
2915bool QQmlJSImportVisitor::visit(QQmlJS::AST::ClassDeclaration *ast)
2917 enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, ast->name.toString(),
2918 ast->firstSourceLocation());
2922void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ClassDeclaration *)
2927bool QQmlJSImportVisitor::visit(QQmlJS::AST::ForStatement *ast)
2929 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"forloop"),
2930 ast->firstSourceLocation());
2934void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ForStatement *)
2939bool QQmlJSImportVisitor::visit(QQmlJS::AST::ForEachStatement *ast)
2941 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"foreachloop"),
2942 ast->firstSourceLocation());
2946void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ForEachStatement *)
2951bool QQmlJSImportVisitor::visit(QQmlJS::AST::Block *ast)
2953 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"block"),
2954 ast->firstSourceLocation());
2956 if (m_pendingSignalHandler.isValid())
2957 flushPendingSignalParameters();
2962void QQmlJSImportVisitor::endVisit(QQmlJS::AST::Block *)
2967bool QQmlJSImportVisitor::visit(QQmlJS::AST::CaseBlock *ast)
2969 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"case"),
2970 ast->firstSourceLocation());
2974void QQmlJSImportVisitor::endVisit(QQmlJS::AST::CaseBlock *)
2979bool QQmlJSImportVisitor::visit(QQmlJS::AST::Catch *catchStatement)
2981 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"catch"),
2982 catchStatement->firstSourceLocation());
2986void QQmlJSImportVisitor::endVisit(QQmlJS::AST::Catch *)
2991bool QQmlJSImportVisitor::visit(QQmlJS::AST::WithStatement *ast)
2993 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"with"),
2994 ast->firstSourceLocation());
2996 m_logger->log(QStringLiteral(
"with statements are strongly discouraged in QML "
2997 "and might cause false positives when analysing unqualified "
2999 qmlWith, ast->firstSourceLocation());
3004void QQmlJSImportVisitor::endVisit(QQmlJS::AST::WithStatement *)
3009bool QQmlJSImportVisitor::visit(QQmlJS::AST::FormalParameterList *fpl)
3011 const auto &boundedNames = fpl->boundNames();
3012 for (
auto const &boundName : boundedNames) {
3014 std::optional<QString> typeName;
3015 if (TypeAnnotation *annotation = boundName.typeAnnotation.data())
3016 if (Type *type = annotation->type)
3017 typeName = type->toString();
3018 safeInsertJSIdentifier(m_currentScope, boundName.id,
3019 { QQmlJSScope::JavaScriptIdentifier::Parameter,
3020 boundName.location, typeName,
false });
3025void QQmlJSImportVisitor::createAttachedAndGroupedScopes(UiQualifiedId *propertyName)
3027 bool needsResolution =
false;
3028 int scopesEnteredCounter = 0;
3030 for (
auto group = propertyName; group->next; group = group->next) {
3031 const QString idName = group->name.toString();
3033 if (idName.isEmpty())
3036 if (group == propertyName && isImportPrefix(idName)) {
3037 prefix = idName + u'.';
3041 const auto scopeKind = idName.front().isUpper() ? QQmlSA::ScopeType::AttachedPropertyScope
3042 : QQmlSA::ScopeType::GroupedPropertyScope;
3045 enterEnvironmentNonUnique(scopeKind, prefix + idName, group->firstSourceLocation());
3047 m_bindings.append(createNonUniqueScopeBinding(m_currentScope, prefix + idName,
3048 group->firstSourceLocation()));
3050 ++scopesEnteredCounter;
3051 needsResolution = needsResolution || !exists;
3056 for (
int i=0; i < scopesEnteredCounter; ++i) {
3061 if (needsResolution) {
3062 QQmlJSScope::resolveTypes(m_currentScope, m_rootScopeImports.contextualTypes(),
3067bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiObjectBinding *uiob)
3071 Q_ASSERT(uiob->qualifiedTypeNameId);
3073 const QString typeName = buildName(uiob->qualifiedTypeNameId);
3074 if (typeName.front().isLower() && typeName.contains(u'.')) {
3075 logLowerCaseImport(typeName, uiob->qualifiedTypeNameId->identifierToken, m_logger);
3078 createAttachedAndGroupedScopes(uiob->qualifiedId);
3080 enterEnvironment(QQmlSA::ScopeType::QMLScope, typeName,
3081 uiob->qualifiedTypeNameId->identifierToken);
3083 m_qmlTypes.append(m_currentScope);
3084 m_objectBindingScopes << m_currentScope;
3088int QQmlJSImportVisitor::openAttachedAndGroupedScopes(UiQualifiedId *propertyName)
3091 int scopesEnteredCounter = 0;
3092 auto group = propertyName;
3093 for (; group->next; group = group->next) {
3094 const QString idName = group->name.toString();
3096 if (idName.isEmpty())
3099 if (group == propertyName && isImportPrefix(idName)) {
3100 prefix = idName + u'.';
3104 const auto scopeKind = idName.front().isUpper() ? QQmlSA::ScopeType::AttachedPropertyScope
3105 : QQmlSA::ScopeType::GroupedPropertyScope;
3107 [[maybe_unused]]
bool exists =
3108 enterEnvironmentNonUnique(scopeKind, prefix + idName, group->firstSourceLocation());
3110 scopesEnteredCounter++;
3114 return scopesEnteredCounter;
3117void QQmlJSImportVisitor::endVisit(QQmlJS::AST::UiObjectBinding *uiob)
3119 QQmlJSScope::resolveTypes(m_currentScope, m_rootScopeImports.contextualTypes(), usedTypes());
3121 const QQmlJSScope::Ptr childScope = m_currentScope;
3124 const int scopesEnteredCounter = openAttachedAndGroupedScopes(uiob->qualifiedId);
3129 auto group = uiob->qualifiedId;
3130 for (; group->next; group = group->next) { }
3131 const QString propertyName = group->name.toString();
3133 if (m_currentScope->isNameDeferred(propertyName)) {
3134 bool foundIds =
false;
3135 QList<QQmlJSScope::ConstPtr> childScopes { childScope };
3137 while (!childScopes.isEmpty()) {
3138 const QQmlJSScope::ConstPtr scope = childScopes.takeFirst();
3139 m_scopesById.possibleIds(
3140 scope, scope, QQmlJSScopesByIdOption::Default,
3141 [&](
const QString &id, QQmlJSScopesById::Confidence confidence) {
3144 Q_UNUSED(confidence);
3146 return QQmlJSScopesById::CallbackResult::StopSearch;
3149 childScopes << scope->childScopes();
3154 u"Cannot defer property assignment to \"%1\". Assigning an id to an object or one of its sub-objects bound to a deferred property will make the assignment immediate."_s
3156 qmlDeferredPropertyId, uiob->firstSourceLocation());
3160 if (checkCustomParser(m_currentScope)) {
3164 m_pendingPropertyObjectBindings
3165 << PendingPropertyObjectBinding { m_currentScope, childScope, propertyName,
3166 uiob->firstSourceLocation(), uiob->hasOnToken };
3168 QQmlJSMetaPropertyBinding binding(uiob->firstSourceLocation(), propertyName);
3169 if (uiob->hasOnToken) {
3170 if (childScope->hasInterface(u"QQmlPropertyValueInterceptor"_s)) {
3171 binding.setInterceptor(QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope),
3172 QQmlJSScope::ConstPtr(childScope));
3174 binding.setValueSource(QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope),
3175 QQmlJSScope::ConstPtr(childScope));
3178 binding.setObject(QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope),
3179 QQmlJSScope::ConstPtr(childScope));
3181 m_bindings.append(UnfinishedBinding { m_currentScope, [=]() {
return binding; } });
3184 for (
int i = 0; i < scopesEnteredCounter; ++i)
3188bool QQmlJSImportVisitor::visit(ExportDeclaration *)
3190 Q_ASSERT(rootScopeIsValid());
3191 Q_ASSERT(m_exportedRootScope != m_globalScope);
3192 Q_ASSERT(m_currentScope == m_globalScope);
3193 m_currentScope = m_exportedRootScope;
3197void QQmlJSImportVisitor::endVisit(ExportDeclaration *)
3199 Q_ASSERT(rootScopeIsValid());
3200 m_currentScope = m_exportedRootScope->parentScope();
3201 Q_ASSERT(m_currentScope == m_globalScope);
3204bool QQmlJSImportVisitor::visit(ESModule *module)
3206 Q_ASSERT(!rootScopeIsValid());
3207 enterRootScope(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"module"),
3208 module->firstSourceLocation());
3209 m_currentScope->setIsScript(
true);
3210 importBaseModules();
3215void QQmlJSImportVisitor::endVisit(ESModule *)
3217 QQmlJSScope::resolveTypes(m_exportedRootScope, m_rootScopeImports.contextualTypes(),
3221bool QQmlJSImportVisitor::visit(Program *program)
3223 Q_ASSERT(m_globalScope == m_currentScope);
3224 Q_ASSERT(!rootScopeIsValid());
3225 enterRootScope(QQmlSA::ScopeType::JSFunctionScope, u"script"_s, program->firstSourceLocation());
3226 m_exportedRootScope->setIsScript(
true);
3227 importBaseModules();
3231void QQmlJSImportVisitor::endVisit(Program *)
3233 QQmlJSScope::resolveTypes(m_exportedRootScope, m_rootScopeImports.contextualTypes(),
3237bool QQmlJSImportVisitor::visit(QQmlJS::AST::PatternElement *element)
3240 if (element->isVariableDeclaration()) {
3241 QQmlJS::AST::BoundNames names;
3242 element->boundNames(&names);
3243 for (
const auto &name : std::as_const(names)) {
3244 std::optional<QString> typeName;
3245 if (TypeAnnotation *annotation = name.typeAnnotation.data())
3246 if (Type *type = annotation->type)
3247 typeName = type->toString();
3248 using Kind = QQmlJSScope::JavaScriptIdentifier::Kind;
3249 const Kind kind = (element->scope == QQmlJS::AST::VariableScope::Var)
3250 ? Kind::FunctionScoped
3251 : Kind::LexicalScoped;
3252 const QString variableName = name.id;
3253 if (kind == Kind::LexicalScoped) {
3254 const QQmlJS::SourceLocation location = element->firstSourceLocation();
3255 if (
auto previousDeclaration = m_currentScope->ownJSIdentifier(variableName)) {
3256 m_logger->log(
"Identifier '%1' has already been declared"_L1.arg(variableName), qmlSyntax,
3258 m_logger->log(
"Note: previous declaration of '%1' here"_L1.arg(variableName), qmlSyntax,
3259 previousDeclaration->location);
3262 const bool isConstVariable = element->scope == QQmlJS::AST::VariableScope::Const;
3263 const bool couldInsert = safeInsertJSIdentifier(m_currentScope,
3265 { (element->scope == QQmlJS::AST::VariableScope::Var)
3266 ? QQmlJSScope::JavaScriptIdentifier::FunctionScoped
3267 : QQmlJSScope::JavaScriptIdentifier::LexicalScoped,
3268 name.location, typeName,