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 const QQmlJS::SourceLocation invalidLoc;
480 const auto types = m_rootScopeImports.types();
481 for (
auto it = types.keyBegin(), end = types.keyEnd(); it != end; it++)
482 addImportWithLocation(*it, invalidLoc,
false);
484 if (!m_qmldirFiles.isEmpty())
485 m_rootScopeImports.addWarnings(m_importer->importQmldirs(m_qmldirFiles));
489 if (!m_logger->filePath().endsWith(u".qmltypes"_s)) {
490 m_rootScopeImports.add(m_importer->importDirectory(
491 m_implicitImportDirectory, QQmlJS::PrecedenceValues::ImplicitImport));
496 if (QQmlJSResourceFileMapper *mapper = m_importer->resourceFileMapper()) {
497 const QStringList resourcePaths = mapper->resourcePaths(QQmlJSResourceFileMapper::Filter {
498 m_logger->filePath(), QStringList(), QQmlJSResourceFileMapper::Resource });
499 for (
const QString &path : resourcePaths) {
500 const qsizetype lastSlash = path.lastIndexOf(QLatin1Char(
'/'));
503 m_rootScopeImports.add(m_importer->importDirectory(
504 path.first(lastSlash), QQmlJS::PrecedenceValues::ImplicitImport));
509 processImportWarnings(QStringLiteral(
"base modules"), m_rootScopeImports.warnings());
512bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiProgram *)
516 if (
auto elementName = QFileInfo(m_logger->filePath()).baseName();
517 !elementName.isEmpty() && elementName[0].isUpper()) {
518 m_rootScopeImports.setType(elementName,
519 { m_exportedRootScope, QTypeRevision{ },
520 QQmlJS::PrecedenceValues::ImplicitImport });
526void QQmlJSImportVisitor::endVisit(UiProgram *)
528 for (
const auto &scope : std::as_const(m_objectBindingScopes)) {
529 breakInheritanceCycles(scope);
530 checkDeprecation(scope);
531 checkForComponentTypeWithProperties(scope);
534 for (
const auto &scope : std::as_const(m_objectDefinitionScopes)) {
535 if (m_pendingDefaultProperties.contains(scope))
537 breakInheritanceCycles(scope);
538 checkDeprecation(scope);
539 checkForComponentTypeWithProperties(scope);
542 const auto &keys = m_pendingDefaultProperties.keys();
543 for (
const auto &scope : keys) {
544 breakInheritanceCycles(scope);
545 checkDeprecation(scope);
546 checkForComponentTypeWithProperties(scope);
550 resolveGroupProperties();
552 for (
const auto &scope : std::as_const(m_objectDefinitionScopes))
553 checkGroupedAndAttachedScopes(scope);
556 processDefaultProperties();
557 processPropertyTypes();
558 processMethodTypes();
559 processPropertyBindings();
560 processPropertyBindingObjects();
561 checkRequiredProperties();
563 auto unusedImports = m_importLocations;
564 for (
const QString &type : std::as_const(m_usedTypes)) {
565 const auto &importLocations = m_importTypeLocationMap.values(type);
566 for (
const auto &importLocation : importLocations)
567 unusedImports.remove(importLocation);
570 if (unusedImports.isEmpty())
574 const auto &imports = m_importStaticModuleLocationMap.values();
575 for (
const QQmlJS::SourceLocation &import : imports)
576 unusedImports.remove(import);
578 for (
const auto &import : unusedImports) {
579 m_logger->log(QString::fromLatin1(
"Unused import"), qmlUnusedImports, import);
582 populateRuntimeFunctionIndicesForDocument();
587 ExpressionStatement *expr = cast<ExpressionStatement *>(statement);
589 if (!statement || !expr->expression)
592 switch (expr->expression->kind) {
593 case Node::Kind_StringLiteral:
594 return cast<StringLiteral *>(expr->expression)->value.toString();
595 case Node::Kind_NumericLiteral:
596 return cast<NumericLiteral *>(expr->expression)->value;
602QList<QQmlJSAnnotation> QQmlJSImportVisitor::parseAnnotations(QQmlJS::AST::UiAnnotationList *list)
605 QList<QQmlJSAnnotation> annotationList;
607 for (UiAnnotationList *item = list; item !=
nullptr; item = item->next) {
608 UiAnnotation *annotation = item->annotation;
610 QQmlJSAnnotation qqmljsAnnotation;
611 qqmljsAnnotation.name = buildName(annotation->qualifiedTypeNameId);
613 for (UiObjectMemberList *memberItem = annotation->initializer->members; memberItem !=
nullptr; memberItem = memberItem->next) {
614 switch (memberItem->member->kind) {
615 case Node::Kind_UiScriptBinding: {
616 auto *scriptBinding = QQmlJS::AST::cast<UiScriptBinding*>(memberItem->member);
617 qqmljsAnnotation.bindings[buildName(scriptBinding->qualifiedId)]
618 = bindingToVariant(scriptBinding->statement);
627 annotationList.append(qqmljsAnnotation);
630 return annotationList;
633void QQmlJSImportVisitor::setAllBindings()
635 using Key = std::pair<QQmlJSScope::ConstPtr, QString>;
636 QHash<Key, QQmlJS::SourceLocation> foundBindings;
638 for (
auto it = m_bindings.cbegin(); it != m_bindings.cend(); ++it) {
640 const QQmlJSScope::Ptr type = it->owner;
641 if (!checkTypeResolved(type))
650 if (!type->isFullyResolved())
652 auto binding = it->create();
653 if (!binding.isValid())
655 type->addOwnPropertyBinding(binding, it->specifier);
658 if (binding.hasInterceptor() || binding.hasValueSource())
660 const QString propertyName = binding.propertyName();
661 QQmlJSMetaProperty property = type->property(propertyName);
664
665
666
667
668
669 if (!property.isValid())
673 if (property.isList())
676 const Key key = std::make_pair(type, propertyName);
677 auto sourceLocationIt = foundBindings.constFind(key);
678 if (sourceLocationIt == foundBindings.constEnd()) {
679 foundBindings.insert(key, binding.sourceLocation());
683 const QQmlJS::SourceLocation location = binding.sourceLocation();
684 m_logger->log(
"Duplicate binding on property '%1'"_L1.arg(propertyName),
685 qmlDuplicatePropertyBinding, location);
686 m_logger->log(
"Note: previous binding on '%1' here"_L1.arg(propertyName),
687 qmlDuplicatePropertyBinding, *sourceLocationIt,
true,
true, {},
692void QQmlJSImportVisitor::processDefaultProperties()
694 for (
auto it = m_pendingDefaultProperties.constBegin();
695 it != m_pendingDefaultProperties.constEnd(); ++it) {
696 QQmlJSScope::ConstPtr parentScope = it.key();
699 if (checkCustomParser(parentScope))
702 if (!checkTypeResolved(parentScope))
706
707
708
709
710
711
712
713
714
716 parentScope = parentScope->baseType();
718 const QString defaultPropertyName =
719 parentScope ? parentScope->defaultPropertyName() : QString();
721 if (defaultPropertyName.isEmpty()) {
724 bool isComponent =
false;
725 for (QQmlJSScope::ConstPtr s = parentScope; s; s = s->baseType()) {
726 if (s->internalName() == QStringLiteral(
"QQmlComponent")) {
732 if (!isComponent && checkTypeResolved(parentScope)) {
733 m_logger->log(QStringLiteral(
"Cannot assign to non-existent default property"),
734 qmlMissingProperty, it.value().constFirst()->sourceLocation());
740 const QQmlJSMetaProperty defaultProp = parentScope->property(defaultPropertyName);
741 auto propType = defaultProp.type();
742 const auto handleUnresolvedDefaultProperty = [&](
const QQmlJSScope::ConstPtr &) {
744 m_logger->log(QStringLiteral(
"Property \"%1\" has incomplete type \"%2\". You may be "
745 "missing an import.")
746 .arg(defaultPropertyName)
747 .arg(defaultProp.typeName()),
748 qmlUnresolvedType, it.value().constFirst()->sourceLocation());
751 const auto assignToUnknownProperty = [&]() {
754 for (
const QQmlJSScope::Ptr &scope : std::as_const(*it))
755 scope->setAssignedToUnknownProperty(
true);
758 if (propType.isNull()) {
759 handleUnresolvedDefaultProperty(propType);
760 assignToUnknownProperty();
764 if (it.value().size() > 1
765 && !defaultProp.isList()
766 && !propType->isListProperty()) {
768 QStringLiteral(
"Cannot assign multiple objects to a default non-list property"),
769 qmlNonListProperty, it.value().constFirst()->sourceLocation());
772 if (!checkTypeResolved(propType, handleUnresolvedDefaultProperty)) {
773 assignToUnknownProperty();
777 for (
const QQmlJSScope::Ptr &scope : std::as_const(*it)) {
778 if (!checkTypeResolved(scope))
783 if (propType->canAssign(scope)) {
784 scope->setIsWrappedInImplicitComponent(
785 causesImplicitComponentWrapping(defaultProp, scope));
789 m_logger->log(QStringLiteral(
"Cannot assign to default property of incompatible type"),
790 qmlIncompatibleType, scope->sourceLocation());
795void QQmlJSImportVisitor::processPropertyTypes()
797 for (
const PendingPropertyType &type : std::as_const(m_pendingPropertyTypes)) {
798 Q_ASSERT(type.scope->hasOwnProperty(type.name));
800 auto property = type.scope->ownProperty(type.name);
802 if (
const auto propertyType = QQmlJSScope::findType(
803 property.typeName(), m_rootScopeImports.contextualTypes()).scope) {
804 property.setType(property.isList() ? propertyType->listType() : propertyType);
805 type.scope->addOwnProperty(property);
807 QString msg = property.typeName() +
' '_L1 + wasNotFound +
' '_L1 + didYouAddAllImports;
808 if (property.typeName() ==
"list"_L1)
809 msg +=
" list is not a type. It requires an element type argument (eg. list<int>)"_L1;
810 m_logger->log(msg, qmlImport, type.location);
815void QQmlJSImportVisitor::processMethodTypes()
817 const auto isEnumUsedAsType = [&](QStringView typeName,
const QQmlJS::SourceLocation &loc) {
818 if (typeName ==
"enum"_L1) {
822 const auto split = typeName.tokenize(u'.').toContainer<QVarLengthArray<QStringView, 4>>();
823 if (split.size() != 2)
826 const QStringView scopeName = split[0];
827 const QStringView enumName = split[1];
829 if (
auto scope = QQmlJSScope::findType(scopeName.toString(),
830 m_rootScopeImports.contextualTypes()).scope) {
831 if (scope->enumeration(enumName.toString()).isValid()) {
833 "QML enumerations are not types. Use int, or use double if the enum's underlying type does not fit into int."_L1,
834 qmlEnumsAreNotTypes, loc);
841 for (
const auto &method : std::as_const(m_pendingMethodTypeAnnotations)) {
842 for (
auto [it, end] = method.scope->mutableOwnMethodsRange(method.methodName); it != end; ++it) {
843 const auto [parameterBegin, parameterEnd] = it->mutableParametersRange();
844 for (
auto parameter = parameterBegin; parameter != parameterEnd; ++parameter) {
845 const int parameterIndex = parameter - parameterBegin;
846 if (isEnumUsedAsType(parameter->typeName(), method.locations[parameterIndex]))
848 if (
const auto parameterType = QQmlJSScope::findType(
849 parameter->typeName(), m_rootScopeImports.contextualTypes()).scope) {
850 parameter->setType({ parameterType });
853 u"\"%1\" was not found for the type of parameter \"%2\" in method \"%3\"."_s
854 .arg(parameter->typeName(), parameter->name(), it->methodName()),
855 qmlUnresolvedType, method.locations[parameter - parameterBegin]);
859 if (isEnumUsedAsType(it->returnTypeName(), method.locations.last()))
861 if (
const auto returnType = QQmlJSScope::findType(
862 it->returnTypeName(), m_rootScopeImports.contextualTypes()).scope) {
863 it->setReturnType({ returnType });
865 m_logger->log(u"\"%1\" was not found for the return type of method \"%2\"."_s.arg(
866 it->returnTypeName(), it->methodName()),
867 qmlUnresolvedType, method.locations.last());
875
876
877
878
879
880
881
885 for (QStringView propertyName: possiblyGroupedProperty.tokenize(u".")) {
886 property = scope->property(propertyName.toString());
887 if (property.isValid())
888 scope = property.type();
895void QQmlJSImportVisitor::processPropertyBindingObjects()
897 QSet<std::pair<QQmlJSScope::Ptr, QString>> foundLiterals;
905 QSet<std::pair<QQmlJSScope::Ptr, QString>> visited;
906 for (
const PendingPropertyObjectBinding &objectBinding :
907 std::as_const(m_pendingPropertyObjectBindings)) {
909 const auto uniqueBindingId = std::make_pair(objectBinding.scope, objectBinding.name);
910 if (visited.contains(uniqueBindingId))
912 visited.insert(uniqueBindingId);
914 auto [existingBindingsBegin, existingBindingsEnd] =
915 uniqueBindingId.first->ownPropertyBindings(uniqueBindingId.second);
916 const bool hasLiteralBindings =
917 std::any_of(existingBindingsBegin, existingBindingsEnd,
918 [](
const QQmlJSMetaPropertyBinding &x) {
return x.hasLiteral(); });
919 if (hasLiteralBindings)
920 foundLiterals.insert(uniqueBindingId);
924 QSet<std::pair<QQmlJSScope::Ptr, QString>> foundObjects;
925 QSet<std::pair<QQmlJSScope::Ptr, QString>> foundInterceptors;
926 QSet<std::pair<QQmlJSScope::Ptr, QString>> foundValueSources;
928 for (
const PendingPropertyObjectBinding &objectBinding :
929 std::as_const(m_pendingPropertyObjectBindings)) {
930 const QString propertyName = objectBinding.name;
931 QQmlJSScope::Ptr childScope = objectBinding.childScope;
933 const auto assignToUnknownProperty = [&]() {
936 childScope->setAssignedToUnknownProperty(
true);
940 if (!checkTypeResolved(objectBinding.scope)) {
941 assignToUnknownProperty();
945 QQmlJSMetaProperty property = resolveProperty(propertyName, objectBinding.scope);
947 if (!property.isValid()) {
948 warnMissingPropertyForBinding(propertyName, objectBinding.location);
951 const auto handleUnresolvedProperty = [&](
const QQmlJSScope::ConstPtr &) {
953 m_logger->log(QStringLiteral(
"Property \"%1\" has incomplete type \"%2\". You may be "
954 "missing an import.")
956 .arg(property.typeName()),
957 qmlUnresolvedType, objectBinding.location);
960 if (property.type().isNull()) {
961 assignToUnknownProperty();
962 handleUnresolvedProperty(property.type());
967 if (!checkTypeResolved(property.type(), handleUnresolvedProperty)) {
968 assignToUnknownProperty();
970 }
else if (!checkTypeResolved(childScope)) {
974 if (!objectBinding.onToken && !property.type()->canAssign(childScope)) {
975 m_logger->log(QStringLiteral(
"Cannot assign object of type %1 to %2")
976 .arg(QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope))
977 .arg(property.typeName()),
978 qmlIncompatibleType, childScope->sourceLocation());
982 childScope->setIsWrappedInImplicitComponent(
983 causesImplicitComponentWrapping(property, childScope));
986 const auto uniqueBindingId = std::make_pair(objectBinding.scope, objectBinding.name);
987 const QString typeName = QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope);
989 auto isConditionalBinding = [&]() ->
bool {
991
992
993
994
995 return childScope->hasOwnPropertyBindings(u"enabled"_s)
996 || childScope->hasOwnPropertyBindings(u"when"_s)
997 || childScope->hasOwnPropertyBindings(u"running"_s);
1000 if (objectBinding.onToken) {
1001 if (childScope->hasInterface(QStringLiteral(
"QQmlPropertyValueInterceptor"))) {
1002 if (foundInterceptors.contains(uniqueBindingId)) {
1003 if (!isConditionalBinding()) {
1004 m_logger->log(QStringLiteral(
"Duplicate interceptor on property \"%1\"")
1006 qmlDuplicatePropertyBinding, objectBinding.location);
1009 foundInterceptors.insert(uniqueBindingId);
1011 }
else if (childScope->hasInterface(QStringLiteral(
"QQmlPropertyValueSource"))) {
1012 if (foundValueSources.contains(uniqueBindingId)) {
1013 if (!isConditionalBinding()) {
1014 m_logger->log(QStringLiteral(
"Duplicate value source on property \"%1\"")
1016 qmlDuplicatePropertyBinding, objectBinding.location);
1018 }
else if (foundObjects.contains(uniqueBindingId)
1019 || foundLiterals.contains(uniqueBindingId)) {
1020 if (!isConditionalBinding()) {
1021 m_logger->log(QStringLiteral(
"Cannot combine value source and binding on "
1024 qmlDuplicatePropertyBinding, objectBinding.location);
1027 foundValueSources.insert(uniqueBindingId);
1030 m_logger->log(QStringLiteral(
"On-binding for property \"%1\" has wrong type \"%2\"")
1033 qmlIncompatibleType, objectBinding.location);
1036 if (foundValueSources.contains(uniqueBindingId)) {
1037 if (!isConditionalBinding()) {
1039 QStringLiteral(
"Cannot combine value source and binding on property \"%1\"")
1041 qmlDuplicatePropertyBinding, objectBinding.location);
1044 foundObjects.insert(uniqueBindingId);
1052 QList<QQmlJSScope::ConstPtr> descendants;
1053 std::vector<QQmlJSScope::ConstPtr> toVisit;
1055 toVisit.push_back(scope);
1056 while (!toVisit.empty()) {
1057 const QQmlJSScope::ConstPtr s = toVisit.back();
1063 toVisit.insert(toVisit.end(), s->childScopesBegin(), s->childScopesEnd());
1070void QQmlJSImportVisitor::populatePropertyAliases()
1072 for (
const auto &alias : std::as_const(m_aliasDefinitions)) {
1073 const auto &[aliasScope, aliasName] = alias;
1074 if (aliasScope.isNull())
1077 auto property = aliasScope->ownProperty(aliasName);
1078 if (!property.isValid() || !property.aliasTargetScope())
1081 Property target(property.aliasTargetScope(), property.aliasTargetName());
1084 m_propertyAliases[target].append(alias);
1085 property = target.scope->property(target.name);
1086 target = Property(property.aliasTargetScope(), property.aliasTargetName());
1087 }
while (property.isAlias());
1091void QQmlJSImportVisitor::checkRequiredProperties()
1093 for (
const auto &required : std::as_const(m_requiredProperties)) {
1094 if (!required.scope->hasProperty(required.name)) {
1096 QStringLiteral(
"Property \"%1\" was marked as required but does not exist.")
1097 .arg(required.name),
1098 qmlRequired, required.location);
1102 const auto compType = m_rootScopeImports.type(u"Component"_s).scope;
1103 const auto isComponentRoot = [&](
const QQmlJSScope::ConstPtr &requiredScope) {
1104 if (requiredScope->isWrappedInImplicitComponent())
1106 if (
const auto s = requiredScope->parentScope(); s && s->baseType() == compType)
1111 const auto scopeRequiresProperty = [&](
const QQmlJSScope::ConstPtr &requiredScope,
1112 const QString &propName,
1113 const QQmlJSScope::ConstPtr &descendant) {
1114 if (!requiredScope->isPropertyLocallyRequired(propName))
1118 return QQmlJSScope::ownerOfProperty(requiredScope, propName).scope
1119 == QQmlJSScope::ownerOfProperty(descendant, propName).scope;
1122 const auto requiredHasBinding = [](
const QList<QQmlJSScope::ConstPtr> &scopesToSearch,
1123 const QQmlJSScope::ConstPtr &owner,
1124 const QString &propName) {
1125 for (
const auto &scope : scopesToSearch) {
1126 if (scope->property(propName).isAlias())
1128 const auto &[begin, end] = scope->ownPropertyBindings(propName);
1129 for (
auto it = begin; it != end; ++it) {
1131 const bool isRelevantBinding = QQmlSA::isRegularBindingType(it->bindingType())
1132 || it->bindingType() == QQmlSA::BindingType::Interceptor
1133 || it->bindingType() == QQmlSA::BindingType::ValueSource;
1134 if (!isRelevantBinding)
1136 if (QQmlJSScope::ownerOfProperty(scope, propName).scope == owner)
1144 const auto requiredUsedInRootAlias = [&](
const QQmlJSScope::ConstPtr &requiredScope,
1145 const QString &propName) {
1146 const Property target(requiredScope, propName);
1149 const auto allAliasesToTargetIt = m_propertyAliases.constFind(target);
1150 if (allAliasesToTargetIt == m_propertyAliases.constEnd())
1157 allAliasesToTargetIt->constBegin(), allAliasesToTargetIt->constEnd(),
1158 [](
const Property &property) {
return property.scope->isFileRootComponent(); });
1161 const auto requiredSetThroughAlias = [&](
const QList<QQmlJSScope::ConstPtr> &scopesToSearch,
1162 const QQmlJSScope::ConstPtr &requiredScope,
1163 const QString &propName) {
1164 const auto &propertyDefScope = QQmlJSScope::ownerOfProperty(requiredScope, propName);
1165 const auto &propertyAliases = m_propertyAliases[{ propertyDefScope.scope, propName }];
1166 for (
const auto &alias : propertyAliases) {
1167 for (
const auto &s : scopesToSearch) {
1168 if (s->hasOwnPropertyBindings(alias.name))
1175 const auto warn = [
this](
const QQmlJSScope::ConstPtr &prevRequiredScope,
1176 const QString &propName,
const QQmlJSScope::ConstPtr &defScope,
1177 const QQmlJSScope::ConstPtr &requiredScope,
1178 const QQmlJSScope::ConstPtr &descendant) {
1179 const auto &propertyScope = QQmlJSScope::ownerOfProperty(requiredScope, propName).scope;
1180 const QString propertyScopeName = !propertyScope.isNull()
1181 ? QQmlJSUtils::getScopeName(propertyScope, QQmlSA::ScopeType::QMLScope)
1184 std::optional<QQmlJSFixSuggestion> suggestion;
1186 QString message = QStringLiteral(
"Component is missing required property %1 from %2")
1188 .arg(propertyScopeName);
1189 if (requiredScope != descendant) {
1190 const QString requiredScopeName = prevRequiredScope
1191 ? QQmlJSUtils::getScopeName(prevRequiredScope, QQmlSA::ScopeType::QMLScope)
1194 if (!prevRequiredScope.isNull()) {
1195 if (
auto sourceScope = prevRequiredScope->baseType()) {
1196 suggestion = QQmlJSFixSuggestion{
1197 "%1:%2:%3: Property marked as required in %4."_L1
1198 .arg(sourceScope->filePath())
1199 .arg(sourceScope->sourceLocation().startLine)
1200 .arg(sourceScope->sourceLocation().startColumn)
1201 .arg(requiredScopeName),
1202 sourceScope->sourceLocation()
1206 if (sourceScope->isComposite())
1207 suggestion->setFilename(sourceScope->filePath());
1210 message +=
" (marked as required by %1)"_L1.arg(requiredScopeName);
1214 m_logger->log(message, qmlRequired, defScope->sourceLocation(),
true,
true, suggestion);
1217 populatePropertyAliases();
1219 for (
const auto &[_, defScope] : m_scopesByIrLocation.asKeyValueRange()) {
1220 if (defScope->isFileRootComponent() || defScope->isInlineComponent()
1221 || defScope->componentRootStatus() != QQmlJSScope::IsComponentRoot::No
1222 || defScope->scopeType() != QQmlSA::ScopeType::QMLScope) {
1226 QList<QQmlJSScope::ConstPtr> scopesToSearch;
1227 for (QQmlJSScope::ConstPtr scope = defScope; scope; scope = scope->baseType()) {
1228 const auto descendants = QList<QQmlJSScope::ConstPtr>()
1229 << scope << qmlScopeDescendants(scope);
1230 for (
const QQmlJSScope::ConstPtr &descendant : std::as_const(descendants)) {
1233 if (descendant != scope && descendant->isInlineComponent())
1235 scopesToSearch << descendant;
1236 const auto ownProperties = descendant->ownProperties();
1237 for (
auto propertyIt = ownProperties.constBegin();
1238 propertyIt != ownProperties.constEnd(); ++propertyIt) {
1239 const QString propName = propertyIt.key();
1240 if (descendant->hasOwnPropertyBindings(propName))
1243 QQmlJSScope::ConstPtr prevRequiredScope;
1244 for (
const QQmlJSScope::ConstPtr &requiredScope : std::as_const(scopesToSearch)) {
1247 if (isComponentRoot(requiredScope))
1250 if (!scopeRequiresProperty(requiredScope, propName, descendant)) {
1251 prevRequiredScope = requiredScope;
1255 if (requiredHasBinding(scopesToSearch, descendant, propName))
1258 if (requiredUsedInRootAlias(requiredScope, propName))
1261 if (requiredSetThroughAlias(scopesToSearch, requiredScope, propName))
1264 warn(prevRequiredScope, propName, defScope, requiredScope, descendant);
1265 prevRequiredScope = requiredScope;
1273void QQmlJSImportVisitor::processPropertyBindings()
1275 for (
auto it = m_propertyBindings.constBegin(); it != m_propertyBindings.constEnd(); ++it) {
1276 QQmlJSScope::Ptr scope = it.key();
1277 for (
auto &[visibilityScope, location, name] : it.value()) {
1278 if (!scope->hasProperty(name) && !m_logger->isDisabled()) {
1282 if (checkCustomParser(scope))
1286 std::optional<QQmlJSFixSuggestion> fixSuggestion;
1288 for (QQmlJSScope::ConstPtr baseScope = scope; !baseScope.isNull();
1289 baseScope = baseScope->baseType()) {
1290 if (
auto suggestion = QQmlJSUtils::didYouMean(
1291 name, baseScope->ownProperties().keys(), m_logger->filePath(), location);
1292 suggestion.has_value()) {
1293 fixSuggestion = suggestion;
1298 if (checkTypeResolved(scope))
1299 warnMissingPropertyForBinding(name, location, fixSuggestion);
1303 const auto property = scope->property(name);
1304 if (!property.type()) {
1305 m_logger->log(QStringLiteral(
"No type found for property \"%1\". This may be due "
1306 "to a missing import statement or incomplete "
1309 qmlMissingType, location);
1312 const auto &annotations = property.annotations();
1314 const auto deprecationAnn =
1315 std::find_if(annotations.cbegin(), annotations.cend(),
1316 [](
const QQmlJSAnnotation &ann) {
return ann.isDeprecation(); });
1318 if (deprecationAnn != annotations.cend()) {
1319 const auto deprecation = deprecationAnn->deprecation();
1321 QString message = QStringLiteral(
"Binding on deprecated property \"%1\"")
1322 .arg(property.propertyName());
1324 if (!deprecation.reason.isEmpty())
1325 message.append(QStringLiteral(
" (Reason: %1)").arg(deprecation.reason));
1327 m_logger->log(message, qmlDeprecated, location);
1333void QQmlJSImportVisitor::checkSignal(
1334 const QQmlJSScope::ConstPtr &signalScope,
const QQmlJS::SourceLocation &location,
1335 const QString &handlerName,
const QStringList &handlerParameters)
1337 const auto signal = QQmlSignalNames::handlerNameToSignalName(handlerName);
1339 std::optional<QQmlJSMetaMethod> signalMethod;
1340 const auto setSignalMethod = [&](
const QQmlJSScope::ConstPtr &scope,
const QString &name) {
1341 const auto methods = scope->methods(name, QQmlJSMetaMethodType::Signal);
1342 if (!methods.isEmpty())
1343 signalMethod = methods[0];
1346 if (signal.has_value()) {
1347 if (signalScope->hasMethod(*signal)) {
1348 setSignalMethod(signalScope, *signal);
1349 }
else if (
auto p = QQmlJSUtils::propertyFromChangedHandler(signalScope, handlerName)) {
1354 if (
auto notify = p->notify(); !notify.isEmpty()) {
1355 setSignalMethod(signalScope, notify);
1357 Q_ASSERT(!p->bindable().isEmpty());
1358 signalMethod = QQmlJSMetaMethod {};
1363 if (!signalMethod.has_value()) {
1368 if (signalScope->baseTypeName() == QStringLiteral(
"Connections")) {
1370 u"Implicitly defining \"%1\" as signal handler in Connections is deprecated. "
1371 u"Create a function instead: \"function %2(%3) { ... }\"."_s.arg(
1372 handlerName, handlerName, handlerParameters.join(u", ")),
1373 qmlUnqualified, location,
true,
true);
1377 auto baseType = QQmlJSScope::nonCompositeBaseType(signalScope);
1378 if (baseType && baseType->hasCustomParser())
1382 QStringLiteral(
"no matching signal found for handler \"%1\"").arg(handlerName),
1383 qmlUnqualified, location,
true,
true);
1387 const auto signalParameters = signalMethod->parameters();
1388 QHash<QString, qsizetype> parameterNameIndexes;
1390 for (
int i = 0, end = signalParameters.size(); i < end; i++) {
1391 auto &p = signalParameters[i];
1392 parameterNameIndexes[p.name()] = i;
1394 auto signalName = [&]() {
1396 return u" called %1"_s.arg(*signal);
1399 auto type = p.type();
1402 "Type %1 of parameter %2 in signal%3 was not found, but is required to compile "
1404 p.typeName(), p.name(), signalName(),
1405 handlerName, didYouAddAllImports),
1406 qmlSignalParameters, location);
1410 if (type->isComposite())
1418 auto parameterName = [&]() {
1419 if (p.name().isEmpty())
1421 return u" called %1"_s.arg(p.name());
1423 switch (type->accessSemantics()) {
1424 case QQmlJSScope::AccessSemantics::Reference:
1426 m_logger->log(QStringLiteral(
"Type %1 of parameter%2 in signal%3 should be "
1427 "passed by pointer to be able to compile %4. ")
1428 .arg(p.typeName(), parameterName(), signalName(),
1430 qmlSignalParameters, location);
1432 case QQmlJSScope::AccessSemantics::Value:
1433 case QQmlJSScope::AccessSemantics::Sequence:
1437 "Type %1 of parameter%2 in signal%3 should be passed by "
1438 "value or const reference to be able to compile %4. ")
1439 .arg(p.typeName(), parameterName(), signalName(),
1441 qmlSignalParameters, location);
1443 case QQmlJSScope::AccessSemantics::None:
1445 QStringLiteral(
"Type %1 of parameter%2 in signal%3 required by the "
1446 "compilation of %4 cannot be used. ")
1447 .arg(p.typeName(), parameterName(), signalName(), handlerName),
1448 qmlSignalParameters, location);
1453 if (handlerParameters.size() > signalParameters.size()) {
1454 m_logger->log(QStringLiteral(
"Signal handler for \"%2\" has more formal"
1455 " parameters than the signal it handles.")
1457 qmlSignalParameters, location);
1461 for (qsizetype i = 0, end = handlerParameters.size(); i < end; i++) {
1462 const QStringView handlerParameter = handlerParameters.at(i);
1463 auto it = parameterNameIndexes.constFind(handlerParameter.toString());
1464 if (it == parameterNameIndexes.constEnd())
1466 const qsizetype j = *it;
1471 m_logger->log(QStringLiteral(
"Parameter %1 to signal handler for \"%2\""
1472 " is called \"%3\". The signal has a parameter"
1473 " of the same name in position %4.")
1475 .arg(handlerName, handlerParameter)
1477 qmlSignalParameters, location);
1481void QQmlJSImportVisitor::addDefaultProperties()
1483 QQmlJSScope::ConstPtr parentScope = m_currentScope->parentScope();
1484 if (m_currentScope == m_exportedRootScope || parentScope->isArrayScope()
1485 || m_currentScope->isInlineComponent())
1488 m_pendingDefaultProperties[m_currentScope->parentScope()] << m_currentScope;
1490 if (checkCustomParser(parentScope))
1494
1495
1496
1497
1498
1499
1500
1501
1502
1504 parentScope = parentScope->baseType();
1506 const QString defaultPropertyName =
1507 parentScope ? parentScope->defaultPropertyName() : QString();
1509 if (defaultPropertyName.isEmpty())
1514 QQmlJSMetaPropertyBinding binding(m_currentScope->sourceLocation(), defaultPropertyName);
1515 binding.setObject(QQmlJSUtils::getScopeName(m_currentScope, QQmlSA::ScopeType::QMLScope),
1516 QQmlJSScope::ConstPtr(m_currentScope));
1517 m_bindings.append(UnfinishedBinding { m_currentScope->parentScope(), [=]() {
return binding; },
1518 QQmlJSScope::UnnamedPropertyTarget });
1521void QQmlJSImportVisitor::breakInheritanceCycles(
const QQmlJSScope::Ptr &originalScope)
1523 QList<QQmlJSScope::ConstPtr> scopes;
1524 for (QQmlJSScope::ConstPtr scope = originalScope; scope;) {
1525 if (scopes.contains(scope)) {
1526 QString inheritenceCycle;
1527 for (
const auto &seen : std::as_const(scopes)) {
1528 inheritenceCycle.append(seen->baseTypeName());
1529 inheritenceCycle.append(QLatin1String(
" -> "));
1531 inheritenceCycle.append(scopes.first()->baseTypeName());
1533 const QString message = QStringLiteral(
"%1 is part of an inheritance cycle: %2")
1534 .arg(originalScope->baseTypeName(), inheritenceCycle);
1535 m_logger->log(message, qmlInheritanceCycle, scope->sourceLocation());
1536 originalScope->clearBaseType();
1537 originalScope->setBaseTypeError(message);
1541 scopes.append(scope);
1543 const auto newScope = scope->baseType();
1544 if (newScope.isNull()) {
1545 const QString error = scope->baseTypeError();
1546 const QString name = scope->baseTypeName();
1547 if (!error.isEmpty()) {
1548 m_logger->log(error, qmlImport, scope->sourceLocation(),
true,
true);
1549 }
else if (!name.isEmpty() && !m_unresolvedTypes.hasSeen(scope)
1550 && !m_logger->isDisabled()) {
1552 name +
' '_L1 + wasNotFound +
' '_L1 + didYouAddAllImports,
1553 qmlImport, scope->sourceLocation(),
true,
true,
1554 QQmlJSUtils::didYouMean(scope->baseTypeName(),
1555 m_rootScopeImports.types().keys(),
1556 m_logger->filePath(),
1557 scope->sourceLocation()));
1565void QQmlJSImportVisitor::checkDeprecation(
const QQmlJSScope::ConstPtr &originalScope)
1567 for (QQmlJSScope::ConstPtr scope = originalScope; scope; scope = scope->baseType()) {
1568 for (
const QQmlJSAnnotation &annotation : scope->annotations()) {
1569 if (annotation.isDeprecation()) {
1570 QQQmlJSDeprecation deprecation = annotation.deprecation();
1573 QStringLiteral(
"Type \"%1\" is deprecated").arg(scope->internalName());
1575 if (!deprecation.reason.isEmpty())
1576 message.append(QStringLiteral(
" (Reason: %1)").arg(deprecation.reason));
1578 m_logger->log(message, qmlDeprecated, originalScope->sourceLocation());
1584void QQmlJSImportVisitor::checkGroupedAndAttachedScopes(QQmlJSScope::ConstPtr scope)
1588 if (checkCustomParser(scope))
1591 auto children = scope->childScopes();
1592 while (!children.isEmpty()) {
1593 auto childScope = children.takeFirst();
1594 const auto type = childScope->scopeType();
1596 case QQmlSA::ScopeType::GroupedPropertyScope:
1597 case QQmlSA::ScopeType::AttachedPropertyScope:
1598 if (!childScope->baseType()) {
1599 m_logger->log(QStringLiteral(
"unknown %1 property scope %2.")
1600 .arg(type == QQmlSA::ScopeType::GroupedPropertyScope
1601 ? QStringLiteral(
"grouped")
1602 : QStringLiteral(
"attached"),
1603 childScope->internalName()),
1604 qmlUnqualified, childScope->sourceLocation());
1606 children.append(childScope->childScopes());
1614void QQmlJSImportVisitor::checkForComponentTypeWithProperties(
const QQmlJSScope::ConstPtr &scope)
1616 const QQmlJSScope::ConstPtr base = scope->baseType();
1623 if (base->isComposite())
1626 if (base->internalName() !=
"QQmlComponent"_L1)
1629 const auto ownProperties = scope->ownProperties();
1630 for (
const auto &property : ownProperties) {
1631 m_logger->log(
"Component objects cannot declare new properties."_L1,
1632 qmlSyntax, property.sourceLocation());
1636bool QQmlJSImportVisitor::checkCustomParser(
const QQmlJSScope::ConstPtr &scope)
1638 return scope->isInCustomParserParent();
1641void QQmlJSImportVisitor::flushPendingSignalParameters()
1643 const QQmlJSMetaSignalHandler handler = m_signalHandlers[m_pendingSignalHandler];
1644 for (
const QString ¶meter : handler.signalParameters) {
1645 safeInsertJSIdentifier(m_currentScope, parameter,
1646 { QQmlJSScope::JavaScriptIdentifier::Injected,
1647 m_pendingSignalHandler, std::nullopt,
false });
1649 m_pendingSignalHandler = QQmlJS::SourceLocation();
1653
1654
1655
1656
1657
1658
1659QQmlJSMetaMethod::RelativeFunctionIndex
1660QQmlJSImportVisitor::addFunctionOrExpression(
const QQmlJSScope::ConstPtr &scope,
1661 const QString &name)
1663 auto &array = m_functionsAndExpressions[scope];
1664 array.emplaceBack(name);
1671 for (
const auto &function : std::as_const(m_functionStack))
1672 m_innerFunctions[function]++;
1673 m_functionStack.push({ scope, name });
1675 return QQmlJSMetaMethod::RelativeFunctionIndex {
int(array.size() - 1) };
1679
1680
1681
1682
1683
1684
1685
1686
1687void QQmlJSImportVisitor::forgetFunctionExpression(
const QString &name)
1689 auto nameToVerify = name.isEmpty() ? u"<anon>"_s : name;
1690 Q_UNUSED(nameToVerify);
1691 Q_ASSERT(!m_functionStack.isEmpty());
1692 Q_ASSERT(m_functionStack.top().name == nameToVerify);
1693 m_functionStack.pop();
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708int QQmlJSImportVisitor::synthesizeCompilationUnitRuntimeFunctionIndices(
1709 const QQmlJSScope::Ptr &scope,
int count)
const
1711 const auto suitableScope = [](
const QQmlJSScope::Ptr &scope) {
1712 const auto type = scope->scopeType();
1713 return type == QQmlSA::ScopeType::QMLScope
1714 || type == QQmlSA::ScopeType::GroupedPropertyScope
1715 || type == QQmlSA::ScopeType::AttachedPropertyScope;
1718 if (!suitableScope(scope))
1721 auto it = m_functionsAndExpressions.constFind(scope);
1722 if (it == m_functionsAndExpressions.cend())
1725 const auto &functionsAndExpressions = *it;
1726 for (
const QString &functionOrExpression : functionsAndExpressions) {
1727 scope->addOwnRuntimeFunctionIndex(
1728 static_cast<QQmlJSMetaMethod::AbsoluteFunctionIndex>(count));
1745 count += m_innerFunctions.value({ scope, functionOrExpression }, 0);
1751void QQmlJSImportVisitor::populateRuntimeFunctionIndicesForDocument()
const
1754 const auto synthesize = [&](
const QQmlJSScope::Ptr ¤t) {
1755 count = synthesizeCompilationUnitRuntimeFunctionIndices(current, count);
1757 QQmlJSUtils::traverseFollowingQmlIrObjectStructure(m_exportedRootScope, synthesize);
1760bool QQmlJSImportVisitor::visit(QQmlJS::AST::ExpressionStatement *ast)
1762 if (m_pendingSignalHandler.isValid()) {
1763 enterEnvironment(QQmlSA::ScopeType::SignalHandlerFunctionScope, u"signalhandler"_s,
1764 ast->firstSourceLocation());
1765 flushPendingSignalParameters();
1770void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ExpressionStatement *)
1772 if (m_currentScope->scopeType() == QQmlSA::ScopeType::SignalHandlerFunctionScope) {
1779 const QQmlJS::SourceLocation &srcLocation);
1782 QQmlJSLogger *logger)
1784 QStringView namespaceName{ superType };
1785 namespaceName = namespaceName.first(namespaceName.indexOf(u'.'));
1786 logger->log(u"Namespace '%1' of '%2' must start with an upper case letter."_s.arg(namespaceName)
1788 qmlUncreatableType, location,
true,
true);
1791bool QQmlJSImportVisitor::visit(UiObjectDefinition *definition)
1793 const QString superType = buildName(definition->qualifiedTypeNameId);
1795 const bool isRoot = !rootScopeIsValid();
1796 Q_ASSERT(!superType.isEmpty());
1801 const qsizetype indexOfTypeName = superType.lastIndexOf(u'.');
1802 const bool looksLikeGroupedProperty = superType.front().isLower();
1804 if (indexOfTypeName != -1 && looksLikeGroupedProperty) {
1805 logLowerCaseImport(superType, definition->qualifiedTypeNameId->identifierToken,
1809 if (!looksLikeGroupedProperty) {
1811 enterEnvironment(QQmlSA::ScopeType::QMLScope, superType,
1812 definition->firstSourceLocation());
1814 enterRootScope(QQmlSA::ScopeType::QMLScope, superType,
1815 definition->firstSourceLocation());
1816 m_currentScope->setIsRootFileComponentFlag(
true);
1819 const QTypeRevision revision = m_currentScope->baseTypeRevision();
1820 if (
auto base = m_currentScope->baseType(); base) {
1821 if (isRoot && base->internalName() == u"QQmlComponent") {
1822 m_logger->log(u"Qml top level type cannot be 'Component'."_s, qmlTopLevelComponent,
1823 definition->qualifiedTypeNameId->identifierToken,
true,
true);
1825 if (base->isSingleton() && m_currentScope->isComposite()) {
1826 m_logger->log(u"Singleton Type %1 is not creatable."_s.arg(
1827 m_currentScope->baseTypeName()),
1828 qmlUncreatableType, definition->qualifiedTypeNameId->identifierToken,
1831 }
else if (!base->isCreatable()) {
1833 m_logger->log(u"Type %1 is not creatable."_s.arg(m_currentScope->baseTypeName()),
1834 qmlUncreatableType, definition->qualifiedTypeNameId->identifierToken,
1838 if (m_nextIsInlineComponent) {
1839 Q_ASSERT(std::holds_alternative<InlineComponentNameType>(m_currentRootName));
1840 const QString &name = std::get<InlineComponentNameType>(m_currentRootName);
1841 m_currentScope->setIsInlineComponent(
true);
1842 m_currentScope->setInlineComponentName(name);
1843 m_currentScope->setOwnModuleName(m_exportedRootScope->moduleName());
1844 m_rootScopeImports.setType(
1845 name, { m_currentScope, revision, QQmlJS::PrecedenceValues::InlineComponent });
1846 m_nextIsInlineComponent =
false;
1849 addDefaultProperties();
1850 Q_ASSERT(m_currentScope->scopeType() == QQmlSA::ScopeType::QMLScope);
1851 m_qmlTypes.append(m_currentScope);
1853 m_objectDefinitionScopes << m_currentScope;
1855 enterEnvironmentNonUnique(QQmlSA::ScopeType::GroupedPropertyScope, superType,
1856 definition->firstSourceLocation());
1857 m_bindings.append(createNonUniqueScopeBinding(m_currentScope, superType,
1858 definition->firstSourceLocation()));
1859 QQmlJSScope::resolveTypes(
1860 m_currentScope, m_rootScopeImports.contextualTypes(), &m_usedTypes);
1863 m_currentScope->setAnnotations(parseAnnotations(definition->annotations));
1868void QQmlJSImportVisitor::endVisit(UiObjectDefinition *)
1870 QQmlJSScope::resolveTypes(m_currentScope, m_rootScopeImports.contextualTypes(), &m_usedTypes);
1874bool QQmlJSImportVisitor::visit(UiInlineComponent *component)
1876 if (!std::holds_alternative<RootDocumentNameType>(m_currentRootName)) {
1877 m_logger->log(u"Nested inline components are not supported"_s, qmlSyntax,
1878 component->firstSourceLocation());
1882 const auto it = m_seenInlineComponents.constFind(component->name);
1883 if (it != m_seenInlineComponents.cend()) {
1884 m_logger->log(
"Duplicate inline component '%1'"_L1.arg(it.key()),
1885 qmlDuplicateInlineComponent, component->firstSourceLocation());
1886 m_logger->log(
"Note: previous component named '%1' here"_L1.arg(it.key()),
1887 qmlDuplicateInlineComponent, it.value(),
true,
true, {},
1888 component->firstSourceLocation().startLine);
1890 m_seenInlineComponents[component->name] = component->firstSourceLocation();
1893 m_nextIsInlineComponent =
true;
1894 m_currentRootName = component->name.toString();
1898void QQmlJSImportVisitor::endVisit(UiInlineComponent *component)
1900 m_currentRootName = RootDocumentNameType();
1901 if (m_nextIsInlineComponent) {
1902 m_logger->log(u"Inline component declaration must be followed by a typename"_s,
1903 qmlSyntax, component->firstSourceLocation());
1905 m_nextIsInlineComponent =
false;
1908bool QQmlJSImportVisitor::visit(UiPublicMember *publicMember)
1910 switch (publicMember->type) {
1911 case UiPublicMember::Signal: {
1912 const QString signalName = publicMember->name.toString();
1913 UiParameterList *param = publicMember->parameters;
1914 QQmlJSMetaMethod method;
1915 method.setMethodType(QQmlJSMetaMethodType::Signal);
1916 method.setReturnTypeName(QStringLiteral(
"void"));
1917 method.setMethodName(signalName);
1918 method.setSourceLocation(combine(publicMember->firstSourceLocation(),
1919 publicMember->lastSourceLocation()));
1921 method.addParameter(
1922 QQmlJSMetaParameter(
1923 param->name.toString(),
1924 param->type ? param->type->toString() : QString()
1926 param = param->next;
1928 m_currentScope->addOwnMethod(method);
1931 case UiPublicMember::Property: {
1932 const QString propertyName = publicMember->name.toString();
1933 QString typeName = buildName(publicMember->memberType);
1934 if (typeName.contains(u'.') && typeName.front().isLower()) {
1935 logLowerCaseImport(typeName, publicMember->typeToken, m_logger);
1939 const bool isAlias = (typeName == u"alias"_s);
1941 auto tryParseAlias = [&]() {
1943 if (!publicMember->statement) {
1944 m_logger->log(QStringLiteral(
"Invalid alias expression - an initializer is needed."),
1945 qmlSyntax, publicMember->memberType->firstSourceLocation());
1948 const auto expression = cast<ExpressionStatement *>(publicMember->statement);
1949 auto node = expression ? expression->expression :
nullptr;
1950 auto fex = cast<FieldMemberExpression *>(node);
1953 aliasExpr.prepend(u'.' + fex->name.toString());
1954 fex = cast<FieldMemberExpression *>(node);
1957 if (
const auto idExpression = cast<IdentifierExpression *>(node)) {
1958 aliasExpr.prepend(idExpression->name.toString());
1962 m_logger->log(QStringLiteral(
"Invalid alias expression. Only IDs and field "
1963 "member expressions can be aliased."),
1964 qmlSyntax, publicMember->statement->firstSourceLocation());
1969 if (m_rootScopeImports.hasType(typeName)
1970 && !m_rootScopeImports.type(typeName).scope.isNull()) {
1971 if (m_importTypeLocationMap.contains(typeName))
1972 m_usedTypes.insert(typeName);
1975 QQmlJSMetaProperty prop;
1976 prop.setPropertyName(propertyName);
1977 prop.setIsList(publicMember->typeModifier == QLatin1String(
"list"));
1978 prop.setIsWritable(!publicMember->isReadonly());
1979 prop.setIsFinal(publicMember->isFinal());
1980 prop.setIsVirtual(publicMember->isVirtual());
1981 prop.setIsOverride(publicMember->isOverride());
1982 prop.setAliasExpression(aliasExpr);
1983 prop.setSourceLocation(
1984 combine(publicMember->firstSourceLocation(), publicMember->colonToken));
1986 isAlias ? QQmlJSScope::ConstPtr() : m_rootScopeImports.type(typeName).scope;
1988 prop.setType(prop.isList() ? type->listType() : type);
1989 const QString internalName = type->internalName();
1990 prop.setTypeName(internalName.isEmpty() ? typeName : internalName);
1991 }
else if (!isAlias) {
1992 m_pendingPropertyTypes << PendingPropertyType { m_currentScope, prop.propertyName(),
1993 publicMember->firstSourceLocation() };
1994 prop.setTypeName(typeName);
1996 prop.setAnnotations(parseAnnotations(publicMember->annotations));
1997 if (publicMember->isDefaultMember())
1998 m_currentScope->setOwnDefaultPropertyName(prop.propertyName());
1999 prop.setIndex(m_currentScope->ownProperties().size());
2000 m_currentScope->insertPropertyIdentifier(prop);
2001 if (publicMember->isRequired())
2002 m_currentScope->setPropertyLocallyRequired(prop.propertyName(),
true);
2004 BindingExpressionParseResult parseResult = BindingExpressionParseResult::Invalid;
2008 parseBindingExpression(publicMember->name.toString(), publicMember->statement,
2014 if (parseResult == BindingExpressionParseResult::Script) {
2015 Q_ASSERT(!m_savedBindingOuterScope);
2016 m_savedBindingOuterScope = m_currentScope;
2017 enterEnvironment(QQmlSA::ScopeType::BindingFunctionScope, QStringLiteral(
"binding"),
2018 publicMember->statement->firstSourceLocation());
2028void QQmlJSImportVisitor::endVisit(UiPublicMember *publicMember)
2030 if (m_savedBindingOuterScope) {
2031 m_currentScope = m_savedBindingOuterScope;
2032 m_savedBindingOuterScope = {};
2034 forgetFunctionExpression(publicMember->name.toString());
2038bool QQmlJSImportVisitor::visit(UiRequired *required)
2040 const QString name = required->name.toString();
2042 m_requiredProperties << RequiredProperty { m_currentScope, name,
2043 required->firstSourceLocation() };
2045 m_currentScope->setPropertyLocallyRequired(name,
true);
2049void QQmlJSImportVisitor::visitFunctionExpressionHelper(QQmlJS::AST::FunctionExpression *fexpr)
2051 using namespace QQmlJS::AST;
2052 auto name = fexpr->name.toString();
2053 if (!name.isEmpty()) {
2054 QQmlJSMetaMethod method(name);
2055 method.setMethodType(QQmlJSMetaMethodType::Method);
2056 method.setSourceLocation(combine(fexpr->firstSourceLocation(), fexpr->lastSourceLocation()));
2058 if (!m_pendingMethodAnnotations.isEmpty()) {
2059 method.setAnnotations(m_pendingMethodAnnotations);
2060 m_pendingMethodAnnotations.clear();
2064 const bool parseTypes = m_scopesById.signaturesAreEnforced();
2066 bool formalsFullyTyped = parseTypes;
2067 bool anyFormalTyped =
false;
2068 PendingMethodTypeAnnotations pending{ m_currentScope, name, {} };
2071 for (
auto formals = fexpr->formals; formals; formals = formals->next) {
2072 PatternElement *e = formals->element;
2075 if (e->typeAnnotation && (e->bindingTarget || e->initializer))
2076 m_logger->log(
"Type annotations on default parameters are not supported"_L1,
2078 combine(e->firstSourceLocation(), e->lastSourceLocation()));
2081 if (
const auto *formals = parseTypes ? fexpr->formals :
nullptr) {
2082 const auto parameters = formals->formals();
2083 for (
const auto ¶meter : parameters) {
2084 const QString type = parameter.typeAnnotation
2085 ? parameter.typeAnnotation->type->toString()
2087 if (type.isEmpty()) {
2088 formalsFullyTyped =
false;
2089 method.addParameter(QQmlJSMetaParameter(parameter.id, QStringLiteral(
"var")));
2090 pending.locations.emplace_back();
2092 anyFormalTyped =
true;
2093 method.addParameter(QQmlJSMetaParameter(parameter.id, type));
2094 pending.locations.append(
2095 combine(parameter.typeAnnotation->firstSourceLocation(),
2096 parameter.typeAnnotation->lastSourceLocation()));
2102 method.setIsJavaScriptFunction(!formalsFullyTyped);
2108 if (parseTypes && fexpr->typeAnnotation) {
2109 method.setReturnTypeName(fexpr->typeAnnotation->type->toString());
2110 pending.locations.append(combine(fexpr->typeAnnotation->firstSourceLocation(),
2111 fexpr->typeAnnotation->lastSourceLocation()));
2112 }
else if (anyFormalTyped) {
2113 method.setReturnTypeName(QStringLiteral(
"void"));
2115 method.setReturnTypeName(QStringLiteral(
"var"));
2118 const auto &locs = pending.locations;
2119 if (std::any_of(locs.cbegin(), locs.cend(), [](
const auto &loc) {
return loc.isValid(); }))
2120 m_pendingMethodTypeAnnotations << pending;
2122 method.setJsFunctionIndex(addFunctionOrExpression(m_currentScope, method.methodName()));
2124 if (m_currentScope->scopeType() != QQmlSA::ScopeType::QMLScope) {
2126 const QQmlJS::SourceLocation functionLocation = fexpr->identifierToken.isValid()
2127 ? fexpr->identifierToken
2128 : fexpr->functionToken;
2129 safeInsertJSIdentifier(m_currentScope, name,
2130 { QQmlJSScope::JavaScriptIdentifier::LexicalScoped,
2131 functionLocation, method.returnTypeName(),
2134 m_currentScope->addOwnMethod(method);
2136 enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, name, fexpr->firstSourceLocation());
2138 addFunctionOrExpression(m_currentScope, QStringLiteral(
"<anon>"));
2139 enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, QStringLiteral(
"<anon>"),
2140 fexpr->firstSourceLocation());
2144bool QQmlJSImportVisitor::visit(QQmlJS::AST::FunctionExpression *fexpr)
2146 visitFunctionExpressionHelper(fexpr);
2150void QQmlJSImportVisitor::endVisit(QQmlJS::AST::FunctionExpression *fexpr)
2152 forgetFunctionExpression(fexpr->name.toString());
2156bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiSourceElement *srcElement)
2158 m_pendingMethodAnnotations = parseAnnotations(srcElement->annotations);
2162bool QQmlJSImportVisitor::visit(QQmlJS::AST::FunctionDeclaration *fdecl)
2164 if (!fdecl->name.isEmpty()) {
2165 const QString name = fdecl->name.toString();
2166 if (
auto previousDeclaration = m_currentScope->ownJSIdentifier(name)) {
2167 m_logger->log(
"Identifier '%1' has already been declared"_L1.arg(name), qmlSyntax,
2168 fdecl->identifierToken);
2169 m_logger->log(
"Note: previous declaration of '%1' here"_L1.arg(name), qmlSyntax,
2170 previousDeclaration->location);
2173 visitFunctionExpressionHelper(fdecl);
2177void QQmlJSImportVisitor::endVisit(QQmlJS::AST::FunctionDeclaration *fdecl)
2179 forgetFunctionExpression(fdecl->name.toString());
2183bool QQmlJSImportVisitor::visit(QQmlJS::AST::ClassExpression *ast)
2185 QQmlJSMetaProperty prop;
2186 prop.setPropertyName(ast->name.toString());
2187 m_currentScope->addOwnProperty(prop);
2188 enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, ast->name.toString(),
2189 ast->firstSourceLocation());
2193void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ClassExpression *)
2199 QQmlJS::AST::ArgumentList *args)
2201 QStringView contextString;
2202 QStringView mainString;
2203 QStringView commentString;
2204 auto registerContextString = [&](QStringView string) {
2205 contextString = string;
2208 auto registerMainString = [&](QStringView string) {
2209 mainString = string;
2212 auto registerCommentString = [&](QStringView string) {
2213 commentString = string;
2216 auto finalizeBinding = [&](QV4::CompiledData::Binding::Type type,
2217 QV4::CompiledData::TranslationData data) {
2218 if (type == QV4::CompiledData::Binding::Type_Translation) {
2219 binding.setTranslation(mainString, commentString, contextString, data.number);
2220 }
else if (type == QV4::CompiledData::Binding::Type_TranslationById) {
2221 binding.setTranslationId(mainString, data.number);
2223 binding.setStringLiteral(mainString);
2226 QmlIR::tryGeneratingTranslationBindingBase(
2228 registerMainString, registerCommentString, registerContextString, finalizeBinding);
2231QQmlJSImportVisitor::BindingExpressionParseResult
2232QQmlJSImportVisitor::parseBindingExpression(
2233 const QString &name,
const QQmlJS::AST::Statement *statement,
2234 const UiPublicMember *associatedPropertyDefinition)
2236 if (statement ==
nullptr)
2237 return BindingExpressionParseResult::Invalid;
2239 const auto *exprStatement = cast<
const ExpressionStatement *>(statement);
2241 if (exprStatement ==
nullptr) {
2242 QQmlJS::SourceLocation location = statement->firstSourceLocation();
2244 if (
const auto *block = cast<
const Block *>(statement); block && block->statements) {
2245 location = block->statements->firstSourceLocation();
2248 QQmlJSMetaPropertyBinding binding(location, name);
2249 binding.setScriptBinding(addFunctionOrExpression(m_currentScope, name),
2250 QQmlSA::ScriptBindingKind::PropertyBinding, ScriptValue_Function);
2251 m_bindings.append(UnfinishedBinding {
2253 [binding = std::move(binding)]() {
return binding; }
2255 return BindingExpressionParseResult::Script;
2258 auto expr = exprStatement->expression;
2259 QQmlJSMetaPropertyBinding binding(
2260 combine(expr->firstSourceLocation(), expr->lastSourceLocation()),
2263 ScriptBindingValueType scriptBindingValuetype = ScriptValue_Unknown;
2265 switch (expr->kind) {
2266 case Node::Kind_TrueLiteral:
2267 binding.setBoolLiteral(
true);
2269 case Node::Kind_FalseLiteral:
2270 binding.setBoolLiteral(
false);
2272 case Node::Kind_NullExpression:
2273 binding.setNullLiteral();
2275 case Node::Kind_IdentifierExpression: {
2276 auto idExpr = QQmlJS::AST::cast<QQmlJS::AST::IdentifierExpression *>(expr);
2278 if (idExpr->name == u"undefined")
2279 scriptBindingValuetype = ScriptValue_Undefined;
2282 case Node::Kind_FunctionDeclaration:
2283 case Node::Kind_FunctionExpression:
2284 case Node::Kind_Block: {
2285 scriptBindingValuetype = ScriptValue_Function;
2288 case Node::Kind_NumericLiteral:
2289 binding.setNumberLiteral(cast<NumericLiteral *>(expr)->value);
2291 case Node::Kind_StringLiteral:
2292 binding.setStringLiteral(cast<StringLiteral *>(expr)->value);
2294 case Node::Kind_RegExpLiteral:
2295 binding.setRegexpLiteral(cast<RegExpLiteral *>(expr)->pattern);
2297 case Node::Kind_TemplateLiteral: {
2298 auto templateLit = QQmlJS::AST::cast<QQmlJS::AST::TemplateLiteral *>(expr);
2299 Q_ASSERT(templateLit);
2300 if (templateLit->hasNoSubstitution) {
2301 binding.setStringLiteral(templateLit->value);
2303 binding.setScriptBinding(addFunctionOrExpression(m_currentScope, name),
2304 QQmlSA::ScriptBindingKind::PropertyBinding);
2305 for (QQmlJS::AST::TemplateLiteral *l = templateLit; l; l = l->next) {
2306 if (QQmlJS::AST::ExpressionNode *expression = l->expression)
2307 expression->accept(
this);
2313 if (QQmlJS::AST::UnaryMinusExpression *unaryMinus = QQmlJS::AST::cast<QQmlJS::AST::UnaryMinusExpression *>(expr)) {
2314 if (QQmlJS::AST::NumericLiteral *lit = QQmlJS::AST::cast<QQmlJS::AST::NumericLiteral *>(unaryMinus->expression))
2315 binding.setNumberLiteral(-lit->value);
2316 }
else if (QQmlJS::AST::CallExpression *call = QQmlJS::AST::cast<QQmlJS::AST::CallExpression *>(expr)) {
2317 if (QQmlJS::AST::IdentifierExpression *base = QQmlJS::AST::cast<QQmlJS::AST::IdentifierExpression *>(call->base))
2318 handleTranslationBinding(binding, base->name, call->arguments);
2323 if (!binding.isValid()) {
2325 binding.setScriptBinding(addFunctionOrExpression(m_currentScope, name),
2326 QQmlSA::ScriptBindingKind::PropertyBinding,
2327 scriptBindingValuetype);
2329 m_bindings.append(UnfinishedBinding { m_currentScope, [=]() {
return binding; } });
2332 if (binding.bindingType() == QQmlSA::BindingType::Translation
2333 || binding.bindingType() == QQmlSA::BindingType::TranslationById) {
2334 return BindingExpressionParseResult::Translation;
2336 if (!QQmlJSMetaPropertyBinding::isLiteralBinding(binding.bindingType()))
2337 return BindingExpressionParseResult::Script;
2339 if (associatedPropertyDefinition)
2340 handleLiteralBinding(binding, associatedPropertyDefinition);
2342 return BindingExpressionParseResult::Literal;
2345bool QQmlJSImportVisitor::isImportPrefix(QString prefix)
const
2347 if (prefix.isEmpty() || !prefix.front().isUpper())
2350 return m_rootScopeImports.isNullType(prefix);
2353void QQmlJSImportVisitor::handleIdDeclaration(QQmlJS::AST::UiScriptBinding *scriptBinding)
2355 if (m_currentScope->scopeType() != QQmlJSScope::ScopeType::QMLScope) {
2356 m_logger->log(u"id declarations are only allowed in objects"_s, qmlSyntax,
2357 scriptBinding->statement->firstSourceLocation());
2360 const auto *statement = cast<ExpressionStatement *>(scriptBinding->statement);
2362 m_logger->log(u"id must be followed by an identifier"_s, qmlSyntax,
2363 scriptBinding->statement->firstSourceLocation());
2366 const QString name = [&]() {
2367 if (
const auto *idExpression = cast<IdentifierExpression *>(statement->expression))
2368 return idExpression->name.toString();
2369 else if (
const auto *idString = cast<StringLiteral *>(statement->expression)) {
2370 m_logger->log(u"ids do not need quotation marks"_s, qmlSyntaxIdQuotation,
2371 idString->firstSourceLocation());
2372 return idString->value.toString();
2374 m_logger->log(u"Failed to parse id"_s, qmlSyntax,
2375 statement->expression->firstSourceLocation());
2379 if (!name.isEmpty() && !name.front().isLower() && name.front() != u'_') {
2380 m_logger->log(u"Id must start with a lower case letter or an '_'"_s, qmlSyntax,
2381 statement->expression->firstSourceLocation());
2384 m_currentScope->setIdSourceLocation(combine(scriptBinding->statement->firstSourceLocation(),
2385 scriptBinding->statement->lastSourceLocation()));
2386 if (m_scopesById.existsAnywhereInDocument(name)) {
2389 breakInheritanceCycles(m_currentScope);
2390 m_scopesById.possibleScopes(
2391 name, m_currentScope, Default,
2392 [&](
const QQmlJSScope::ConstPtr &otherScopeWithID,
2393 QQmlJSScopesById::Confidence confidence) {
2395 Q_UNUSED(confidence);
2397 auto otherLocation = otherScopeWithID->sourceLocation();
2401 m_logger->log(u"Found a duplicated id. id %1 was first declared at %2:%3"_s.arg(
2402 name, QString::number(otherLocation.startLine),
2403 QString::number(otherLocation.startColumn)),
2404 qmlSyntaxDuplicateIds,
2405 scriptBinding->firstSourceLocation());
2406 return QQmlJSScopesById::CallbackResult::ContinueSearch;
2409 if (!name.isEmpty())
2410 m_scopesById.insert(name, m_currentScope);
2413void QQmlJSImportVisitor::handleLiteralBinding(
const QQmlJSMetaPropertyBinding &binding,
2414 const UiPublicMember *associatedPropertyDefinition)
2418 Q_UNUSED(associatedPropertyDefinition);
2422
2423
2424
2425
2426
2429 const QQmlJS::SourceLocation &srcLocation)
2431 const auto createBinding = [=]() {
2432 const QQmlJSScope::ScopeType type = scope->scopeType();
2439 const auto propertyBindings = scope->parentScope()->ownPropertyBindings(name);
2440 const bool alreadyHasBinding =
std::any_of(propertyBindings.first, propertyBindings.second,
2441 [&](
const QQmlJSMetaPropertyBinding &binding) {
2442 return binding.bindingType() == bindingType;
2444 if (alreadyHasBinding)
2445 return QQmlJSMetaPropertyBinding(QQmlJS::SourceLocation {});
2448 if (type == QQmlSA::ScopeType::GroupedPropertyScope)
2449 binding.setGroupBinding(
static_cast<QSharedPointer<QQmlJSScope>>(scope));
2451 binding.setAttachedBinding(
static_cast<QSharedPointer<QQmlJSScope>>(scope));
2454 return { scope->parentScope(), createBinding };
2457bool QQmlJSImportVisitor::visit(UiScriptBinding *scriptBinding)
2459 Q_ASSERT(!m_savedBindingOuterScope);
2460 Q_ASSERT(!m_thisScriptBindingIsJavaScript);
2461 m_savedBindingOuterScope = m_currentScope;
2462 const auto id = scriptBinding->qualifiedId;
2463 if (!id->next && id->name == QLatin1String(
"id")) {
2464 handleIdDeclaration(scriptBinding);
2471 for (; group->next; group = group->next) {
2472 const QString name = group->name.toString();
2476 if (group == id && isImportPrefix(name)) {
2477 prefix = name + u'.';
2481 const bool isAttachedProperty = name.front().isUpper();
2482 if (isAttachedProperty) {
2484 enterEnvironmentNonUnique(QQmlSA::ScopeType::AttachedPropertyScope, prefix + name,
2485 group->firstSourceLocation());
2488 enterEnvironmentNonUnique(QQmlSA::ScopeType::GroupedPropertyScope, prefix + name,
2489 group->firstSourceLocation());
2491 m_bindings.append(createNonUniqueScopeBinding(m_currentScope, prefix + name,
2492 group->firstSourceLocation()));
2497 const auto name = group->name.toString();
2501 const auto signal = QQmlSignalNames::handlerNameToSignalName(name);
2503 if (!signal.has_value() || m_currentScope->hasProperty(name)) {
2504 m_propertyBindings[m_currentScope].append(
2505 { m_savedBindingOuterScope, group->firstSourceLocation(), name });
2507 auto result = parseBindingExpression(name, scriptBinding->statement);
2508 m_thisScriptBindingIsJavaScript = (result == BindingExpressionParseResult::Script);
2510 const auto statement = scriptBinding->statement;
2511 QStringList signalParameters;
2513 if (ExpressionStatement *expr = cast<ExpressionStatement *>(statement)) {
2514 if (FunctionExpression *func = expr->expression->asFunctionDefinition()) {
2515 for (FormalParameterList *formal = func->formals; formal; formal = formal->next)
2516 signalParameters << formal->element->bindingIdentifier.toString();
2520 QQmlJSMetaMethod scopeSignal;
2521 const auto methods = m_currentScope->methods(*signal, QQmlJSMetaMethodType::Signal);
2522 if (!methods.isEmpty())
2523 scopeSignal = methods[0];
2525 const auto firstSourceLocation = statement->firstSourceLocation();
2526 bool hasMultilineStatementBody =
2527 statement->lastSourceLocation().startLine > firstSourceLocation.startLine;
2528 m_pendingSignalHandler = firstSourceLocation;
2529 m_signalHandlers.insert(firstSourceLocation,
2530 { scopeSignal.parameterNames(), hasMultilineStatementBody });
2534 const auto index = addFunctionOrExpression(m_currentScope, name);
2535 const auto createBinding = [
2537 scope = m_currentScope,
2538 signalName = *signal,
2541 firstSourceLocation,
2542 groupLocation = group->firstSourceLocation(),
2543 signalParameters]() {
2545 Q_ASSERT(scope->isFullyResolved());
2546 QQmlSA::ScriptBindingKind kind = QQmlSA::ScriptBindingKind::Invalid;
2547 const auto methods = scope->methods(signalName, QQmlJSMetaMethodType::Signal);
2548 if (!methods.isEmpty()) {
2549 kind = QQmlSA::ScriptBindingKind::SignalHandler;
2550 checkSignal(scope, groupLocation, name, signalParameters);
2551 }
else if (QQmlJSUtils::propertyFromChangedHandler(scope, name).has_value()) {
2552 kind = QQmlSA::ScriptBindingKind::ChangeHandler;
2553 checkSignal(scope, groupLocation, name, signalParameters);
2554 }
else if (scope->hasProperty(name)) {
2557 kind = QQmlSA::ScriptBindingKind::PropertyBinding;
2558 m_signalHandlers.remove(firstSourceLocation);
2561 checkSignal(scope, groupLocation, name, signalParameters);
2564 QQmlJSMetaPropertyBinding binding(firstSourceLocation, name);
2565 binding.setScriptBinding(index, kind, ScriptValue_Function);
2568 m_bindings.append(UnfinishedBinding { m_currentScope, createBinding });
2569 m_thisScriptBindingIsJavaScript =
true;
2575 while (m_currentScope->scopeType() == QQmlSA::ScopeType::GroupedPropertyScope
2576 || m_currentScope->scopeType() == QQmlSA::ScopeType::AttachedPropertyScope) {
2581 enterEnvironment(QQmlSA::ScopeType::SignalHandlerFunctionScope,
2583 scriptBinding->statement->firstSourceLocation());
2585 enterEnvironment(QQmlSA::ScopeType::BindingFunctionScope,
2587 scriptBinding->statement->firstSourceLocation());
2593void QQmlJSImportVisitor::endVisit(UiScriptBinding *)
2595 if (m_savedBindingOuterScope) {
2596 m_currentScope = m_savedBindingOuterScope;
2597 m_savedBindingOuterScope = {};
2603 if (m_thisScriptBindingIsJavaScript) {
2604 m_thisScriptBindingIsJavaScript =
false;
2605 Q_ASSERT(!m_functionStack.isEmpty());
2606 m_functionStack.pop();
2610bool QQmlJSImportVisitor::visit(UiArrayBinding *arrayBinding)
2612 createAttachedAndGroupedScopes(arrayBinding->qualifiedId);
2613 enterEnvironment(QQmlSA::ScopeType::QMLScope, buildName(arrayBinding->qualifiedId),
2614 arrayBinding->firstSourceLocation());
2615 m_currentScope->setIsArrayScope(
true);
2619void QQmlJSImportVisitor::endVisit(UiArrayBinding *arrayBinding)
2626 const auto children = m_currentScope->childScopes();
2629 const int scopesEnteredCounter = openAttachedAndGroupedScopes(arrayBinding->qualifiedId);
2630 auto guard = qScopeGuard([
this, scopesEnteredCounter]() {
2631 for (
int i = 0; i < scopesEnteredCounter; ++i)
2635 if (checkCustomParser(m_currentScope)) {
2641 auto group = arrayBinding->qualifiedId;
2642 for (; group->next; group = group->next) { }
2643 const QString propertyName = group->name.toString();
2646 for (
auto element = arrayBinding->members; element; element = element->next, ++i) {
2647 const auto &type = children[i];
2648 if ((type->scopeType() != QQmlSA::ScopeType::QMLScope)) {
2649 m_logger->log(u"Declaring an object which is not a Qml object"
2650 " as a list member."_s, qmlSyntax, element->firstSourceLocation());
2653 m_pendingPropertyObjectBindings
2654 << PendingPropertyObjectBinding { m_currentScope, type, propertyName,
2655 element->firstSourceLocation(),
false };
2656 QQmlJSMetaPropertyBinding binding(element->firstSourceLocation(), propertyName);
2657 binding.setObject(QQmlJSUtils::getScopeName(type, QQmlSA::ScopeType::QMLScope),
2658 QQmlJSScope::ConstPtr(type));
2659 m_bindings.append(UnfinishedBinding {
2661 [binding = std::move(binding)]() {
return binding; },
2662 QQmlJSScope::ListPropertyTarget
2667bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiEnumDeclaration *uied)
2669 QQmlJSMetaEnum qmlEnum(uied->name.toString());
2670 qmlEnum.setIsQml(
true);
2671 qmlEnum.setLineNumber(uied->enumToken.startLine);
2672 for (
const auto *member = uied->members; member; member = member->next) {
2673 qmlEnum.addKey(member->member.toString());
2674 qmlEnum.addValue(
int(member->value));
2676 m_currentScope->addOwnEnumeration(qmlEnum);
2680void QQmlJSImportVisitor::addImportWithLocation(
2681 const QString &name,
const QQmlJS::SourceLocation &loc,
bool hadWarnings)
2683 if (m_importTypeLocationMap.contains(name)
2684 && m_importTypeLocationMap.values(name).contains(loc)) {
2688 m_importTypeLocationMap.insert(name, loc);
2693 if (!hadWarnings && loc.isValid())
2694 m_importLocations.insert(loc);
2697QList<QQmlJS::DiagnosticMessage> QQmlJSImportVisitor::importFromHost(
2698 const QString &path,
const QString &prefix,
const QQmlJS::SourceLocation &location)
2700 QFileInfo fileInfo(path);
2701 if (!fileInfo.exists()) {
2702 m_logger->log(
"File or directory you are trying to import does not exist: %1."_L1.arg(path),
2703 qmlImport, location);
2707 if (fileInfo.isFile()) {
2708 const auto scope = m_importer->importFile(path);
2709 const QString actualPrefix = prefix.isEmpty() ? scope->internalName() : prefix;
2710 m_rootScopeImports.setType(actualPrefix,
2711 { scope, QTypeRevision(), QQmlJS::PrecedenceValues::Default });
2712 addImportWithLocation(actualPrefix, location,
false);
2716 if (fileInfo.isDir()) {
2717 auto scopes = m_importer->importDirectory(path, QQmlJS::PrecedenceValues::Default, prefix);
2718 const auto types = scopes.types();
2719 const auto warnings = scopes.warnings();
2720 m_rootScopeImports.add(std::move(scopes));
2721 for (
auto it = types.keyBegin(), end = types.keyEnd(); it != end; it++)
2722 addImportWithLocation(*it, location, !warnings.isEmpty());
2727 "%1 is neither a file nor a directory. Are sure the import path is correct?"_L1.arg(
2729 qmlImport, location);
2733QList<QQmlJS::DiagnosticMessage> QQmlJSImportVisitor::importFromQrc(
2734 const QString &path,
const QString &prefix,
const QQmlJS::SourceLocation &location)
2736 Q_ASSERT(path.startsWith(u':'));
2737 const QQmlJSResourceFileMapper *mapper = m_importer->resourceFileMapper();
2741 const auto pathNoColon = QStringView(path).mid(1);
2742 if (mapper->isFile(pathNoColon)) {
2743 const auto entry = m_importer->resourceFileMapper()->entry(
2744 QQmlJSResourceFileMapper::resourceFileFilter(pathNoColon.toString()));
2745 const auto scope = m_importer->importFile(entry.filePath);
2746 const QString actualPrefix =
2747 prefix.isEmpty() ? QFileInfo(entry.resourcePath).baseName() : prefix;
2748 m_rootScopeImports.setType(actualPrefix,
2749 { scope, QTypeRevision(), QQmlJS::PrecedenceValues::Default });
2750 addImportWithLocation(actualPrefix, location,
false);
2754 auto scopes = m_importer->importDirectory(path, QQmlJS::PrecedenceValues::Default, prefix);
2755 const auto types = scopes.types();
2756 const auto warnings = scopes.warnings();
2757 m_rootScopeImports.add(std::move(scopes));
2758 for (
auto it = types.keyBegin(), end = types.keyEnd(); it != end; it++)
2759 addImportWithLocation(*it, location, !warnings.isEmpty());
2763bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiImport *import)
2766 QString prefix = QLatin1String(
"");
2767 if (import->asToken.isValid()) {
2768 prefix += import->importId;
2769 if (!import->importId.isEmpty() && !import->importId.front().isUpper()) {
2770 m_logger->log(u"Import qualifier '%1' must start with a capital letter."_s.arg(
2772 qmlImport, import->importIdToken,
true,
true);
2774 m_seenModuleQualifiers.append(prefix);
2777 const QString filename = import->fileName.toString();
2778 if (!filename.isEmpty()) {
2779 const QUrl url(filename);
2780 const QString scheme = url.scheme();
2781 const QQmlJS::SourceLocation importLocation = import->firstSourceLocation();
2782 if (scheme ==
""_L1) {
2783 QFileInfo fileInfo(url.path());
2784 QString absolute = fileInfo.isRelative()
2785 ? QDir::cleanPath(QDir(m_implicitImportDirectory).filePath(filename))
2787 auto warnings = absolute.startsWith(u':')
2788 ? importFromQrc(absolute, prefix, importLocation)
2789 : importFromHost(absolute, prefix, importLocation);
2790 processImportWarnings(
"path \"%1\""_L1.arg(url.path()), warnings, importLocation);
2792 }
else if (scheme ==
"file"_L1) {
2793 auto warnings = importFromHost(url.path(), prefix, importLocation);
2794 processImportWarnings(
"URL \"%1\""_L1.arg(url.path()), warnings, importLocation);
2796 }
else if (scheme ==
"qrc"_L1) {
2797 auto warnings = importFromQrc(
":"_L1 + url.path(), prefix, importLocation);
2798 processImportWarnings(
"URL \"%1\""_L1.arg(url.path()), warnings, importLocation);
2801 m_logger->log(
"Unknown import syntax. Imports can be paths, qrc urls or file urls"_L1,
2802 qmlImport, import->firstSourceLocation());
2806 const QString path = buildName(import->importUri);
2808 QStringList staticModulesProvided;
2810 auto imported = m_importer->importModule(
2811 path, QQmlJS::PrecedenceValues::Default, prefix,
2812 import->version ? import->version->version : QTypeRevision(), &staticModulesProvided);
2813 const auto types = imported.types();
2814 const auto warnings = imported.warnings();
2815 m_rootScopeImports.add(std::move(imported));
2816 for (
auto it = types.keyBegin(), end = types.keyEnd(); it != end; it++)
2817 addImportWithLocation(*it, import->firstSourceLocation(), !warnings.isEmpty());
2819 if (prefix.isEmpty()) {
2820 for (
const QString &staticModule : std::as_const(staticModulesProvided)) {
2822 if (path != staticModule && m_importStaticModuleLocationMap.contains(staticModule))
2825 m_importStaticModuleLocationMap[staticModule] = import->firstSourceLocation();
2829 processImportWarnings(
2830 QStringLiteral(
"module \"%1\"").arg(path), warnings, import->firstSourceLocation());
2834#if QT_VERSION >= QT_VERSION_CHECK(6
, 6
, 0
)
2836void handlePragmaValues(QQmlJS::AST::UiPragma *pragma, F &&assign)
2838 for (
const QQmlJS::AST::UiPragmaValueList *v = pragma->values; v; v = v->next)
2843void handlePragmaValues(QQmlJS::AST::UiPragma *pragma, F &&assign)
2845 assign(pragma->value);
2849bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiPragma *pragma)
2851 if (pragma->name == u"Strict"_s) {
2856 if (!m_logger->wasCategoryChanged(qmlCompiler))
2857 m_logger->setCategorySeverity(qmlCompiler, QQmlJS::WarningSeverity::Warning);
2858 }
else if (pragma->name == u"ComponentBehavior") {
2859 handlePragmaValues(pragma, [
this, pragma](QStringView value) {
2860 if (value == u"Bound") {
2861 m_scopesById.setComponentsAreBound(
true);
2862 }
else if (value == u"Unbound") {
2863 m_scopesById.setComponentsAreBound(
false);
2865 m_logger->log(u"Unknown argument \"%1\" to pragma ComponentBehavior"_s.arg(value),
2866 qmlSyntax, pragma->firstSourceLocation());
2869 }
else if (pragma->name == u"FunctionSignatureBehavior") {
2870 handlePragmaValues(pragma, [
this, pragma](QStringView value) {
2871 if (value == u"Enforced") {
2872 m_scopesById.setSignaturesAreEnforced(
true);
2873 }
else if (value == u"Ignored") {
2874 m_scopesById.setSignaturesAreEnforced(
false);
2877 u"Unknown argument \"%1\" to pragma FunctionSignatureBehavior"_s.arg(value),
2878 qmlSyntax, pragma->firstSourceLocation());
2881 }
else if (pragma->name == u"ValueTypeBehavior") {
2882 handlePragmaValues(pragma, [
this, pragma](QStringView value) {
2883 if (value == u"Copy") {
2885 }
else if (value == u"Reference") {
2887 }
else if (value == u"Addressable") {
2888 m_scopesById.setValueTypesAreAddressable(
true);
2889 }
else if (value == u"Inaddressable") {
2890 m_scopesById.setValueTypesAreAddressable(
false);
2891 }
else if (value == u"Assertable") {
2892 m_scopesById.setValueTypesAreAssertable(
true);
2893 }
else if (value == u"Inassertable") {
2894 m_scopesById.setValueTypesAreAssertable(
false);
2896 m_logger->log(u"Unknown argument \"%1\" to pragma ValueTypeBehavior"_s.arg(value),
2897 qmlSyntax, pragma->firstSourceLocation());
2905void QQmlJSImportVisitor::throwRecursionDepthError()
2907 m_logger->log(QStringLiteral(
"Maximum statement or expression depth exceeded"),
2908 qmlRecursionDepthErrors, QQmlJS::SourceLocation());
2911bool QQmlJSImportVisitor::visit(QQmlJS::AST::ClassDeclaration *ast)
2913 enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, ast->name.toString(),
2914 ast->firstSourceLocation());
2918void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ClassDeclaration *)
2923bool QQmlJSImportVisitor::visit(QQmlJS::AST::ForStatement *ast)
2925 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"forloop"),
2926 ast->firstSourceLocation());
2930void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ForStatement *)
2935bool QQmlJSImportVisitor::visit(QQmlJS::AST::ForEachStatement *ast)
2937 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"foreachloop"),
2938 ast->firstSourceLocation());
2942void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ForEachStatement *)
2947bool QQmlJSImportVisitor::visit(QQmlJS::AST::Block *ast)
2949 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"block"),
2950 ast->firstSourceLocation());
2952 if (m_pendingSignalHandler.isValid())
2953 flushPendingSignalParameters();
2958void QQmlJSImportVisitor::endVisit(QQmlJS::AST::Block *)
2963bool QQmlJSImportVisitor::visit(QQmlJS::AST::CaseBlock *ast)
2965 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"case"),
2966 ast->firstSourceLocation());
2970void QQmlJSImportVisitor::endVisit(QQmlJS::AST::CaseBlock *)
2975bool QQmlJSImportVisitor::visit(QQmlJS::AST::Catch *catchStatement)
2977 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"catch"),
2978 catchStatement->firstSourceLocation());
2982void QQmlJSImportVisitor::endVisit(QQmlJS::AST::Catch *)
2987bool QQmlJSImportVisitor::visit(QQmlJS::AST::WithStatement *ast)
2989 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"with"),
2990 ast->firstSourceLocation());
2992 m_logger->log(QStringLiteral(
"with statements are strongly discouraged in QML "
2993 "and might cause false positives when analysing unqualified "
2995 qmlWith, ast->firstSourceLocation());
3000void QQmlJSImportVisitor::endVisit(QQmlJS::AST::WithStatement *)
3005bool QQmlJSImportVisitor::visit(QQmlJS::AST::FormalParameterList *fpl)
3007 const auto &boundedNames = fpl->boundNames();
3008 for (
auto const &boundName : boundedNames) {
3010 std::optional<QString> typeName;
3011 if (TypeAnnotation *annotation = boundName.typeAnnotation.data())
3012 if (Type *type = annotation->type)
3013 typeName = type->toString();
3014 safeInsertJSIdentifier(m_currentScope, boundName.id,
3015 { QQmlJSScope::JavaScriptIdentifier::Parameter,
3016 boundName.location, typeName,
false });
3021void QQmlJSImportVisitor::createAttachedAndGroupedScopes(UiQualifiedId *propertyName)
3023 bool needsResolution =
false;
3024 int scopesEnteredCounter = 0;
3026 for (
auto group = propertyName; group->next; group = group->next) {
3027 const QString idName = group->name.toString();
3029 if (idName.isEmpty())
3032 if (group == propertyName && isImportPrefix(idName)) {
3033 prefix = idName + u'.';
3037 const auto scopeKind = idName.front().isUpper() ? QQmlSA::ScopeType::AttachedPropertyScope
3038 : QQmlSA::ScopeType::GroupedPropertyScope;
3041 enterEnvironmentNonUnique(scopeKind, prefix + idName, group->firstSourceLocation());
3043 m_bindings.append(createNonUniqueScopeBinding(m_currentScope, prefix + idName,
3044 group->firstSourceLocation()));
3046 ++scopesEnteredCounter;
3047 needsResolution = needsResolution || !exists;
3052 for (
int i=0; i < scopesEnteredCounter; ++i) {
3057 if (needsResolution) {
3058 QQmlJSScope::resolveTypes(
3059 m_currentScope, m_rootScopeImports.contextualTypes(), &m_usedTypes);
3063bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiObjectBinding *uiob)
3067 Q_ASSERT(uiob->qualifiedTypeNameId);
3069 const QString typeName = buildName(uiob->qualifiedTypeNameId);
3070 if (typeName.front().isLower() && typeName.contains(u'.')) {
3071 logLowerCaseImport(typeName, uiob->qualifiedTypeNameId->identifierToken, m_logger);
3074 createAttachedAndGroupedScopes(uiob->qualifiedId);
3076 enterEnvironment(QQmlSA::ScopeType::QMLScope, typeName,
3077 uiob->qualifiedTypeNameId->identifierToken);
3079 m_qmlTypes.append(m_currentScope);
3080 m_objectBindingScopes << m_currentScope;
3084int QQmlJSImportVisitor::openAttachedAndGroupedScopes(UiQualifiedId *propertyName)
3087 int scopesEnteredCounter = 0;
3088 auto group = propertyName;
3089 for (; group->next; group = group->next) {
3090 const QString idName = group->name.toString();
3092 if (idName.isEmpty())
3095 if (group == propertyName && isImportPrefix(idName)) {
3096 prefix = idName + u'.';
3100 const auto scopeKind = idName.front().isUpper() ? QQmlSA::ScopeType::AttachedPropertyScope
3101 : QQmlSA::ScopeType::GroupedPropertyScope;
3103 [[maybe_unused]]
bool exists =
3104 enterEnvironmentNonUnique(scopeKind, prefix + idName, group->firstSourceLocation());
3106 scopesEnteredCounter++;
3110 return scopesEnteredCounter;
3113void QQmlJSImportVisitor::endVisit(QQmlJS::AST::UiObjectBinding *uiob)
3115 QQmlJSScope::resolveTypes(m_currentScope, m_rootScopeImports.contextualTypes(), &m_usedTypes);
3117 const QQmlJSScope::Ptr childScope = m_currentScope;
3120 const int scopesEnteredCounter = openAttachedAndGroupedScopes(uiob->qualifiedId);
3125 auto group = uiob->qualifiedId;
3126 for (; group->next; group = group->next) { }
3127 const QString propertyName = group->name.toString();
3129 if (m_currentScope->isNameDeferred(propertyName)) {
3130 bool foundIds =
false;
3131 QList<QQmlJSScope::ConstPtr> childScopes { childScope };
3133 while (!childScopes.isEmpty()) {
3134 const QQmlJSScope::ConstPtr scope = childScopes.takeFirst();
3135 m_scopesById.possibleIds(
3136 scope, scope, Default,
3137 [&](
const QString &id, QQmlJSScopesById::Confidence confidence) {
3140 Q_UNUSED(confidence);
3142 return QQmlJSScopesById::CallbackResult::StopSearch;
3145 childScopes << scope->childScopes();
3150 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
3152 qmlDeferredPropertyId, uiob->firstSourceLocation());
3156 if (checkCustomParser(m_currentScope)) {
3160 m_pendingPropertyObjectBindings
3161 << PendingPropertyObjectBinding { m_currentScope, childScope, propertyName,
3162 uiob->firstSourceLocation(), uiob->hasOnToken };
3164 QQmlJSMetaPropertyBinding binding(uiob->firstSourceLocation(), propertyName);
3165 if (uiob->hasOnToken) {
3166 if (childScope->hasInterface(u"QQmlPropertyValueInterceptor"_s)) {
3167 binding.setInterceptor(QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope),
3168 QQmlJSScope::ConstPtr(childScope));
3170 binding.setValueSource(QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope),
3171 QQmlJSScope::ConstPtr(childScope));
3174 binding.setObject(QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope),
3175 QQmlJSScope::ConstPtr(childScope));
3177 m_bindings.append(UnfinishedBinding { m_currentScope, [=]() {
return binding; } });
3180 for (
int i = 0; i < scopesEnteredCounter; ++i)
3184bool QQmlJSImportVisitor::visit(ExportDeclaration *)
3186 Q_ASSERT(rootScopeIsValid());
3187 Q_ASSERT(m_exportedRootScope != m_globalScope);
3188 Q_ASSERT(m_currentScope == m_globalScope);
3189 m_currentScope = m_exportedRootScope;
3193void QQmlJSImportVisitor::endVisit(ExportDeclaration *)
3195 Q_ASSERT(rootScopeIsValid());
3196 m_currentScope = m_exportedRootScope->parentScope();
3197 Q_ASSERT(m_currentScope == m_globalScope);
3200bool QQmlJSImportVisitor::visit(ESModule *module)
3202 Q_ASSERT(!rootScopeIsValid());
3203 enterRootScope(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"module"),
3204 module->firstSourceLocation());
3205 m_currentScope->setIsScript(
true);
3206 importBaseModules();
3211void QQmlJSImportVisitor::endVisit(ESModule *)
3213 QQmlJSScope::resolveTypes(
3214 m_exportedRootScope, m_rootScopeImports.contextualTypes(), &m_usedTypes);
3217bool QQmlJSImportVisitor::visit(Program *program)
3219 Q_ASSERT(m_globalScope == m_currentScope);
3220 Q_ASSERT(!rootScopeIsValid());
3221 enterRootScope(QQmlSA::ScopeType::JSFunctionScope, u"script"_s, program->firstSourceLocation());
3222 m_exportedRootScope->setIsScript(
true);
3223 importBaseModules();
3227void QQmlJSImportVisitor::endVisit(Program *)
3229 QQmlJSScope::resolveTypes(
3230 m_exportedRootScope, m_rootScopeImports.contextualTypes(), &m_usedTypes);
3233void QQmlJSImportVisitor::endVisit(QQmlJS::AST::FieldMemberExpression *fieldMember)
3237 const QString name = fieldMember->name.toString();
3238 if (m_importTypeLocationMap.contains(name)) {
3239 const QQmlJSImportedScope type = m_rootScopeImports.type(name);
3240 if (type.scope.isNull()) {
3241 if (m_rootScopeImports.hasType(name))
3242 m_usedTypes.insert(name);
3243 }
else if (!type.scope->ownAttachedTypeName().isEmpty()) {
3244 m_usedTypes.insert(name);
3249bool QQmlJSImportVisitor::visit(QQmlJS::AST::IdentifierExpression *idexp)
3251 const QString name = idexp->name.toString();
3252 if (m_importTypeLocationMap.contains(name)) {
3253 m_usedTypes.insert(name);
3259bool QQmlJSImportVisitor::visit(QQmlJS::AST::PatternElement *element)
3262 if (element->isVariableDeclaration()) {
3263 QQmlJS::AST::BoundNames names;
3264 element->boundNames(&names);
3265 for (
const auto &name : std::as_const(names)) {
3266 std::optional<QString> typeName;
3267 if (TypeAnnotation *annotation = name.typeAnnotation.data())
3268 if (Type *type = annotation->type)
3269 typeName = type->toString();
3270 using Kind = QQmlJSScope::JavaScriptIdentifier::Kind;
3271 const Kind kind = (element->scope == QQmlJS::AST::VariableScope::Var)
3272 ? Kind::FunctionScoped
3273 : Kind::LexicalScoped;
3274 const QString variableName = name.id;
3275 if (kind == Kind::LexicalScoped) {
3276 const QQmlJS::SourceLocation location = element->firstSourceLocation();
3277 if (
auto previousDeclaration = m_currentScope->ownJSIdentifier(variableName)) {
3278 m_logger->log(
"Identifier '%1' has already been declared"_L1.arg(variableName), qmlSyntax,
3280 m_logger->log(
"Note: previous declaration of '%1' here"_L1.arg(variableName), qmlSyntax,
3281 previousDeclaration->location);
3284 const bool isConstVariable = element->scope == QQmlJS::AST::VariableScope::Const;
3285 const bool couldInsert = safeInsertJSIdentifier(m_currentScope,
3287 { (element->scope == QQmlJS::AST::VariableScope::Var)
3288 ? QQmlJSScope::JavaScriptIdentifier::FunctionScoped
3289 : QQmlJSScope::JavaScriptIdentifier::LexicalScoped,
3290 name.location, typeName,
3300bool QQmlJSImportVisitor::visit(IfStatement *statement)
3302 if (BinaryExpression *binary = cast<BinaryExpression *>(statement->expression)) {
3303 if (binary->op == QSOperator::Assign) {
3305 "Assignment in condition: did you mean to use \"===\" or \"==\" instead of \"=\"?"_L1,
3306 qmlAssignmentInCondition, binary->operatorToken);