151 const QString &implicitImportDirectory,
152 const QStringList &qmldirFiles)
153 : m_implicitImportDirectory(implicitImportDirectory),
154 m_qmldirFiles(qmldirFiles),
155 m_exportedRootScope(QQmlJSScope::resetForReparse(importer->importFile(logger->filePath()))),
156 m_importer(importer),
158 m_rootScopeImports(QQmlJS::ContextualTypes(
159 QQmlJS::ContextualTypes::QML, { }, { },
160 importer->builtinInternalNames().contextualTypes().arrayType()),
166 m_exportedRootScope->setScopeType(QQmlSA::ScopeType::QMLScope);
167 m_exportedRootScope->setBaseTypeName(QQmlJSImporter::s_inProcessMarker);
168 m_exportedRootScope->setFilePath(m_logger->filePath());
169 m_exportedRootScope->setIsComposite(
true);
172
173
174
175
176
177 auto globalScope = QQmlJSScope::create();
178 globalScope->setInternalName(u"global"_s);
179 globalScope->setScopeType(QQmlSA::ScopeType::JSFunctionScope);
181 QQmlJSScope::JavaScriptIdentifier globalJavaScript = {
182 QQmlJSScope::JavaScriptIdentifier::LexicalScoped, QQmlJS::SourceLocation(), std::nullopt,
186 QV4::Compiler::Codegen::forEachGlobalName([&](QLatin1StringView globalName) {
187 globalScope->insertJSIdentifier(globalName, globalJavaScript);
190 m_globalScope = globalScope;
191 m_currentScope = globalScope;
194QQmlJSImportVisitor::~QQmlJSImportVisitor() =
default;
196void QQmlJSImportVisitor::populateCurrentScope(
197 QQmlJSScope::ScopeType type,
const QString &name,
const QQmlJS::SourceLocation &location)
199 m_currentScope->setScopeType(type);
200 m_currentScope->setIsComposite(
true);
201 m_currentScope->setFilePath(m_logger->filePath());
202 m_currentScope->setSourceLocation(location);
203 setScopeName(m_currentScope, type, name);
204 m_scopesByIrLocation.insert({ location.startLine, location.startColumn }, m_currentScope);
207void QQmlJSImportVisitor::enterRootScope(QQmlJSScope::ScopeType type,
const QString &name,
const QQmlJS::SourceLocation &location)
209 Q_ASSERT(m_currentScope == m_globalScope);
210 QQmlJSScope::reparent(m_currentScope, m_exportedRootScope);
211 m_currentScope = m_exportedRootScope;
212 populateCurrentScope(type, name, location);
215void QQmlJSImportVisitor::enterEnvironment(QQmlJSScope::ScopeType type,
const QString &name,
216 const QQmlJS::SourceLocation &location)
218 QQmlJSScope::Ptr newScope = QQmlJSScope::create();
219 QQmlJSScope::reparent(m_currentScope, newScope);
220 m_currentScope = std::move(newScope);
221 populateCurrentScope(type, name, location);
224bool QQmlJSImportVisitor::enterEnvironmentNonUnique(QQmlJSScope::ScopeType type,
226 const QQmlJS::SourceLocation &location)
228 Q_ASSERT(type == QQmlSA::ScopeType::GroupedPropertyScope
229 || type == QQmlSA::ScopeType::AttachedPropertyScope);
231 const auto pred = [&](
const QQmlJSScope::ConstPtr &s) {
234 return s->internalName() == name;
236 const auto scopes = m_currentScope->childScopes();
239 auto it = std::find_if(scopes.begin(), scopes.end(), pred);
240 if (it == scopes.end()) {
242 enterEnvironment(type, name, location);
246 m_scopesByIrLocation.insert({ location.startLine, location.startColumn }, *it);
247 m_currentScope = *it;
251void QQmlJSImportVisitor::leaveEnvironment()
253 m_currentScope = m_currentScope->parentScope();
256void QQmlJSImportVisitor::warnUnresolvedType(
const QQmlJSScope::ConstPtr &type)
const
258 m_logger->log(QStringLiteral(
"Type %1 is used but it is not resolved")
259 .arg(QQmlJSUtils::getScopeName(type, type->scopeType())),
260 qmlUnresolvedType, type->sourceLocation());
263void QQmlJSImportVisitor::warnMissingPropertyForBinding(
264 const QString &property,
const QQmlJS::SourceLocation &location,
265 const std::optional<QQmlJSFixSuggestion> &fixSuggestion)
267 m_logger->log(QStringLiteral(
"Could not find property \"%1\".").arg(property),
268 qmlMissingProperty, location,
true,
true, fixSuggestion);
276void QQmlJSImportVisitor::resolveAliases()
278 QQueue<QQmlJSScope::Ptr> objects;
279 objects.enqueue(m_exportedRootScope);
281 qsizetype lastRequeueLength = std::numeric_limits<qsizetype>::max();
282 QQueue<QQmlJSScope::Ptr> requeue;
284 while (!objects.isEmpty()) {
285 const QQmlJSScope::Ptr object = objects.dequeue();
286 const auto properties = object->ownProperties();
288 bool doRequeue =
false;
289 for (
const auto &property : properties) {
290 if (!property.isAlias() || !property.type().isNull())
293 QStringList components = property.aliasExpression().split(u'.');
294 QQmlJSMetaProperty targetProperty;
296 bool foundProperty =
false;
299 QQmlJSScope::ConstPtr type = m_scopesById.scope(components.takeFirst(), object);
300 QQmlJSScope::ConstPtr typeScope;
301 if (!type.isNull()) {
302 foundProperty =
true;
309 while (type && !components.isEmpty()) {
310 const QString name = components.takeFirst();
312 if (!type->hasProperty(name)) {
313 foundProperty =
false;
318 const auto target = type->property(name);
319 if (!target.type() && target.isAlias())
322 type = target.type();
323 targetProperty = target;
331 m_logger->log(QStringLiteral(
"Cannot deduce type of alias \"%1\"")
332 .arg(property.propertyName()),
333 qmlMissingType, property.sourceLocation());
335 m_logger->log(QStringLiteral(
"Cannot resolve alias \"%1\"")
336 .arg(property.propertyName()),
337 qmlUnresolvedAlias, property.sourceLocation());
340 Q_ASSERT(property.index() >= 0);
341 object->addOwnProperty(property);
344 QQmlJSMetaProperty newProperty = property;
345 newProperty.setType(type);
347 newProperty.setIsList(targetProperty.isList());
348 newProperty.setIsWritable(targetProperty.isWritable());
349 newProperty.setIsFinal(targetProperty.isFinal());
350 newProperty.setIsPointer(targetProperty.isPointer());
352 const bool onlyId = !property.aliasExpression().contains(u'.');
354 newProperty.setAliasTargetScope(type);
355 newProperty.setAliasTargetName(QStringLiteral(
"id-only-alias"));
357 const auto &ownerScope = QQmlJSScope::ownerOfProperty(
358 typeScope, targetProperty.propertyName()).scope;
359 newProperty.setAliasTargetScope(ownerScope);
360 newProperty.setAliasTargetName(targetProperty.propertyName());
363 if (
const QString internalName = type->internalName(); !internalName.isEmpty())
364 newProperty.setTypeName(internalName);
366 Q_ASSERT(newProperty.index() >= 0);
367 object->addOwnProperty(newProperty);
368 m_aliasDefinitions.append({ object, property.propertyName() });
372 const auto childScopes = object->childScopes();
373 for (
const auto &childScope : childScopes)
374 objects.enqueue(childScope);
377 requeue.enqueue(object);
379 if (objects.isEmpty() && requeue.size() < lastRequeueLength) {
380 lastRequeueLength = requeue.size();
381 objects.swap(requeue);
385 while (!requeue.isEmpty()) {
386 const QQmlJSScope::Ptr object = requeue.dequeue();
387 const auto properties = object->ownProperties();
388 for (
const auto &property : properties) {
389 if (!property.isAlias() || property.type())
391 m_logger->log(QStringLiteral(
"Alias \"%1\" is part of an alias cycle")
392 .arg(property.propertyName()),
393 qmlAliasCycle, property.sourceLocation());
398void QQmlJSImportVisitor::resolveGroupProperties()
400 QQueue<QQmlJSScope::Ptr> objects;
401 objects.enqueue(m_exportedRootScope);
403 while (!objects.isEmpty()) {
404 const QQmlJSScope::Ptr object = objects.dequeue();
405 const auto childScopes = object->childScopes();
406 for (
const auto &childScope : childScopes) {
407 if (mayBeUnresolvedGroupedProperty(childScope)) {
408 const QString name = childScope->internalName();
409 if (object->isNameDeferred(name)) {
410 const QQmlJSScope::ConstPtr deferred = m_scopesById.scope(name, childScope);
411 if (!deferred.isNull()) {
412 QQmlJSScope::resolveGroup(
413 childScope, deferred, m_rootScopeImports.contextualTypes(),
416 }
else if (
const QQmlJSScope::ConstPtr propType = object->property(name).type()) {
417 QQmlJSScope::resolveGroup(
418 childScope, propType, m_rootScopeImports.contextualTypes(),
422 objects.enqueue(childScope);
427QString QQmlJSImportVisitor::implicitImportDirectory(
428 const QString &localFile, QQmlJSResourceFileMapper *mapper)
431 const auto resource = mapper->entry(
432 QQmlJSResourceFileMapper::localFileFilter(localFile));
433 if (resource.isValid()) {
434 return resource.resourcePath.contains(u'/')
435 ? (u':' + resource.resourcePath.left(
436 resource.resourcePath.lastIndexOf(u'/') + 1))
437 : QStringLiteral(
":/");
441 return QFileInfo(localFile).canonicalPath() + u'/';
444void QQmlJSImportVisitor::processImportWarnings(
445 const QString &what,
const QList<QQmlJS::DiagnosticMessage> &warnings,
446 const QQmlJS::SourceLocation &srcLocation)
448 if (warnings.isEmpty())
451 QList<QQmlJS::DiagnosticMessage> importWarnings = warnings;
454 auto fileSelectorWarningsIt = std::partition(importWarnings.begin(), importWarnings.end(),
455 [](
const QQmlJS::DiagnosticMessage &message) {
456 return message.type != QtMsgType::QtInfoMsg;
458 if (fileSelectorWarningsIt != importWarnings.end()) {
459 m_logger->log(QStringLiteral(
"Warnings occurred while importing %1:").arg(what), qmlImportFileSelector,
461 m_logger->processMessages(QSpan(fileSelectorWarningsIt, importWarnings.end()),
462 qmlImportFileSelector, srcLocation);
465 if (fileSelectorWarningsIt == importWarnings.begin())
468 m_logger->log(QStringLiteral(
"Warnings occurred while importing %1:").arg(what), qmlImport,
470 m_logger->processMessages(QSpan(importWarnings.begin(), fileSelectorWarningsIt), qmlImport,
474void QQmlJSImportVisitor::importBaseModules()
476 Q_ASSERT(m_rootScopeImports.isEmpty());
477 m_rootScopeImports = m_importer->importHardCodedBuiltins();
479
480
481
482
483
484 m_rootScopeImports.setCurrentFileSelector(
485 QQmlJSUtils::fileSelectorFor(m_exportedRootScope));
487 const QQmlJS::SourceLocation invalidLoc;
488 const auto types = m_rootScopeImports.types();
489 for (
auto it = types.keyBegin(), end = types.keyEnd(); it != end; it++)
490 addImportWithLocation(*it, invalidLoc,
false);
492 if (!m_qmldirFiles.isEmpty())
493 m_rootScopeImports.addWarnings(m_importer->importQmldirs(m_qmldirFiles));
497 if (!m_logger->filePath().endsWith(u".qmltypes"_s)) {
498 auto precedence = quint8(QQmlJS::PrecedenceValues::ImplicitImport);
499 m_rootScopeImports.add(m_importer->importDirectory(m_implicitImportDirectory, precedence));
504 if (QQmlJSResourceFileMapper *mapper = m_importer->resourceFileMapper()) {
505 const QStringList resourcePaths = mapper->resourcePaths(QQmlJSResourceFileMapper::Filter {
506 m_logger->filePath(), QStringList(), QQmlJSResourceFileMapper::Resource });
507 for (
const QString &path : resourcePaths) {
508 const qsizetype lastSlash = path.lastIndexOf(QLatin1Char(
'/'));
511 auto precedence = quint8(QQmlJS::PrecedenceValues::ImplicitImport);
512 m_rootScopeImports.add(m_importer->importDirectory(path.first(lastSlash),
518 processImportWarnings(QStringLiteral(
"base modules"), m_rootScopeImports.warnings());
521bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiProgram *)
525 if (
auto elementName = QFileInfo(m_logger->filePath()).baseName();
526 !elementName.isEmpty() && elementName[0].isUpper()) {
527 auto precedence = quint8(QQmlJS::PrecedenceValues::ImplicitImport);
528 m_rootScopeImports.setType(elementName,
529 { m_exportedRootScope, QTypeRevision{ }, precedence });
535void QQmlJSImportVisitor::endVisit(UiProgram *)
537 for (
const auto &scope : std::as_const(m_objectBindingScopes)) {
538 breakInheritanceCycles(scope);
539 checkDeprecation(scope);
540 checkForComponentTypeWithProperties(scope);
543 for (
const auto &scope : std::as_const(m_objectDefinitionScopes)) {
544 if (m_pendingDefaultProperties.contains(scope))
546 breakInheritanceCycles(scope);
547 checkDeprecation(scope);
548 checkForComponentTypeWithProperties(scope);
551 const auto &keys = m_pendingDefaultProperties.keys();
552 for (
const auto &scope : keys) {
553 breakInheritanceCycles(scope);
554 checkDeprecation(scope);
555 checkForComponentTypeWithProperties(scope);
559 resolveGroupProperties();
561 for (
const auto &scope : std::as_const(m_objectDefinitionScopes))
562 checkGroupedAndAttachedScopes(scope);
565 processDefaultProperties();
566 processPropertyTypes();
567 processMethodTypes();
568 processPropertyBindings();
569 processPropertyBindingObjects();
570 checkRequiredProperties();
572 auto unusedImports = m_importLocations;
573 for (
const QString &type : std::as_const(m_usedTypes)) {
574 const auto &importLocations = m_importTypeLocationMap.values(type);
575 for (
const auto &importLocation : importLocations)
576 unusedImports.remove(importLocation);
579 if (unusedImports.isEmpty())
583 const auto &imports = m_importStaticModuleLocationMap.values();
584 for (
const QQmlJS::SourceLocation &import : imports)
585 unusedImports.remove(import);
587 for (
const auto &import : unusedImports) {
588 m_logger->log(QString::fromLatin1(
"Unused import"), qmlUnusedImports, import);
591 populateRuntimeFunctionIndicesForDocument();
596 ExpressionStatement *expr = cast<ExpressionStatement *>(statement);
598 if (!statement || !expr->expression)
601 switch (expr->expression->kind) {
602 case Node::Kind_StringLiteral:
603 return cast<StringLiteral *>(expr->expression)->value.toString();
604 case Node::Kind_NumericLiteral:
605 return cast<NumericLiteral *>(expr->expression)->value;
611QList<QQmlJSAnnotation> QQmlJSImportVisitor::parseAnnotations(QQmlJS::AST::UiAnnotationList *list)
614 QList<QQmlJSAnnotation> annotationList;
616 for (UiAnnotationList *item = list; item !=
nullptr; item = item->next) {
617 UiAnnotation *annotation = item->annotation;
619 QQmlJSAnnotation qqmljsAnnotation;
620 qqmljsAnnotation.name = buildName(annotation->qualifiedTypeNameId);
622 for (UiObjectMemberList *memberItem = annotation->initializer->members; memberItem !=
nullptr; memberItem = memberItem->next) {
623 switch (memberItem->member->kind) {
624 case Node::Kind_UiScriptBinding: {
625 auto *scriptBinding = QQmlJS::AST::cast<UiScriptBinding*>(memberItem->member);
626 qqmljsAnnotation.bindings[buildName(scriptBinding->qualifiedId)]
627 = bindingToVariant(scriptBinding->statement);
636 annotationList.append(qqmljsAnnotation);
639 return annotationList;
642void QQmlJSImportVisitor::setAllBindings()
644 using Key = std::pair<QQmlJSScope::ConstPtr, QString>;
645 QHash<Key, QQmlJS::SourceLocation> foundBindings;
647 for (
auto it = m_bindings.cbegin(); it != m_bindings.cend(); ++it) {
649 const QQmlJSScope::Ptr type = it->owner;
650 if (!checkTypeResolved(type))
659 if (!type->isFullyResolved())
661 auto binding = it->create();
662 if (!binding.isValid())
664 type->addOwnPropertyBinding(binding, it->specifier);
667 if (binding.hasInterceptor() || binding.hasValueSource())
669 const QString propertyName = binding.propertyName();
670 QQmlJSMetaProperty property = type->property(propertyName);
673
674
675
676
677
678 if (!property.isValid())
682 if (property.isList())
685 const Key key = std::make_pair(type, propertyName);
686 auto sourceLocationIt = foundBindings.constFind(key);
687 if (sourceLocationIt == foundBindings.constEnd()) {
688 foundBindings.insert(key, binding.sourceLocation());
692 const QQmlJS::SourceLocation location = binding.sourceLocation();
693 m_logger->log(
"Duplicate binding on property '%1'"_L1.arg(propertyName),
694 qmlDuplicatePropertyBinding, location);
695 m_logger->log(
"Note: previous binding on '%1' here"_L1.arg(propertyName),
696 qmlDuplicatePropertyBinding, *sourceLocationIt,
true,
true, {},
701void QQmlJSImportVisitor::processDefaultProperties()
703 for (
auto it = m_pendingDefaultProperties.constBegin();
704 it != m_pendingDefaultProperties.constEnd(); ++it) {
705 QQmlJSScope::ConstPtr parentScope = it.key();
708 if (checkCustomParser(parentScope))
711 if (!checkTypeResolved(parentScope))
715
716
717
718
719
720
721
722
723
725 parentScope = parentScope->baseType();
727 const QString defaultPropertyName =
728 parentScope ? parentScope->defaultPropertyName() : QString();
730 if (defaultPropertyName.isEmpty()) {
733 bool isComponent =
false;
734 for (QQmlJSScope::ConstPtr s = parentScope; s; s = s->baseType()) {
735 if (s->internalName() == QStringLiteral(
"QQmlComponent")) {
741 if (!isComponent && checkTypeResolved(parentScope)) {
742 m_logger->log(QStringLiteral(
"Cannot assign to non-existent default property"),
743 qmlMissingProperty, it.value().constFirst()->sourceLocation());
749 const QQmlJSMetaProperty defaultProp = parentScope->property(defaultPropertyName);
750 auto propType = defaultProp.type();
751 const auto handleUnresolvedDefaultProperty = [&](
const QQmlJSScope::ConstPtr &) {
753 m_logger->log(QStringLiteral(
"Property \"%1\" has incomplete type \"%2\". You may be "
754 "missing an import.")
755 .arg(defaultPropertyName)
756 .arg(defaultProp.typeName()),
757 qmlUnresolvedType, it.value().constFirst()->sourceLocation());
760 const auto assignToUnknownProperty = [&]() {
763 for (
const QQmlJSScope::Ptr &scope : std::as_const(*it))
764 scope->setAssignedToUnknownProperty(
true);
767 if (propType.isNull()) {
768 handleUnresolvedDefaultProperty(propType);
769 assignToUnknownProperty();
773 if (it.value().size() > 1
774 && !defaultProp.isList()
775 && !propType->isListProperty()) {
777 QStringLiteral(
"Cannot assign multiple objects to a default non-list property"),
778 qmlNonListProperty, it.value().constFirst()->sourceLocation());
781 if (!checkTypeResolved(propType, handleUnresolvedDefaultProperty)) {
782 assignToUnknownProperty();
786 for (
const QQmlJSScope::Ptr &scope : std::as_const(*it)) {
787 if (!checkTypeResolved(scope))
792 if (propType->canAssign(scope)) {
793 scope->setIsWrappedInImplicitComponent(
794 causesImplicitComponentWrapping(defaultProp, scope));
798 m_logger->log(QStringLiteral(
"Cannot assign to default property of incompatible type"),
799 qmlIncompatibleType, scope->sourceLocation());
804void QQmlJSImportVisitor::processPropertyTypes()
806 for (
const PendingPropertyType &type : std::as_const(m_pendingPropertyTypes)) {
807 Q_ASSERT(type.scope->hasOwnProperty(type.name));
809 auto property = type.scope->ownProperty(type.name);
811 if (
const auto propertyType = QQmlJSScope::findType(
812 property.typeName(), m_rootScopeImports.contextualTypes()).scope) {
813 property.setType(property.isList() ? propertyType->listType() : propertyType);
814 type.scope->addOwnProperty(property);
816 QString msg = property.typeName() +
' '_L1 + wasNotFound +
' '_L1 + didYouAddAllImports;
817 if (property.typeName() ==
"list"_L1)
818 msg +=
" list is not a type. It requires an element type argument (eg. list<int>)"_L1;
819 m_logger->log(msg, qmlImport, type.location);
824void QQmlJSImportVisitor::processMethodTypes()
826 const auto isEnumUsedAsType = [&](QStringView typeName,
const QQmlJS::SourceLocation &loc) {
827 if (typeName ==
"enum"_L1) {
831 const auto split = typeName.tokenize(u'.').toContainer<QVarLengthArray<QStringView, 4>>();
832 if (split.size() != 2)
835 const QStringView scopeName = split[0];
836 const QStringView enumName = split[1];
838 if (
auto scope = QQmlJSScope::findType(scopeName.toString(),
839 m_rootScopeImports.contextualTypes()).scope) {
840 if (scope->enumeration(enumName.toString()).isValid()) {
842 "QML enumerations are not types. Use int, or use double if the enum's underlying type does not fit into int."_L1,
843 qmlEnumsAreNotTypes, loc);
850 for (
const auto &method : std::as_const(m_pendingMethodTypeAnnotations)) {
851 for (
auto [it, end] = method.scope->mutableOwnMethodsRange(method.methodName); it != end; ++it) {
852 const auto [parameterBegin, parameterEnd] = it->mutableParametersRange();
853 for (
auto parameter = parameterBegin; parameter != parameterEnd; ++parameter) {
854 const int parameterIndex = parameter - parameterBegin;
855 if (isEnumUsedAsType(parameter->typeName(), method.locations[parameterIndex]))
857 if (
const auto parameterType = QQmlJSScope::findType(
858 parameter->typeName(), m_rootScopeImports.contextualTypes()).scope) {
859 parameter->setType({ parameterType });
862 u"\"%1\" was not found for the type of parameter \"%2\" in method \"%3\"."_s
863 .arg(parameter->typeName(), parameter->name(), it->methodName()),
864 qmlUnresolvedType, method.locations[parameter - parameterBegin]);
868 if (isEnumUsedAsType(it->returnTypeName(), method.locations.last()))
870 if (
const auto returnType = QQmlJSScope::findType(
871 it->returnTypeName(), m_rootScopeImports.contextualTypes()).scope) {
872 it->setReturnType({ returnType });
874 m_logger->log(u"\"%1\" was not found for the return type of method \"%2\"."_s.arg(
875 it->returnTypeName(), it->methodName()),
876 qmlUnresolvedType, method.locations.last());
884
885
886
887
888
889
890
894 for (QStringView propertyName: possiblyGroupedProperty.tokenize(u".")) {
895 property = scope->property(propertyName.toString());
896 if (property.isValid())
897 scope = property.type();
904void QQmlJSImportVisitor::processPropertyBindingObjects()
906 QSet<std::pair<QQmlJSScope::Ptr, QString>> foundLiterals;
914 QSet<std::pair<QQmlJSScope::Ptr, QString>> visited;
915 for (
const PendingPropertyObjectBinding &objectBinding :
916 std::as_const(m_pendingPropertyObjectBindings)) {
918 const auto uniqueBindingId = std::make_pair(objectBinding.scope, objectBinding.name);
919 if (visited.contains(uniqueBindingId))
921 visited.insert(uniqueBindingId);
923 auto [existingBindingsBegin, existingBindingsEnd] =
924 uniqueBindingId.first->ownPropertyBindings(uniqueBindingId.second);
925 const bool hasLiteralBindings =
926 std::any_of(existingBindingsBegin, existingBindingsEnd,
927 [](
const QQmlJSMetaPropertyBinding &x) {
return x.hasLiteral(); });
928 if (hasLiteralBindings)
929 foundLiterals.insert(uniqueBindingId);
933 QSet<std::pair<QQmlJSScope::Ptr, QString>> foundObjects;
934 QSet<std::pair<QQmlJSScope::Ptr, QString>> foundInterceptors;
935 QSet<std::pair<QQmlJSScope::Ptr, QString>> foundValueSources;
937 for (
const PendingPropertyObjectBinding &objectBinding :
938 std::as_const(m_pendingPropertyObjectBindings)) {
939 const QString propertyName = objectBinding.name;
940 QQmlJSScope::Ptr childScope = objectBinding.childScope;
942 const auto assignToUnknownProperty = [&]() {
945 childScope->setAssignedToUnknownProperty(
true);
949 if (!checkTypeResolved(objectBinding.scope)) {
950 assignToUnknownProperty();
954 QQmlJSMetaProperty property = resolveProperty(propertyName, objectBinding.scope);
956 if (!property.isValid()) {
957 warnMissingPropertyForBinding(propertyName, objectBinding.location);
960 const auto handleUnresolvedProperty = [&](
const QQmlJSScope::ConstPtr &) {
962 m_logger->log(QStringLiteral(
"Property \"%1\" has incomplete type \"%2\". You may be "
963 "missing an import.")
965 .arg(property.typeName()),
966 qmlUnresolvedType, objectBinding.location);
969 if (property.type().isNull()) {
970 assignToUnknownProperty();
971 handleUnresolvedProperty(property.type());
976 if (!checkTypeResolved(property.type(), handleUnresolvedProperty)) {
977 assignToUnknownProperty();
979 }
else if (!checkTypeResolved(childScope)) {
983 if (!objectBinding.onToken && !property.type()->canAssign(childScope)) {
984 m_logger->log(QStringLiteral(
"Cannot assign object of type %1 to %2")
985 .arg(QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope))
986 .arg(property.typeName()),
987 qmlIncompatibleType, childScope->sourceLocation());
991 childScope->setIsWrappedInImplicitComponent(
992 causesImplicitComponentWrapping(property, childScope));
995 const auto uniqueBindingId = std::make_pair(objectBinding.scope, objectBinding.name);
996 const QString typeName = QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope);
998 auto isConditionalBinding = [&]() ->
bool {
1000
1001
1002
1003
1004 return childScope->hasOwnPropertyBindings(u"enabled"_s)
1005 || childScope->hasOwnPropertyBindings(u"when"_s)
1006 || childScope->hasOwnPropertyBindings(u"running"_s);
1009 if (objectBinding.onToken) {
1010 if (childScope->hasInterface(QStringLiteral(
"QQmlPropertyValueInterceptor"))) {
1011 if (foundInterceptors.contains(uniqueBindingId)) {
1012 if (!isConditionalBinding()) {
1013 m_logger->log(QStringLiteral(
"Duplicate interceptor on property \"%1\"")
1015 qmlDuplicatePropertyBinding, objectBinding.location);
1018 foundInterceptors.insert(uniqueBindingId);
1020 }
else if (childScope->hasInterface(QStringLiteral(
"QQmlPropertyValueSource"))) {
1021 if (foundValueSources.contains(uniqueBindingId)) {
1022 if (!isConditionalBinding()) {
1023 m_logger->log(QStringLiteral(
"Duplicate value source on property \"%1\"")
1025 qmlDuplicatePropertyBinding, objectBinding.location);
1027 }
else if (foundObjects.contains(uniqueBindingId)
1028 || foundLiterals.contains(uniqueBindingId)) {
1029 if (!isConditionalBinding()) {
1030 m_logger->log(QStringLiteral(
"Cannot combine value source and binding on "
1033 qmlDuplicatePropertyBinding, objectBinding.location);
1036 foundValueSources.insert(uniqueBindingId);
1039 m_logger->log(QStringLiteral(
"On-binding for property \"%1\" has wrong type \"%2\"")
1042 qmlIncompatibleType, objectBinding.location);
1045 if (foundValueSources.contains(uniqueBindingId)) {
1046 if (!isConditionalBinding()) {
1048 QStringLiteral(
"Cannot combine value source and binding on property \"%1\"")
1050 qmlDuplicatePropertyBinding, objectBinding.location);
1053 foundObjects.insert(uniqueBindingId);
1061 QList<QQmlJSScope::ConstPtr> descendants;
1062 std::vector<QQmlJSScope::ConstPtr> toVisit;
1064 toVisit.push_back(scope);
1065 while (!toVisit.empty()) {
1066 const QQmlJSScope::ConstPtr s = toVisit.back();
1072 toVisit.insert(toVisit.end(), s->childScopesBegin(), s->childScopesEnd());
1079void QQmlJSImportVisitor::populatePropertyAliases()
1081 for (
const auto &alias : std::as_const(m_aliasDefinitions)) {
1082 const auto &[aliasScope, aliasName] = alias;
1083 if (aliasScope.isNull())
1086 auto property = aliasScope->ownProperty(aliasName);
1087 if (!property.isValid() || !property.aliasTargetScope())
1090 Property target(property.aliasTargetScope(), property.aliasTargetName());
1093 m_propertyAliases[target].append(alias);
1094 property = target.scope->property(target.name);
1095 target = Property(property.aliasTargetScope(), property.aliasTargetName());
1096 }
while (property.isAlias());
1100void QQmlJSImportVisitor::checkRequiredProperties()
1102 for (
const auto &required : std::as_const(m_requiredProperties)) {
1103 if (!required.scope->hasProperty(required.name)) {
1105 QStringLiteral(
"Property \"%1\" was marked as required but does not exist.")
1106 .arg(required.name),
1107 qmlRequired, required.location);
1111 const auto compType = m_rootScopeImports.type(u"Component"_s).scope;
1112 const auto isComponentRoot = [&](
const QQmlJSScope::ConstPtr &requiredScope) {
1113 if (requiredScope->isWrappedInImplicitComponent())
1115 if (
const auto s = requiredScope->parentScope(); s && s->baseType() == compType)
1120 const auto scopeRequiresProperty = [&](
const QQmlJSScope::ConstPtr &requiredScope,
1121 const QString &propName,
1122 const QQmlJSScope::ConstPtr &descendant) {
1123 if (!requiredScope->isPropertyLocallyRequired(propName))
1127 return QQmlJSScope::ownerOfProperty(requiredScope, propName).scope
1128 == QQmlJSScope::ownerOfProperty(descendant, propName).scope;
1131 const auto requiredHasBinding = [](
const QList<QQmlJSScope::ConstPtr> &scopesToSearch,
1132 const QQmlJSScope::ConstPtr &owner,
1133 const QString &propName) {
1134 for (
const auto &scope : scopesToSearch) {
1135 if (scope->property(propName).isAlias())
1137 const auto &[begin, end] = scope->ownPropertyBindings(propName);
1138 for (
auto it = begin; it != end; ++it) {
1140 const bool isRelevantBinding = QQmlSA::isRegularBindingType(it->bindingType())
1141 || it->bindingType() == QQmlSA::BindingType::Interceptor
1142 || it->bindingType() == QQmlSA::BindingType::ValueSource;
1143 if (!isRelevantBinding)
1145 if (QQmlJSScope::ownerOfProperty(scope, propName).scope == owner)
1153 const auto requiredUsedInRootAlias = [&](
const QQmlJSScope::ConstPtr &requiredScope,
1154 const QString &propName) {
1155 const Property target(requiredScope, propName);
1158 const auto allAliasesToTargetIt = m_propertyAliases.constFind(target);
1159 if (allAliasesToTargetIt == m_propertyAliases.constEnd())
1166 allAliasesToTargetIt->constBegin(), allAliasesToTargetIt->constEnd(),
1167 [](
const Property &property) {
return property.scope->isFileRootComponent(); });
1170 const auto requiredSetThroughAlias = [&](
const QList<QQmlJSScope::ConstPtr> &scopesToSearch,
1171 const QQmlJSScope::ConstPtr &requiredScope,
1172 const QString &propName) {
1173 const auto &propertyDefScope = QQmlJSScope::ownerOfProperty(requiredScope, propName);
1174 const auto &propertyAliases = m_propertyAliases[{ propertyDefScope.scope, propName }];
1175 for (
const auto &alias : propertyAliases) {
1176 for (
const auto &s : scopesToSearch) {
1177 if (s->hasOwnPropertyBindings(alias.name))
1184 const auto warn = [
this](
const QQmlJSScope::ConstPtr &prevRequiredScope,
1185 const QString &propName,
const QQmlJSScope::ConstPtr &defScope,
1186 const QQmlJSScope::ConstPtr &requiredScope,
1187 const QQmlJSScope::ConstPtr &descendant) {
1188 const auto &propertyScope = QQmlJSScope::ownerOfProperty(requiredScope, propName).scope;
1189 const QString propertyScopeName = !propertyScope.isNull()
1190 ? QQmlJSUtils::getScopeName(propertyScope, QQmlSA::ScopeType::QMLScope)
1193 std::optional<QQmlJSFixSuggestion> suggestion;
1195 QString message = QStringLiteral(
"Component is missing required property %1 from %2")
1197 .arg(propertyScopeName);
1198 if (requiredScope != descendant) {
1199 const QString requiredScopeName = prevRequiredScope
1200 ? QQmlJSUtils::getScopeName(prevRequiredScope, QQmlSA::ScopeType::QMLScope)
1203 if (!prevRequiredScope.isNull()) {
1204 if (
auto sourceScope = prevRequiredScope->baseType()) {
1205 suggestion = QQmlJSFixSuggestion{
1206 "%1:%2:%3: Property marked as required in %4."_L1
1207 .arg(sourceScope->filePath())
1208 .arg(sourceScope->sourceLocation().startLine)
1209 .arg(sourceScope->sourceLocation().startColumn)
1210 .arg(requiredScopeName),
1211 sourceScope->sourceLocation()
1215 if (sourceScope->isComposite())
1216 suggestion->setFilename(sourceScope->filePath());
1219 message +=
" (marked as required by %1)"_L1.arg(requiredScopeName);
1223 m_logger->log(message, qmlRequired, defScope->sourceLocation(),
true,
true, suggestion);
1226 populatePropertyAliases();
1228 for (
const auto &[_, defScope] : m_scopesByIrLocation.asKeyValueRange()) {
1229 if (defScope->isFileRootComponent() || defScope->isInlineComponent()
1230 || defScope->componentRootStatus() != QQmlJSScope::IsComponentRoot::No
1231 || defScope->scopeType() != QQmlSA::ScopeType::QMLScope) {
1235 QList<QQmlJSScope::ConstPtr> scopesToSearch;
1236 for (QQmlJSScope::ConstPtr scope = defScope; scope; scope = scope->baseType()) {
1237 const auto descendants = QList<QQmlJSScope::ConstPtr>()
1238 << scope << qmlScopeDescendants(scope);
1239 for (
const QQmlJSScope::ConstPtr &descendant : std::as_const(descendants)) {
1242 if (descendant != scope && descendant->isInlineComponent())
1244 scopesToSearch << descendant;
1245 const auto ownProperties = descendant->ownProperties();
1246 for (
auto propertyIt = ownProperties.constBegin();
1247 propertyIt != ownProperties.constEnd(); ++propertyIt) {
1248 const QString propName = propertyIt.key();
1249 if (descendant->hasOwnPropertyBindings(propName))
1252 QQmlJSScope::ConstPtr prevRequiredScope;
1253 for (
const QQmlJSScope::ConstPtr &requiredScope : std::as_const(scopesToSearch)) {
1256 if (isComponentRoot(requiredScope))
1259 if (!scopeRequiresProperty(requiredScope, propName, descendant)) {
1260 prevRequiredScope = requiredScope;
1264 if (requiredHasBinding(scopesToSearch, descendant, propName))
1267 if (requiredUsedInRootAlias(requiredScope, propName))
1270 if (requiredSetThroughAlias(scopesToSearch, requiredScope, propName))
1273 warn(prevRequiredScope, propName, defScope, requiredScope, descendant);
1274 prevRequiredScope = requiredScope;
1282void QQmlJSImportVisitor::processPropertyBindings()
1284 for (
auto it = m_propertyBindings.constBegin(); it != m_propertyBindings.constEnd(); ++it) {
1285 QQmlJSScope::Ptr scope = it.key();
1286 for (
auto &[visibilityScope, location, name] : it.value()) {
1287 if (!scope->hasProperty(name) && !m_logger->isDisabled()) {
1291 if (checkCustomParser(scope))
1295 std::optional<QQmlJSFixSuggestion> fixSuggestion;
1297 for (QQmlJSScope::ConstPtr baseScope = scope; !baseScope.isNull();
1298 baseScope = baseScope->baseType()) {
1299 if (
auto suggestion = QQmlJSUtils::didYouMean(
1300 name, baseScope->ownProperties().keys(), m_logger->filePath(), location);
1301 suggestion.has_value()) {
1302 fixSuggestion = suggestion;
1307 if (checkTypeResolved(scope))
1308 warnMissingPropertyForBinding(name, location, fixSuggestion);
1312 const auto property = scope->property(name);
1313 if (!property.type()) {
1314 m_logger->log(QStringLiteral(
"No type found for property \"%1\". This may be due "
1315 "to a missing import statement or incomplete "
1318 qmlMissingType, location);
1321 const auto &annotations = property.annotations();
1323 const auto deprecationAnn =
1324 std::find_if(annotations.cbegin(), annotations.cend(),
1325 [](
const QQmlJSAnnotation &ann) {
return ann.isDeprecation(); });
1327 if (deprecationAnn != annotations.cend()) {
1328 const auto deprecation = deprecationAnn->deprecation();
1330 QString message = QStringLiteral(
"Binding on deprecated property \"%1\"")
1331 .arg(property.propertyName());
1333 if (!deprecation.reason.isEmpty())
1334 message.append(QStringLiteral(
" (Reason: %1)").arg(deprecation.reason));
1336 m_logger->log(message, qmlDeprecated, location);
1342void QQmlJSImportVisitor::checkSignal(
1343 const QQmlJSScope::ConstPtr &signalScope,
const QQmlJS::SourceLocation &location,
1344 const QString &handlerName,
const QStringList &handlerParameters)
1346 const auto signal = QQmlSignalNames::handlerNameToSignalName(handlerName);
1348 std::optional<QQmlJSMetaMethod> signalMethod;
1349 const auto setSignalMethod = [&](
const QQmlJSScope::ConstPtr &scope,
const QString &name) {
1350 const auto methods = scope->methods(name, QQmlJSMetaMethodType::Signal);
1351 if (!methods.isEmpty())
1352 signalMethod = methods[0];
1355 if (signal.has_value()) {
1356 if (signalScope->hasMethod(*signal)) {
1357 setSignalMethod(signalScope, *signal);
1358 }
else if (
auto p = QQmlJSUtils::propertyFromChangedHandler(signalScope, handlerName)) {
1363 if (
auto notify = p->notify(); !notify.isEmpty()) {
1364 setSignalMethod(signalScope, notify);
1366 Q_ASSERT(!p->bindable().isEmpty());
1367 signalMethod = QQmlJSMetaMethod {};
1372 if (!signalMethod.has_value()) {
1377 if (signalScope->baseTypeName() == QStringLiteral(
"Connections")) {
1379 u"Implicitly defining \"%1\" as signal handler in Connections is deprecated. "
1380 u"Create a function instead: \"function %2(%3) { ... }\"."_s.arg(
1381 handlerName, handlerName, handlerParameters.join(u", ")),
1382 qmlUnqualified, location,
true,
true);
1386 auto baseType = QQmlJSScope::nonCompositeBaseType(signalScope);
1387 if (baseType && baseType->hasCustomParser())
1391 QStringLiteral(
"no matching signal found for handler \"%1\"").arg(handlerName),
1392 qmlUnqualified, location,
true,
true);
1396 const auto signalParameters = signalMethod->parameters();
1397 QHash<QString, qsizetype> parameterNameIndexes;
1399 for (
int i = 0, end = signalParameters.size(); i < end; i++) {
1400 auto &p = signalParameters[i];
1401 parameterNameIndexes[p.name()] = i;
1403 auto signalName = [&]() {
1405 return u" called %1"_s.arg(*signal);
1408 auto type = p.type();
1411 "Type %1 of parameter %2 in signal%3 was not found, but is required to compile "
1413 p.typeName(), p.name(), signalName(),
1414 handlerName, didYouAddAllImports),
1415 qmlSignalParameters, location);
1419 if (type->isComposite())
1427 auto parameterName = [&]() {
1428 if (p.name().isEmpty())
1430 return u" called %1"_s.arg(p.name());
1432 switch (type->accessSemantics()) {
1433 case QQmlJSScope::AccessSemantics::Reference:
1435 m_logger->log(QStringLiteral(
"Type %1 of parameter%2 in signal%3 should be "
1436 "passed by pointer to be able to compile %4. ")
1437 .arg(p.typeName(), parameterName(), signalName(),
1439 qmlSignalParameters, location);
1441 case QQmlJSScope::AccessSemantics::Value:
1442 case QQmlJSScope::AccessSemantics::Sequence:
1446 "Type %1 of parameter%2 in signal%3 should be passed by "
1447 "value or const reference to be able to compile %4. ")
1448 .arg(p.typeName(), parameterName(), signalName(),
1450 qmlSignalParameters, location);
1452 case QQmlJSScope::AccessSemantics::None:
1454 QStringLiteral(
"Type %1 of parameter%2 in signal%3 required by the "
1455 "compilation of %4 cannot be used. ")
1456 .arg(p.typeName(), parameterName(), signalName(), handlerName),
1457 qmlSignalParameters, location);
1462 if (handlerParameters.size() > signalParameters.size()) {
1463 m_logger->log(QStringLiteral(
"Signal handler for \"%2\" has more formal"
1464 " parameters than the signal it handles.")
1466 qmlSignalParameters, location);
1470 for (qsizetype i = 0, end = handlerParameters.size(); i < end; i++) {
1471 const QStringView handlerParameter = handlerParameters.at(i);
1472 auto it = parameterNameIndexes.constFind(handlerParameter.toString());
1473 if (it == parameterNameIndexes.constEnd())
1475 const qsizetype j = *it;
1480 m_logger->log(QStringLiteral(
"Parameter %1 to signal handler for \"%2\""
1481 " is called \"%3\". The signal has a parameter"
1482 " of the same name in position %4.")
1484 .arg(handlerName, handlerParameter)
1486 qmlSignalParameters, location);
1490void QQmlJSImportVisitor::addDefaultProperties()
1492 QQmlJSScope::ConstPtr parentScope = m_currentScope->parentScope();
1493 if (m_currentScope == m_exportedRootScope || parentScope->isArrayScope()
1494 || m_currentScope->isInlineComponent())
1497 m_pendingDefaultProperties[m_currentScope->parentScope()] << m_currentScope;
1499 if (checkCustomParser(parentScope))
1503
1504
1505
1506
1507
1508
1509
1510
1511
1513 parentScope = parentScope->baseType();
1515 const QString defaultPropertyName =
1516 parentScope ? parentScope->defaultPropertyName() : QString();
1518 if (defaultPropertyName.isEmpty())
1523 QQmlJSMetaPropertyBinding binding(m_currentScope->sourceLocation(), defaultPropertyName);
1524 binding.setObject(QQmlJSUtils::getScopeName(m_currentScope, QQmlSA::ScopeType::QMLScope),
1525 QQmlJSScope::ConstPtr(m_currentScope));
1526 m_bindings.append(UnfinishedBinding { m_currentScope->parentScope(), [=]() {
return binding; },
1527 QQmlJSScope::UnnamedPropertyTarget });
1530void QQmlJSImportVisitor::breakInheritanceCycles(
const QQmlJSScope::Ptr &originalScope)
1532 QList<QQmlJSScope::ConstPtr> scopes;
1533 for (QQmlJSScope::ConstPtr scope = originalScope; scope;) {
1534 if (scopes.contains(scope)) {
1535 QString inheritenceCycle;
1536 for (
const auto &seen : std::as_const(scopes)) {
1537 inheritenceCycle.append(seen->baseTypeName());
1538 inheritenceCycle.append(QLatin1String(
" -> "));
1540 inheritenceCycle.append(scopes.first()->baseTypeName());
1542 const QString message = QStringLiteral(
"%1 is part of an inheritance cycle: %2")
1543 .arg(originalScope->baseTypeName(), inheritenceCycle);
1544 m_logger->log(message, qmlInheritanceCycle, scope->sourceLocation());
1545 originalScope->clearBaseType();
1546 originalScope->setBaseTypeError(message);
1550 scopes.append(scope);
1552 const auto newScope = scope->baseType();
1553 if (newScope.isNull()) {
1554 const QString error = scope->baseTypeError();
1555 const QString name = scope->baseTypeName();
1556 if (!error.isEmpty()) {
1557 m_logger->log(error, qmlImport, scope->sourceLocation(),
true,
true);
1558 }
else if (!name.isEmpty() && !m_unresolvedTypes.hasSeen(scope)
1559 && !m_logger->isDisabled()) {
1561 name +
' '_L1 + wasNotFound +
' '_L1 + didYouAddAllImports,
1562 qmlImport, scope->sourceLocation(),
true,
true,
1563 QQmlJSUtils::didYouMean(scope->baseTypeName(),
1564 m_rootScopeImports.types().keys(),
1565 m_logger->filePath(),
1566 scope->sourceLocation()));
1574void QQmlJSImportVisitor::checkDeprecation(
const QQmlJSScope::ConstPtr &originalScope)
1576 for (QQmlJSScope::ConstPtr scope = originalScope; scope; scope = scope->baseType()) {
1577 for (
const QQmlJSAnnotation &annotation : scope->annotations()) {
1578 if (annotation.isDeprecation()) {
1579 QQQmlJSDeprecation deprecation = annotation.deprecation();
1582 QStringLiteral(
"Type \"%1\" is deprecated").arg(scope->internalName());
1584 if (!deprecation.reason.isEmpty())
1585 message.append(QStringLiteral(
" (Reason: %1)").arg(deprecation.reason));
1587 m_logger->log(message, qmlDeprecated, originalScope->sourceLocation());
1593void QQmlJSImportVisitor::checkGroupedAndAttachedScopes(QQmlJSScope::ConstPtr scope)
1597 if (checkCustomParser(scope))
1600 auto children = scope->childScopes();
1601 while (!children.isEmpty()) {
1602 auto childScope = children.takeFirst();
1603 const auto type = childScope->scopeType();
1605 case QQmlSA::ScopeType::GroupedPropertyScope:
1606 case QQmlSA::ScopeType::AttachedPropertyScope:
1607 if (!childScope->baseType()) {
1608 m_logger->log(QStringLiteral(
"unknown %1 property scope %2.")
1609 .arg(type == QQmlSA::ScopeType::GroupedPropertyScope
1610 ? QStringLiteral(
"grouped")
1611 : QStringLiteral(
"attached"),
1612 childScope->internalName()),
1613 qmlUnqualified, childScope->sourceLocation());
1615 children.append(childScope->childScopes());
1623void QQmlJSImportVisitor::checkForComponentTypeWithProperties(
const QQmlJSScope::ConstPtr &scope)
1625 const QQmlJSScope::ConstPtr base = scope->baseType();
1632 if (base->isComposite())
1635 if (base->internalName() !=
"QQmlComponent"_L1)
1638 const auto ownProperties = scope->ownProperties();
1639 for (
const auto &property : ownProperties) {
1640 m_logger->log(
"Component objects cannot declare new properties."_L1,
1641 qmlSyntax, property.sourceLocation());
1645bool QQmlJSImportVisitor::checkCustomParser(
const QQmlJSScope::ConstPtr &scope)
1647 return scope->isInCustomParserParent();
1650void QQmlJSImportVisitor::flushPendingSignalParameters()
1652 const QQmlJSMetaSignalHandler handler = m_signalHandlers[m_pendingSignalHandler];
1653 for (
const QString ¶meter : handler.signalParameters) {
1654 safeInsertJSIdentifier(m_currentScope, parameter,
1655 { QQmlJSScope::JavaScriptIdentifier::Injected,
1656 m_pendingSignalHandler, std::nullopt,
false });
1658 m_pendingSignalHandler = QQmlJS::SourceLocation();
1662
1663
1664
1665
1666
1667
1668QQmlJSMetaMethod::RelativeFunctionIndex
1669QQmlJSImportVisitor::addFunctionOrExpression(
const QQmlJSScope::ConstPtr &scope,
1670 const QString &name)
1672 auto &array = m_functionsAndExpressions[scope];
1673 array.emplaceBack(name);
1680 for (
const auto &function : std::as_const(m_functionStack))
1681 m_innerFunctions[function]++;
1682 m_functionStack.push({ scope, name });
1684 return QQmlJSMetaMethod::RelativeFunctionIndex {
int(array.size() - 1) };
1688
1689
1690
1691
1692
1693
1694
1695
1696void QQmlJSImportVisitor::forgetFunctionExpression(
const QString &name)
1698 auto nameToVerify = name.isEmpty() ? u"<anon>"_s : name;
1699 Q_UNUSED(nameToVerify);
1700 Q_ASSERT(!m_functionStack.isEmpty());
1701 Q_ASSERT(m_functionStack.top().name == nameToVerify);
1702 m_functionStack.pop();
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717int QQmlJSImportVisitor::synthesizeCompilationUnitRuntimeFunctionIndices(
1718 const QQmlJSScope::Ptr &scope,
int count)
const
1720 const auto suitableScope = [](
const QQmlJSScope::Ptr &scope) {
1721 const auto type = scope->scopeType();
1722 return type == QQmlSA::ScopeType::QMLScope
1723 || type == QQmlSA::ScopeType::GroupedPropertyScope
1724 || type == QQmlSA::ScopeType::AttachedPropertyScope;
1727 if (!suitableScope(scope))
1730 auto it = m_functionsAndExpressions.constFind(scope);
1731 if (it == m_functionsAndExpressions.cend())
1734 const auto &functionsAndExpressions = *it;
1735 for (
const QString &functionOrExpression : functionsAndExpressions) {
1736 scope->addOwnRuntimeFunctionIndex(
1737 static_cast<QQmlJSMetaMethod::AbsoluteFunctionIndex>(count));
1754 count += m_innerFunctions.value({ scope, functionOrExpression }, 0);
1760void QQmlJSImportVisitor::populateRuntimeFunctionIndicesForDocument()
const
1763 const auto synthesize = [&](
const QQmlJSScope::Ptr ¤t) {
1764 count = synthesizeCompilationUnitRuntimeFunctionIndices(current, count);
1766 QQmlJSUtils::traverseFollowingQmlIrObjectStructure(m_exportedRootScope, synthesize);
1769bool QQmlJSImportVisitor::visit(QQmlJS::AST::ExpressionStatement *ast)
1771 if (m_pendingSignalHandler.isValid()) {
1772 enterEnvironment(QQmlSA::ScopeType::SignalHandlerFunctionScope, u"signalhandler"_s,
1773 ast->firstSourceLocation());
1774 flushPendingSignalParameters();
1779void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ExpressionStatement *)
1781 if (m_currentScope->scopeType() == QQmlSA::ScopeType::SignalHandlerFunctionScope) {
1788 const QQmlJS::SourceLocation &srcLocation);
1791 QQmlJSLogger *logger)
1793 QStringView namespaceName{ superType };
1794 namespaceName = namespaceName.first(namespaceName.indexOf(u'.'));
1795 logger->log(u"Namespace '%1' of '%2' must start with an upper case letter."_s.arg(namespaceName)
1797 qmlUncreatableType, location,
true,
true);
1800bool QQmlJSImportVisitor::visit(UiObjectDefinition *definition)
1802 const QString superType = buildName(definition->qualifiedTypeNameId);
1804 const bool isRoot = !rootScopeIsValid();
1805 Q_ASSERT(!superType.isEmpty());
1810 const qsizetype indexOfTypeName = superType.lastIndexOf(u'.');
1811 const bool looksLikeGroupedProperty = superType.front().isLower();
1813 if (indexOfTypeName != -1 && looksLikeGroupedProperty) {
1814 logLowerCaseImport(superType, definition->qualifiedTypeNameId->identifierToken,
1818 if (!looksLikeGroupedProperty) {
1820 enterEnvironment(QQmlSA::ScopeType::QMLScope, superType,
1821 definition->firstSourceLocation());
1823 enterRootScope(QQmlSA::ScopeType::QMLScope, superType,
1824 definition->firstSourceLocation());
1825 m_currentScope->setIsRootFileComponentFlag(
true);
1828 const QTypeRevision revision = m_currentScope->baseTypeRevision();
1829 if (
auto base = m_currentScope->baseType(); base) {
1830 if (isRoot && base->internalName() == u"QQmlComponent") {
1831 m_logger->log(u"Qml top level type cannot be 'Component'."_s, qmlTopLevelComponent,
1832 definition->qualifiedTypeNameId->identifierToken,
true,
true);
1834 if (base->isSingleton() && m_currentScope->isComposite()) {
1835 m_logger->log(u"Singleton Type %1 is not creatable."_s.arg(
1836 m_currentScope->baseTypeName()),
1837 qmlUncreatableType, definition->qualifiedTypeNameId->identifierToken,
1840 }
else if (!base->isCreatable()) {
1842 m_logger->log(u"Type %1 is not creatable."_s.arg(m_currentScope->baseTypeName()),
1843 qmlUncreatableType, definition->qualifiedTypeNameId->identifierToken,
1847 if (m_nextIsInlineComponent) {
1848 Q_ASSERT(std::holds_alternative<InlineComponentNameType>(m_currentRootName));
1849 const QString &name = std::get<InlineComponentNameType>(m_currentRootName);
1850 m_currentScope->setIsInlineComponent(
true);
1851 m_currentScope->setInlineComponentName(name);
1852 m_currentScope->setOwnModuleName(m_exportedRootScope->moduleName());
1853 auto precedence = quint8(QQmlJS::PrecedenceValues::InlineComponent);
1854 m_rootScopeImports.setType(name, { m_currentScope, revision, precedence });
1855 m_nextIsInlineComponent =
false;
1858 addDefaultProperties();
1859 Q_ASSERT(m_currentScope->scopeType() == QQmlSA::ScopeType::QMLScope);
1860 m_qmlTypes.append(m_currentScope);
1862 m_objectDefinitionScopes << m_currentScope;
1864 enterEnvironmentNonUnique(QQmlSA::ScopeType::GroupedPropertyScope, superType,
1865 definition->firstSourceLocation());
1866 m_bindings.append(createNonUniqueScopeBinding(m_currentScope, superType,
1867 definition->firstSourceLocation()));
1868 QQmlJSScope::resolveTypes(
1869 m_currentScope, m_rootScopeImports.contextualTypes(), &m_usedTypes);
1872 m_currentScope->setAnnotations(parseAnnotations(definition->annotations));
1877void QQmlJSImportVisitor::endVisit(UiObjectDefinition *)
1879 QQmlJSScope::resolveTypes(m_currentScope, m_rootScopeImports.contextualTypes(), &m_usedTypes);
1883bool QQmlJSImportVisitor::visit(UiInlineComponent *component)
1885 if (!std::holds_alternative<RootDocumentNameType>(m_currentRootName)) {
1886 m_logger->log(u"Nested inline components are not supported"_s, qmlSyntax,
1887 component->firstSourceLocation());
1891 const auto it = m_seenInlineComponents.constFind(component->name);
1892 if (it != m_seenInlineComponents.cend()) {
1893 m_logger->log(
"Duplicate inline component '%1'"_L1.arg(it.key()),
1894 qmlDuplicateInlineComponent, component->firstSourceLocation());
1895 m_logger->log(
"Note: previous component named '%1' here"_L1.arg(it.key()),
1896 qmlDuplicateInlineComponent, it.value(),
true,
true, {},
1897 component->firstSourceLocation().startLine);
1899 m_seenInlineComponents[component->name] = component->firstSourceLocation();
1902 m_nextIsInlineComponent =
true;
1903 m_currentRootName = component->name.toString();
1907void QQmlJSImportVisitor::endVisit(UiInlineComponent *component)
1909 m_currentRootName = RootDocumentNameType();
1910 if (m_nextIsInlineComponent) {
1911 m_logger->log(u"Inline component declaration must be followed by a typename"_s,
1912 qmlSyntax, component->firstSourceLocation());
1914 m_nextIsInlineComponent =
false;
1917bool QQmlJSImportVisitor::visit(UiPublicMember *publicMember)
1919 switch (publicMember->type) {
1920 case UiPublicMember::Signal: {
1921 const QString signalName = publicMember->name.toString();
1922 UiParameterList *param = publicMember->parameters;
1923 QQmlJSMetaMethod method;
1924 method.setMethodType(QQmlJSMetaMethodType::Signal);
1925 method.setReturnTypeName(QStringLiteral(
"void"));
1926 method.setMethodName(signalName);
1927 method.setSourceLocation(combine(publicMember->firstSourceLocation(),
1928 publicMember->lastSourceLocation()));
1929 method.setOtherMethodIndex(
1930 QQmlJSMetaMethod::RelativeFunctionIndex(m_currentScope->ownMethods().size()));
1932 method.addParameter(
1933 QQmlJSMetaParameter(
1934 param->name.toString(),
1935 param->type ? param->type->toString() : QString()
1937 param = param->next;
1939 m_currentScope->addOwnMethod(method);
1942 case UiPublicMember::Property: {
1943 const QString propertyName = publicMember->name.toString();
1944 QString typeName = buildName(publicMember->memberType);
1945 if (typeName.contains(u'.') && typeName.front().isLower()) {
1946 logLowerCaseImport(typeName, publicMember->typeToken, m_logger);
1950 const bool isAlias = (typeName == u"alias"_s);
1952 auto tryParseAlias = [&]() {
1954 if (!publicMember->statement) {
1955 m_logger->log(QStringLiteral(
"Invalid alias expression - an initializer is needed."),
1956 qmlSyntax, publicMember->memberType->firstSourceLocation());
1959 const auto expression = cast<ExpressionStatement *>(publicMember->statement);
1960 auto node = expression ? expression->expression :
nullptr;
1961 auto fex = cast<FieldMemberExpression *>(node);
1964 aliasExpr.prepend(u'.' + fex->name.toString());
1965 fex = cast<FieldMemberExpression *>(node);
1968 if (
const auto idExpression = cast<IdentifierExpression *>(node)) {
1969 aliasExpr.prepend(idExpression->name.toString());
1973 m_logger->log(QStringLiteral(
"Invalid alias expression. Only IDs and field "
1974 "member expressions can be aliased."),
1975 qmlSyntax, publicMember->statement->firstSourceLocation());
1980 if (m_rootScopeImports.hasType(typeName)
1981 && !m_rootScopeImports.type(typeName).scope.isNull()) {
1982 if (m_importTypeLocationMap.contains(typeName))
1983 m_usedTypes.insert(typeName);
1986 QQmlJSMetaProperty prop;
1987 prop.setPropertyName(propertyName);
1988 prop.setIsList(publicMember->typeModifier == QLatin1String(
"list"));
1989 prop.setIsWritable(!publicMember->isReadonly());
1990 prop.setIsFinal(publicMember->isFinal());
1991 prop.setIsVirtual(publicMember->isVirtual());
1992 prop.setIsOverride(publicMember->isOverride());
1993 prop.setAliasExpression(aliasExpr);
1994 prop.setSourceLocation(
1995 combine(publicMember->firstSourceLocation(), publicMember->colonToken));
1997 isAlias ? QQmlJSScope::ConstPtr() : m_rootScopeImports.type(typeName).scope;
1999 prop.setType(prop.isList() ? type->listType() : type);
2000 const QString internalName = type->internalName();
2001 prop.setTypeName(internalName.isEmpty() ? typeName : internalName);
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.setOtherMethodIndex(
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.setJsFunctionIndex(addFunctionOrExpression(m_currentScope, method.methodName()));
2143 method.setOtherMethodIndex(
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);
2702void QQmlJSImportVisitor::addImportWithLocation(
2703 const QString &name,
const QQmlJS::SourceLocation &loc,
bool hadWarnings)
2705 if (m_importTypeLocationMap.contains(name)
2706 && m_importTypeLocationMap.values(name).contains(loc)) {
2710 m_importTypeLocationMap.insert(name, loc);
2715 if (!hadWarnings && loc.isValid())
2716 m_importLocations.insert(loc);
2719QList<QQmlJS::DiagnosticMessage> QQmlJSImportVisitor::importFromHost(
2720 const QString &path,
const QString &prefix,
const QQmlJS::SourceLocation &location)
2722 QFileInfo fileInfo(path);
2723 if (!fileInfo.exists()) {
2724 m_logger->log(
"File or directory you are trying to import does not exist: %1."_L1.arg(path),
2725 qmlImport, location);
2729 if (fileInfo.isFile()) {
2730 const auto scope = m_importer->importFile(path);
2731 const QString actualPrefix = prefix.isEmpty() ? scope->internalName() : prefix;
2732 auto precedence = quint8(QQmlJS::PrecedenceValues::Default);
2733 m_rootScopeImports.setType(actualPrefix, { scope, QTypeRevision(), precedence });
2734 addImportWithLocation(actualPrefix, location,
false);
2738 if (fileInfo.isDir()) {
2739 auto precedence = quint8(QQmlJS::PrecedenceValues::Default);
2740 auto scopes = m_importer->importDirectory(path, precedence, prefix);
2741 const auto types = scopes.types();
2742 const auto warnings = scopes.warnings();
2743 m_rootScopeImports.add(std::move(scopes));
2744 for (
auto it = types.keyBegin(), end = types.keyEnd(); it != end; it++)
2745 addImportWithLocation(*it, location, !warnings.isEmpty());
2750 "%1 is neither a file nor a directory. Are sure the import path is correct?"_L1.arg(
2752 qmlImport, location);
2756QList<QQmlJS::DiagnosticMessage> QQmlJSImportVisitor::importFromQrc(
2757 const QString &path,
const QString &prefix,
const QQmlJS::SourceLocation &location)
2759 Q_ASSERT(path.startsWith(u':'));
2760 const QQmlJSResourceFileMapper *mapper = m_importer->resourceFileMapper();
2764 const auto pathNoColon = QStringView(path).mid(1);
2765 if (mapper->isFile(pathNoColon)) {
2766 const auto entry = m_importer->resourceFileMapper()->entry(
2767 QQmlJSResourceFileMapper::resourceFileFilter(pathNoColon.toString()));
2768 const auto scope = m_importer->importFile(entry.filePath);
2769 const QString actualPrefix =
2770 prefix.isEmpty() ? QFileInfo(entry.resourcePath).baseName() : prefix;
2771 auto precedence = quint8(QQmlJS::PrecedenceValues::Default);
2772 m_rootScopeImports.setType(actualPrefix, { scope, QTypeRevision(), precedence });
2773 addImportWithLocation(actualPrefix, location,
false);
2777 auto scopes = m_importer->importDirectory(path, quint8(QQmlJS::PrecedenceValues::Default), prefix);
2778 const auto types = scopes.types();
2779 const auto warnings = scopes.warnings();
2780 m_rootScopeImports.add(std::move(scopes));
2781 for (
auto it = types.keyBegin(), end = types.keyEnd(); it != end; it++)
2782 addImportWithLocation(*it, location, !warnings.isEmpty());
2786bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiImport *import)
2789 QString prefix = QLatin1String(
"");
2790 if (import->asToken.isValid()) {
2791 prefix += import->importId;
2792 if (!import->importId.isEmpty() && !import->importId.front().isUpper()) {
2793 m_logger->log(u"Import qualifier '%1' must start with a capital letter."_s.arg(
2795 qmlImport, import->importIdToken,
true,
true);
2797 m_seenModuleQualifiers.append(prefix);
2800 const QString filename = import->fileName.toString();
2801 if (!filename.isEmpty()) {
2802 const QUrl url(filename);
2803 const QString scheme = url.scheme();
2804 const QQmlJS::SourceLocation importLocation = import->firstSourceLocation();
2805 if (scheme ==
""_L1) {
2806 QFileInfo fileInfo(url.path());
2807 QString absolute = fileInfo.isRelative()
2808 ? QDir::cleanPath(QDir(m_implicitImportDirectory).filePath(filename))
2810 auto warnings = absolute.startsWith(u':')
2811 ? importFromQrc(absolute, prefix, importLocation)
2812 : importFromHost(absolute, prefix, importLocation);
2813 processImportWarnings(
"path \"%1\""_L1.arg(url.path()), warnings, importLocation);
2815 }
else if (scheme ==
"file"_L1) {
2816 auto warnings = importFromHost(url.path(), prefix, importLocation);
2817 processImportWarnings(
"URL \"%1\""_L1.arg(url.path()), warnings, importLocation);
2819 }
else if (scheme ==
"qrc"_L1) {
2820 auto warnings = importFromQrc(
":"_L1 + url.path(), prefix, importLocation);
2821 processImportWarnings(
"URL \"%1\""_L1.arg(url.path()), warnings, importLocation);
2824 m_logger->log(
"Unknown import syntax. Imports can be paths, qrc urls or file urls"_L1,
2825 qmlImport, import->firstSourceLocation());
2829 const QString path = buildName(import->importUri);
2831 QStringList staticModulesProvided;
2833 auto imported = m_importer->importModule(
2834 path, quint8(QQmlJS::PrecedenceValues::Default), prefix,
2835 import->version ? import->version->version : QTypeRevision(), &staticModulesProvided);
2836 const auto types = imported.types();
2837 const auto warnings = imported.warnings();
2838 m_rootScopeImports.add(std::move(imported));
2839 for (
auto it = types.keyBegin(), end = types.keyEnd(); it != end; it++)
2840 addImportWithLocation(*it, import->firstSourceLocation(), !warnings.isEmpty());
2842 if (prefix.isEmpty()) {
2843 for (
const QString &staticModule : std::as_const(staticModulesProvided)) {
2845 if (path != staticModule && m_importStaticModuleLocationMap.contains(staticModule))
2848 m_importStaticModuleLocationMap[staticModule] = import->firstSourceLocation();
2852 processImportWarnings(
2853 QStringLiteral(
"module \"%1\"").arg(path), warnings, import->firstSourceLocation());
2857#if QT_VERSION >= QT_VERSION_CHECK(6
, 6
, 0
)
2859void handlePragmaValues(QQmlJS::AST::UiPragma *pragma, F &&assign)
2861 for (
const QQmlJS::AST::UiPragmaValueList *v = pragma->values; v; v = v->next)
2866void handlePragmaValues(QQmlJS::AST::UiPragma *pragma, F &&assign)
2868 assign(pragma->value);
2872bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiPragma *pragma)
2874 if (pragma->name == u"Strict"_s) {
2879 if (!m_logger->wasCategoryChanged(qmlCompiler))
2880 m_logger->setCategorySeverity(qmlCompiler, QQmlJS::WarningSeverity::Warning);
2881 }
else if (pragma->name == u"ComponentBehavior") {
2882 handlePragmaValues(pragma, [
this, pragma](QStringView value) {
2883 if (value == u"Bound") {
2884 m_scopesById.setComponentsAreBound(
true);
2885 }
else if (value == u"Unbound") {
2886 m_scopesById.setComponentsAreBound(
false);
2888 m_logger->log(u"Unknown argument \"%1\" to pragma ComponentBehavior"_s.arg(value),
2889 qmlSyntax, pragma->firstSourceLocation());
2892 }
else if (pragma->name == u"FunctionSignatureBehavior") {
2893 handlePragmaValues(pragma, [
this, pragma](QStringView value) {
2894 if (value == u"Enforced") {
2895 m_scopesById.setSignaturesAreEnforced(
true);
2896 }
else if (value == u"Ignored") {
2897 m_scopesById.setSignaturesAreEnforced(
false);
2900 u"Unknown argument \"%1\" to pragma FunctionSignatureBehavior"_s.arg(value),
2901 qmlSyntax, pragma->firstSourceLocation());
2904 }
else if (pragma->name == u"ValueTypeBehavior") {
2905 handlePragmaValues(pragma, [
this, pragma](QStringView value) {
2906 if (value == u"Copy") {
2908 }
else if (value == u"Reference") {
2910 }
else if (value == u"Addressable") {
2911 m_scopesById.setValueTypesAreAddressable(
true);
2912 }
else if (value == u"Inaddressable") {
2913 m_scopesById.setValueTypesAreAddressable(
false);
2914 }
else if (value == u"Assertable") {
2915 m_scopesById.setValueTypesAreAssertable(
true);
2916 }
else if (value == u"Inassertable") {
2917 m_scopesById.setValueTypesAreAssertable(
false);
2919 m_logger->log(u"Unknown argument \"%1\" to pragma ValueTypeBehavior"_s.arg(value),
2920 qmlSyntax, pragma->firstSourceLocation());
2928void QQmlJSImportVisitor::throwRecursionDepthError()
2930 m_logger->log(QStringLiteral(
"Maximum statement or expression depth exceeded"),
2931 qmlRecursionDepthErrors, QQmlJS::SourceLocation());
2934bool QQmlJSImportVisitor::visit(QQmlJS::AST::ClassDeclaration *ast)
2936 enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, ast->name.toString(),
2937 ast->firstSourceLocation());
2941void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ClassDeclaration *)
2946bool QQmlJSImportVisitor::visit(QQmlJS::AST::ForStatement *ast)
2948 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"forloop"),
2949 ast->firstSourceLocation());
2953void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ForStatement *)
2958bool QQmlJSImportVisitor::visit(QQmlJS::AST::ForEachStatement *ast)
2960 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"foreachloop"),
2961 ast->firstSourceLocation());
2965void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ForEachStatement *)
2970bool QQmlJSImportVisitor::visit(QQmlJS::AST::Block *ast)
2972 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"block"),
2973 ast->firstSourceLocation());
2975 if (m_pendingSignalHandler.isValid())
2976 flushPendingSignalParameters();
2981void QQmlJSImportVisitor::endVisit(QQmlJS::AST::Block *)
2986bool QQmlJSImportVisitor::visit(QQmlJS::AST::CaseBlock *ast)
2988 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"case"),
2989 ast->firstSourceLocation());
2993void QQmlJSImportVisitor::endVisit(QQmlJS::AST::CaseBlock *)
2998bool QQmlJSImportVisitor::visit(QQmlJS::AST::Catch *catchStatement)
3000 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"catch"),
3001 catchStatement->firstSourceLocation());
3005void QQmlJSImportVisitor::endVisit(QQmlJS::AST::Catch *)
3010bool QQmlJSImportVisitor::visit(QQmlJS::AST::WithStatement *ast)
3012 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"with"),
3013 ast->firstSourceLocation());
3015 m_logger->log(QStringLiteral(
"with statements are strongly discouraged in QML "
3016 "and might cause false positives when analysing unqualified "
3018 qmlWith, ast->firstSourceLocation());
3023void QQmlJSImportVisitor::endVisit(QQmlJS::AST::WithStatement *)
3028bool QQmlJSImportVisitor::visit(QQmlJS::AST::FormalParameterList *fpl)
3030 const auto &boundedNames = fpl->boundNames();
3031 for (
auto const &boundName : boundedNames) {
3033 std::optional<QString> typeName;
3034 if (TypeAnnotation *annotation = boundName.typeAnnotation.data())
3035 if (Type *type = annotation->type)
3036 typeName = type->toString();
3037 safeInsertJSIdentifier(m_currentScope, boundName.id,
3038 { QQmlJSScope::JavaScriptIdentifier::Parameter,
3039 boundName.location, typeName,
false });
3044void QQmlJSImportVisitor::createAttachedAndGroupedScopes(UiQualifiedId *propertyName)
3046 bool needsResolution =
false;
3047 int scopesEnteredCounter = 0;
3049 for (
auto group = propertyName; group->next; group = group->next) {
3050 const QString idName = group->name.toString();
3052 if (idName.isEmpty())
3055 if (group == propertyName && isImportPrefix(idName)) {
3056 prefix = idName + u'.';
3060 const auto scopeKind = idName.front().isUpper() ? QQmlSA::ScopeType::AttachedPropertyScope
3061 : QQmlSA::ScopeType::GroupedPropertyScope;
3064 enterEnvironmentNonUnique(scopeKind, prefix + idName, group->firstSourceLocation());
3066 m_bindings.append(createNonUniqueScopeBinding(m_currentScope, prefix + idName,
3067 group->firstSourceLocation()));
3069 ++scopesEnteredCounter;
3070 needsResolution = needsResolution || !exists;
3075 for (
int i=0; i < scopesEnteredCounter; ++i) {
3080 if (needsResolution) {
3081 QQmlJSScope::resolveTypes(
3082 m_currentScope, m_rootScopeImports.contextualTypes(), &m_usedTypes);
3086bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiObjectBinding *uiob)
3090 Q_ASSERT(uiob->qualifiedTypeNameId);
3092 const QString typeName = buildName(uiob->qualifiedTypeNameId);
3093 if (typeName.front().isLower() && typeName.contains(u'.')) {
3094 logLowerCaseImport(typeName, uiob->qualifiedTypeNameId->identifierToken, m_logger);
3097 createAttachedAndGroupedScopes(uiob->qualifiedId);
3099 enterEnvironment(QQmlSA::ScopeType::QMLScope, typeName,
3100 uiob->qualifiedTypeNameId->identifierToken);
3102 m_qmlTypes.append(m_currentScope);
3103 m_objectBindingScopes << m_currentScope;
3107int QQmlJSImportVisitor::openAttachedAndGroupedScopes(UiQualifiedId *propertyName)
3110 int scopesEnteredCounter = 0;
3111 auto group = propertyName;
3112 for (; group->next; group = group->next) {
3113 const QString idName = group->name.toString();
3115 if (idName.isEmpty())
3118 if (group == propertyName && isImportPrefix(idName)) {
3119 prefix = idName + u'.';
3123 const auto scopeKind = idName.front().isUpper() ? QQmlSA::ScopeType::AttachedPropertyScope
3124 : QQmlSA::ScopeType::GroupedPropertyScope;
3126 [[maybe_unused]]
bool exists =
3127 enterEnvironmentNonUnique(scopeKind, prefix + idName, group->firstSourceLocation());
3129 scopesEnteredCounter++;
3133 return scopesEnteredCounter;
3136void QQmlJSImportVisitor::endVisit(QQmlJS::AST::UiObjectBinding *uiob)
3138 QQmlJSScope::resolveTypes(m_currentScope, m_rootScopeImports.contextualTypes(), &m_usedTypes);
3140 const QQmlJSScope::Ptr childScope = m_currentScope;
3143 const int scopesEnteredCounter = openAttachedAndGroupedScopes(uiob->qualifiedId);
3148 auto group = uiob->qualifiedId;
3149 for (; group->next; group = group->next) { }
3150 const QString propertyName = group->name.toString();
3152 if (m_currentScope->isNameDeferred(propertyName)) {
3153 bool foundIds =
false;
3154 QList<QQmlJSScope::ConstPtr> childScopes { childScope };
3156 while (!childScopes.isEmpty()) {
3157 const QQmlJSScope::ConstPtr scope = childScopes.takeFirst();
3158 m_scopesById.possibleIds(
3159 scope, scope, QQmlJSScopesByIdOption::Default,
3160 [&](
const QString &id, QQmlJSScopesById::Confidence confidence) {
3163 Q_UNUSED(confidence);
3165 return QQmlJSScopesById::CallbackResult::StopSearch;
3168 childScopes << scope->childScopes();
3173 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
3175 qmlDeferredPropertyId, uiob->firstSourceLocation());
3179 if (checkCustomParser(m_currentScope)) {
3183 m_pendingPropertyObjectBindings
3184 << PendingPropertyObjectBinding { m_currentScope, childScope, propertyName,
3185 uiob->firstSourceLocation(), uiob->hasOnToken };
3187 QQmlJSMetaPropertyBinding binding(uiob->firstSourceLocation(), propertyName);
3188 if (uiob->hasOnToken) {
3189 if (childScope->hasInterface(u"QQmlPropertyValueInterceptor"_s)) {
3190 binding.setInterceptor(QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope),
3191 QQmlJSScope::ConstPtr(childScope));
3193 binding.setValueSource(QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope),
3194 QQmlJSScope::ConstPtr(childScope));
3197 binding.setObject(QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope),
3198 QQmlJSScope::ConstPtr(childScope));
3200 m_bindings.append(UnfinishedBinding { m_currentScope, [=]() {
return binding; } });
3203 for (
int i = 0; i < scopesEnteredCounter; ++i)
3207bool QQmlJSImportVisitor::visit(ExportDeclaration *)
3209 Q_ASSERT(rootScopeIsValid());
3210 Q_ASSERT(m_exportedRootScope != m_globalScope);
3211 Q_ASSERT(m_currentScope == m_globalScope);
3212 m_currentScope = m_exportedRootScope;
3216void QQmlJSImportVisitor::endVisit(ExportDeclaration *)
3218 Q_ASSERT(rootScopeIsValid());
3219 m_currentScope = m_exportedRootScope->parentScope();
3220 Q_ASSERT(m_currentScope == m_globalScope);
3223bool QQmlJSImportVisitor::visit(ESModule *module)
3225 Q_ASSERT(!rootScopeIsValid());
3226 enterRootScope(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"module"),
3227 module->firstSourceLocation());
3228 m_currentScope->setIsScript(
true);
3229 importBaseModules();
3234void QQmlJSImportVisitor::endVisit(ESModule *)
3236 QQmlJSScope::resolveTypes(
3237 m_exportedRootScope, m_rootScopeImports.contextualTypes(), &m_usedTypes);
3240bool QQmlJSImportVisitor::visit(Program *program)
3242 Q_ASSERT(m_globalScope == m_currentScope);
3243 Q_ASSERT(!rootScopeIsValid());
3244 enterRootScope(QQmlSA::ScopeType::JSFunctionScope, u"script"_s, program->firstSourceLocation());
3245 m_exportedRootScope->setIsScript(
true);
3246 importBaseModules();
3250void QQmlJSImportVisitor::endVisit(Program *)
3252 QQmlJSScope::resolveTypes(
3253 m_exportedRootScope, m_rootScopeImports.contextualTypes(), &m_usedTypes);
3256void QQmlJSImportVisitor::endVisit(QQmlJS::AST::FieldMemberExpression *fieldMember)
3260 const QString name = fieldMember->name.toString();
3261 if (m_importTypeLocationMap.contains(name)) {
3262 const QQmlJSImportedScope type = m_rootScopeImports.type(name);
3263 if (type.scope.isNull()) {
3264 if (m_rootScopeImports.hasType(name))
3265 m_usedTypes.insert(name);
3266 }
else if (!type.scope->ownAttachedTypeName().isEmpty()) {
3267 m_usedTypes.insert(name);
3272bool QQmlJSImportVisitor::visit(QQmlJS::AST::IdentifierExpression *idexp)
3274 const QString name = idexp->name.toString();
3275 if (m_importTypeLocationMap.contains(name)) {
3276 m_usedTypes.insert(name);
3282bool QQmlJSImportVisitor::visit(QQmlJS::AST::PatternElement *element)
3285 if (element->isVariableDeclaration()) {
3286 QQmlJS::AST::BoundNames names;
3287 element->boundNames(&names);
3288 for (
const auto &name : std::as_const(names)) {
3289 std::optional<QString> typeName;
3290 if (TypeAnnotation *annotation = name.typeAnnotation.data())
3291 if (Type *type = annotation->type)
3292 typeName = type->toString();
3293 using Kind = QQmlJSScope::JavaScriptIdentifier::Kind;
3294 const Kind kind = (element->scope == QQmlJS::AST::VariableScope::Var)
3295 ? Kind::FunctionScoped
3296 : Kind::LexicalScoped;
3297 const QString variableName = name.id;
3298 if (kind == Kind::LexicalScoped) {
3299 const QQmlJS::SourceLocation location = element->firstSourceLocation();
3300 if (
auto previousDeclaration = m_currentScope->ownJSIdentifier(variableName)) {
3301 m_logger->log(
"Identifier '%1' has already been declared"_L1.arg(variableName), qmlSyntax,
3303 m_logger->log(
"Note: previous declaration of '%1' here"_L1.arg(variableName), qmlSyntax,
3304 previousDeclaration->location);
3307 const bool isConstVariable = element->scope == QQmlJS::AST::VariableScope::Const;
3308 const bool couldInsert = safeInsertJSIdentifier(m_currentScope,
3310 { (element->scope == QQmlJS::AST::VariableScope::Var)
3311 ? QQmlJSScope::JavaScriptIdentifier::FunctionScoped
3312 : QQmlJSScope::JavaScriptIdentifier::LexicalScoped,
3313 name.location, typeName,
3323bool QQmlJSImportVisitor::visit(IfStatement *statement)
3325 if (BinaryExpression *binary = cast<BinaryExpression *>(statement->expression)) {
3326 if (binary->op == QSOperator::Assign) {
3328 "Assignment in condition: did you mean to use \"===\" or \"==\" instead of \"=\"?"_L1,
3329 qmlAssignmentInCondition, binary->operatorToken);