150QQmlJSImportVisitor::QQmlJSImportVisitor(QQmlJSImporter *importer, QQmlJSLogger *logger,
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);
276bool QQmlJSImportVisitor::resolveAliasProperty(
const QQmlJSScope::Ptr &object,
277 const QQmlJSMetaProperty &property)
279 bool doRequeue =
false;
280 QStringList components = property.aliasExpression().split(u'.');
281 QQmlJSMetaProperty targetProperty;
283 bool foundProperty =
false;
286 QQmlJSScope::ConstPtr type = m_scopesById.scope(components.takeFirst(), object);
287 QQmlJSScope::ConstPtr typeScope;
288 if (!type.isNull()) {
289 foundProperty =
true;
296 while (type && !components.isEmpty()) {
297 const QString name = components.takeFirst();
299 if (!type->hasProperty(name)) {
300 foundProperty =
false;
305 const auto target = type->property(name);
306 if (!target.type() && target.isAlias())
309 type = target.type();
310 targetProperty = target;
318 m_logger->log(QStringLiteral(
"Cannot deduce type of alias \"%1\"")
319 .arg(property.propertyName()),
320 qmlMissingType, property.sourceLocation());
323 QStringLiteral(
"Cannot resolve alias \"%1\"").arg(property.propertyName()),
324 qmlUnresolvedAlias, property.sourceLocation());
327 Q_ASSERT(property.index() >= 0);
328 object->addOwnProperty(property);
331 QQmlJSMetaProperty newProperty = property;
332 newProperty.setType(type);
334 newProperty.setIsList(targetProperty.isList());
335 newProperty.setIsWritable(targetProperty.isWritable());
336 newProperty.setIsFinal(targetProperty.isFinal());
337 newProperty.setIsPointer(targetProperty.isPointer());
339 const bool onlyId = !property.aliasExpression().contains(u'.');
341 newProperty.setAliasTargetScope(type);
342 newProperty.setAliasTargetName(QStringLiteral(
"id-only-alias"));
344 const auto &ownerScope =
345 QQmlJSScope::ownerOfProperty(typeScope, targetProperty.propertyName()).scope;
346 newProperty.setAliasTargetScope(ownerScope);
347 newProperty.setAliasTargetName(targetProperty.propertyName());
350 if (
const QString internalName = type->internalName(); !internalName.isEmpty())
351 newProperty.setTypeName(internalName);
353 Q_ASSERT(newProperty.index() >= 0);
354 object->addOwnProperty(newProperty);
355 m_aliasDefinitions.append({ object, property.propertyName() });
360void QQmlJSImportVisitor::resolveAliases()
362 QQueue<QQmlJSScope::Ptr> objects;
363 objects.enqueue(m_exportedRootScope);
365 qsizetype lastRequeueLength = std::numeric_limits<qsizetype>::max();
366 QQueue<QQmlJSScope::Ptr> requeue;
368 while (!objects.isEmpty()) {
369 const QQmlJSScope::Ptr object = objects.dequeue();
370 const auto properties = object->ownProperties();
372 bool doRequeue =
false;
373 for (
const auto &property : properties) {
374 if (!property.isAlias() || !property.type().isNull())
376 doRequeue |= resolveAliasProperty(object, property);
379 const auto childScopes = object->childScopes();
380 for (
const auto &childScope : childScopes)
381 objects.enqueue(childScope);
384 requeue.enqueue(object);
386 if (objects.isEmpty() && requeue.size() < lastRequeueLength) {
387 lastRequeueLength = requeue.size();
388 objects.swap(requeue);
392 while (!requeue.isEmpty()) {
393 const QQmlJSScope::Ptr object = requeue.dequeue();
394 const auto properties = object->ownProperties();
395 for (
const auto &property : properties) {
396 if (!property.isAlias() || property.type())
398 m_logger->log(QStringLiteral(
"Alias \"%1\" is part of an alias cycle")
399 .arg(property.propertyName()),
400 qmlAliasCycle, property.sourceLocation());
405void QQmlJSImportVisitor::resolveGroupProperties()
407 QQueue<QQmlJSScope::Ptr> objects;
408 objects.enqueue(m_exportedRootScope);
410 while (!objects.isEmpty()) {
411 const QQmlJSScope::Ptr object = objects.dequeue();
412 const auto childScopes = object->childScopes();
413 for (
const auto &childScope : childScopes) {
414 if (mayBeUnresolvedGroupedProperty(childScope)) {
415 const QString name = childScope->internalName();
416 if (object->isNameDeferred(name)) {
417 const QQmlJSScope::ConstPtr deferred = m_scopesById.scope(name, childScope);
418 if (!deferred.isNull()) {
419 QQmlJSScope::resolveGroup(childScope, deferred,
420 m_rootScopeImports.contextualTypes(),
423 }
else if (
const QQmlJSScope::ConstPtr propType = object->property(name).type()) {
424 QQmlJSScope::resolveGroup(childScope, propType,
425 m_rootScopeImports.contextualTypes(), usedTypes());
428 objects.enqueue(childScope);
433QString QQmlJSImportVisitor::implicitImportDirectory(
const QString &localFile,
434 const QQmlJSResourceFileMapper *mapper)
437 const auto resource = mapper->entry(
438 QQmlJSResourceFileMapper::localFileFilter(localFile));
439 if (resource.isValid()) {
440 return resource.resourcePath.contains(u'/')
441 ? (u':' + resource.resourcePath.left(
442 resource.resourcePath.lastIndexOf(u'/') + 1))
443 : QStringLiteral(
":/");
447 return QFileInfo(localFile).canonicalPath() + u'/';
450void QQmlJSImportVisitor::processImportWarnings(
451 const QString &what,
const QList<QQmlJS::DiagnosticMessage> &warnings,
452 const QQmlJS::SourceLocation &srcLocation)
454 if (warnings.isEmpty())
457 QList<QQmlJS::DiagnosticMessage> importWarnings = warnings;
460 auto fileSelectorWarningsIt = std::partition(importWarnings.begin(), importWarnings.end(),
461 [](
const QQmlJS::DiagnosticMessage &message) {
462 return message.type != QtMsgType::QtInfoMsg;
464 if (fileSelectorWarningsIt != importWarnings.end()) {
465 m_logger->log(QStringLiteral(
"Warnings occurred while importing %1:").arg(what), qmlImportFileSelector,
467 m_logger->processMessages(QSpan(fileSelectorWarningsIt, importWarnings.end()),
468 qmlImportFileSelector, srcLocation);
471 if (fileSelectorWarningsIt == importWarnings.begin())
474 m_logger->log(QStringLiteral(
"Warnings occurred while importing %1:").arg(what), qmlImport,
476 m_logger->processMessages(QSpan(importWarnings.begin(), fileSelectorWarningsIt), qmlImport,
480void QQmlJSImportVisitor::importBaseModules()
482 Q_ASSERT(m_rootScopeImports.isEmpty());
483 m_rootScopeImports = m_importer->importHardCodedBuiltins();
485
486
487
488
489
490 m_rootScopeImports.setCurrentFileSelector(
491 QQmlJSUtils::fileSelectorFor(m_exportedRootScope));
493 const QQmlJS::SourceLocation invalidLoc;
494 const auto types = m_rootScopeImports.types();
495 for (
auto it = types.keyBegin(), end = types.keyEnd(); it != end; it++)
496 addImportWithLocation(*it, invalidLoc,
false);
498 if (!m_qmldirFiles.isEmpty())
499 m_rootScopeImports.addWarnings(m_importer->importQmldirs(m_qmldirFiles));
503 if (!m_logger->filePath().endsWith(u".qmltypes"_s)) {
504 auto precedence = quint8(QQmlJS::PrecedenceValues::ImplicitImport);
505 m_rootScopeImports.add(m_importer->importDirectory(m_implicitImportDirectory, precedence));
510 if (
const QQmlJSResourceFileMapper *mapper = m_importer->resourceFileMapper()) {
511 const QStringList resourcePaths = mapper->resourcePaths(QQmlJSResourceFileMapper::Filter {
512 m_logger->filePath(), QStringList(), QQmlJSResourceFileMapper::Resource });
513 for (
const QString &path : resourcePaths) {
514 const qsizetype lastSlash = path.lastIndexOf(QLatin1Char(
'/'));
517 auto precedence = quint8(QQmlJS::PrecedenceValues::ImplicitImport);
518 m_rootScopeImports.add(m_importer->importDirectory(path.first(lastSlash),
524 processImportWarnings(QStringLiteral(
"base modules"), m_rootScopeImports.warnings());
527bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiProgram *)
531 if (
auto elementName = QFileInfo(m_logger->filePath()).baseName();
532 !elementName.isEmpty() && elementName[0].isUpper()) {
533 auto precedence = quint8(QQmlJS::PrecedenceValues::ImplicitImport);
534 m_rootScopeImports.setType(elementName,
535 { m_exportedRootScope, QTypeRevision{ }, precedence });
541void QQmlJSImportVisitor::endVisit(UiProgram *)
543 for (
const auto &scope : std::as_const(m_objectBindingScopes)) {
544 breakInheritanceCycles(scope);
545 checkDeprecation(scope);
546 checkForComponentTypeWithProperties(scope);
549 for (
const auto &scope : std::as_const(m_objectDefinitionScopes)) {
550 if (m_pendingDefaultProperties.contains(scope))
552 breakInheritanceCycles(scope);
553 checkDeprecation(scope);
554 checkForComponentTypeWithProperties(scope);
557 const auto &keys = m_pendingDefaultProperties.keys();
558 for (
const auto &scope : keys) {
559 breakInheritanceCycles(scope);
560 checkDeprecation(scope);
561 checkForComponentTypeWithProperties(scope);
565 resolveGroupProperties();
567 for (
const auto &scope : std::as_const(m_objectDefinitionScopes))
568 checkGroupedAndAttachedScopes(scope);
571 processDefaultProperties();
572 processPropertyTypes();
573 processMethodTypes();
574 processPropertyBindings();
575 processPropertyBindingObjects();
576 checkRequiredProperties();
578 populateRuntimeFunctionIndicesForDocument();
583 ExpressionStatement *expr = cast<ExpressionStatement *>(statement);
585 if (!statement || !expr->expression)
588 switch (expr->expression->kind) {
589 case Node::Kind_StringLiteral:
590 return cast<StringLiteral *>(expr->expression)->value.toString();
591 case Node::Kind_NumericLiteral:
592 return cast<NumericLiteral *>(expr->expression)->value;
598QList<QQmlJSAnnotation> QQmlJSImportVisitor::parseAnnotations(QQmlJS::AST::UiAnnotationList *list)
601 QList<QQmlJSAnnotation> annotationList;
603 for (UiAnnotationList *item = list; item !=
nullptr; item = item->next) {
604 UiAnnotation *annotation = item->annotation;
606 QQmlJSAnnotation qqmljsAnnotation;
607 qqmljsAnnotation.name = buildName(annotation->qualifiedTypeNameId);
609 for (UiObjectMemberList *memberItem = annotation->initializer->members; memberItem !=
nullptr; memberItem = memberItem->next) {
610 switch (memberItem->member->kind) {
611 case Node::Kind_UiScriptBinding: {
612 auto *scriptBinding = QQmlJS::AST::cast<UiScriptBinding*>(memberItem->member);
613 qqmljsAnnotation.bindings[buildName(scriptBinding->qualifiedId)]
614 = bindingToVariant(scriptBinding->statement);
623 annotationList.append(qqmljsAnnotation);
626 return annotationList;
629void QQmlJSImportVisitor::setAllBindings()
631 using Key = std::pair<QQmlJSScope::ConstPtr, QString>;
632 QHash<Key, QQmlJS::SourceLocation> foundBindings;
634 for (
auto it = m_bindings.cbegin(); it != m_bindings.cend(); ++it) {
636 const QQmlJSScope::Ptr type = it->owner;
637 if (!checkTypeResolved(type))
646 if (!type->isFullyResolved())
648 auto binding = it->create();
649 if (!binding.isValid())
651 type->addOwnPropertyBinding(binding, it->specifier);
654 if (binding.hasInterceptor() || binding.hasValueSource())
656 const QString propertyName = binding.propertyName();
657 QQmlJSMetaProperty property = type->property(propertyName);
660
661
662
663
664
665 if (!property.isValid())
669 if (property.isList())
672 const Key key = std::make_pair(type, propertyName);
673 auto sourceLocationIt = foundBindings.constFind(key);
674 if (sourceLocationIt == foundBindings.constEnd()) {
675 foundBindings.insert(key, binding.sourceLocation());
679 const QQmlJS::SourceLocation location = binding.sourceLocation();
680 m_logger->log(
"Duplicate binding on property '%1'"_L1.arg(propertyName),
681 qmlDuplicatePropertyBinding, location);
682 m_logger->log(
"Note: previous binding on '%1' here"_L1.arg(propertyName),
683 qmlDuplicatePropertyBinding, *sourceLocationIt,
true,
true, {},
688void QQmlJSImportVisitor::processDefaultProperties()
690 for (
auto it = m_pendingDefaultProperties.constBegin();
691 it != m_pendingDefaultProperties.constEnd(); ++it) {
692 QQmlJSScope::ConstPtr parentScope = it.key();
695 if (checkCustomParser(parentScope))
698 if (!checkTypeResolved(parentScope))
702
703
704
705
706
707
708
709
710
712 parentScope = parentScope->baseType();
714 const QString defaultPropertyName =
715 parentScope ? parentScope->defaultPropertyName() : QString();
717 if (defaultPropertyName.isEmpty()) {
720 bool isComponent =
false;
721 for (QQmlJSScope::ConstPtr s = parentScope; s; s = s->baseType()) {
722 if (s->internalName() == QStringLiteral(
"QQmlComponent")) {
728 if (!isComponent && checkTypeResolved(parentScope)) {
729 m_logger->log(QStringLiteral(
"Cannot assign to non-existent default property"),
730 qmlMissingProperty, it.value().constFirst()->sourceLocation());
736 const QQmlJSMetaProperty defaultProp = parentScope->property(defaultPropertyName);
737 auto propType = defaultProp.type();
738 const auto handleUnresolvedDefaultProperty = [&](
const QQmlJSScope::ConstPtr &) {
740 m_logger->log(QStringLiteral(
"Property \"%1\" has incomplete type \"%2\". You may be "
741 "missing an import.")
742 .arg(defaultPropertyName)
743 .arg(defaultProp.typeName()),
744 qmlUnresolvedType, it.value().constFirst()->sourceLocation());
747 const auto assignToUnknownProperty = [&]() {
750 for (
const QQmlJSScope::Ptr &scope : std::as_const(*it))
751 scope->setAssignedToUnknownProperty(
true);
754 if (propType.isNull()) {
755 handleUnresolvedDefaultProperty(propType);
756 assignToUnknownProperty();
760 if (it.value().size() > 1
761 && !defaultProp.isList()
762 && !propType->isListProperty()) {
764 QStringLiteral(
"Cannot assign multiple objects to a default non-list property"),
765 qmlNonListProperty, it.value().constFirst()->sourceLocation());
768 if (!checkTypeResolved(propType, handleUnresolvedDefaultProperty)) {
769 assignToUnknownProperty();
773 for (
const QQmlJSScope::Ptr &scope : std::as_const(*it)) {
774 if (!checkTypeResolved(scope))
779 if (propType->canAssign(scope)) {
780 scope->setIsWrappedInImplicitComponent(
781 causesImplicitComponentWrapping(defaultProp, scope));
785 m_logger->log(QStringLiteral(
"Cannot assign to default property of incompatible type"),
786 qmlIncompatibleType, scope->sourceLocation());
791void QQmlJSImportVisitor::processPropertyTypes()
793 for (
const PendingPropertyType &type : std::as_const(m_pendingPropertyTypes)) {
794 Q_ASSERT(type.scope->hasOwnProperty(type.name));
796 auto property = type.scope->ownProperty(type.name);
798 if (
const auto propertyType = QQmlJSScope::findType(
799 property.typeName(), m_rootScopeImports.contextualTypes()).scope) {
800 property.setType(property.isList() ? propertyType->listType() : propertyType);
801 type.scope->addOwnProperty(property);
803 QString msg = property.typeName() +
' '_L1 + wasNotFound +
' '_L1 + didYouAddAllImports;
804 if (property.typeName() ==
"list"_L1)
805 msg +=
" list is not a type. It requires an element type argument (eg. list<int>)"_L1;
806 m_logger->log(msg, qmlImport, type.location);
811void QQmlJSImportVisitor::processMethodTypes()
813 const auto isEnumUsedAsType = [&](QStringView typeName,
const QQmlJS::SourceLocation &loc) {
814 if (typeName ==
"enum"_L1) {
818 const auto split = typeName.tokenize(u'.').toContainer<QVarLengthArray<QStringView, 4>>();
819 if (split.size() != 2)
822 const QStringView scopeName = split[0];
823 const QStringView enumName = split[1];
825 if (
auto scope = QQmlJSScope::findType(scopeName.toString(),
826 m_rootScopeImports.contextualTypes()).scope) {
827 if (scope->enumeration(enumName.toString()).isValid()) {
829 "QML enumerations are not types. Use int, or use double if the enum's underlying type does not fit into int."_L1,
830 qmlEnumsAreNotTypes, loc);
837 for (
const auto &method : std::as_const(m_pendingMethodTypeAnnotations)) {
838 for (
auto [it, end] = method.scope->mutableOwnMethodsRange(method.methodName); it != end; ++it) {
839 const auto [parameterBegin, parameterEnd] = it->mutableParametersRange();
840 for (
auto parameter = parameterBegin; parameter != parameterEnd; ++parameter) {
841 const int parameterIndex = parameter - parameterBegin;
842 if (isEnumUsedAsType(parameter->typeName(), method.locations[parameterIndex]))
844 if (
const auto parameterType = QQmlJSScope::findType(
845 parameter->typeName(), m_rootScopeImports.contextualTypes()).scope) {
846 parameter->setType({ parameterType });
849 u"\"%1\" was not found for the type of parameter \"%2\" in method \"%3\"."_s
850 .arg(parameter->typeName(), parameter->name(), it->methodName()),
851 qmlUnresolvedType, method.locations[parameter - parameterBegin]);
855 if (isEnumUsedAsType(it->returnTypeName(), method.locations.last()))
857 if (
const auto returnType = QQmlJSScope::findType(
858 it->returnTypeName(), m_rootScopeImports.contextualTypes()).scope) {
859 it->setReturnType({ returnType });
861 m_logger->log(u"\"%1\" was not found for the return type of method \"%2\"."_s.arg(
862 it->returnTypeName(), it->methodName()),
863 qmlUnresolvedType, method.locations.last());
871
872
873
874
875
876
877
881 for (QStringView propertyName: possiblyGroupedProperty.tokenize(u".")) {
882 property = scope->property(propertyName.toString());
883 if (property.isValid())
884 scope = property.type();
891void QQmlJSImportVisitor::processPropertyBindingObjects()
893 QSet<std::pair<QQmlJSScope::Ptr, QString>> foundLiterals;
901 QSet<std::pair<QQmlJSScope::Ptr, QString>> visited;
902 for (
const PendingPropertyObjectBinding &objectBinding :
903 std::as_const(m_pendingPropertyObjectBindings)) {
905 const auto uniqueBindingId = std::make_pair(objectBinding.scope, objectBinding.name);
906 if (visited.contains(uniqueBindingId))
908 visited.insert(uniqueBindingId);
910 auto [existingBindingsBegin, existingBindingsEnd] =
911 uniqueBindingId.first->ownPropertyBindings(uniqueBindingId.second);
912 const bool hasLiteralBindings =
913 std::any_of(existingBindingsBegin, existingBindingsEnd,
914 [](
const QQmlJSMetaPropertyBinding &x) {
return x.hasLiteral(); });
915 if (hasLiteralBindings)
916 foundLiterals.insert(uniqueBindingId);
920 QSet<std::pair<QQmlJSScope::Ptr, QString>> foundObjects;
921 QSet<std::pair<QQmlJSScope::Ptr, QString>> foundInterceptors;
922 QSet<std::pair<QQmlJSScope::Ptr, QString>> foundValueSources;
924 for (
const PendingPropertyObjectBinding &objectBinding :
925 std::as_const(m_pendingPropertyObjectBindings)) {
926 const QString propertyName = objectBinding.name;
927 QQmlJSScope::Ptr childScope = objectBinding.childScope;
929 const auto assignToUnknownProperty = [&]() {
932 childScope->setAssignedToUnknownProperty(
true);
936 if (!checkTypeResolved(objectBinding.scope)) {
937 assignToUnknownProperty();
941 QQmlJSMetaProperty property = resolveProperty(propertyName, objectBinding.scope);
943 if (!property.isValid()) {
944 warnMissingPropertyForBinding(propertyName, objectBinding.location);
947 const auto handleUnresolvedProperty = [&](
const QQmlJSScope::ConstPtr &) {
949 m_logger->log(QStringLiteral(
"Property \"%1\" has incomplete type \"%2\". You may be "
950 "missing an import.")
952 .arg(property.typeName()),
953 qmlUnresolvedType, objectBinding.location);
956 if (property.type().isNull()) {
957 assignToUnknownProperty();
958 handleUnresolvedProperty(property.type());
963 if (!checkTypeResolved(property.type(), handleUnresolvedProperty)) {
964 assignToUnknownProperty();
966 }
else if (!checkTypeResolved(childScope)) {
970 if (!objectBinding.onToken && !property.type()->canAssign(childScope)) {
971 m_logger->log(QStringLiteral(
"Cannot assign object of type %1 to %2")
972 .arg(QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope))
973 .arg(property.typeName()),
974 qmlIncompatibleType, childScope->sourceLocation());
978 childScope->setIsWrappedInImplicitComponent(
979 causesImplicitComponentWrapping(property, childScope));
982 const auto uniqueBindingId = std::make_pair(objectBinding.scope, objectBinding.name);
983 const QString typeName = QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope);
985 auto isConditionalBinding = [&]() ->
bool {
987
988
989
990
991 return childScope->hasOwnPropertyBindings(u"enabled"_s)
992 || childScope->hasOwnPropertyBindings(u"when"_s)
993 || childScope->hasOwnPropertyBindings(u"running"_s);
996 if (objectBinding.onToken) {
997 if (childScope->hasInterface(QStringLiteral(
"QQmlPropertyValueInterceptor"))) {
998 if (foundInterceptors.contains(uniqueBindingId)) {
999 if (!isConditionalBinding()) {
1000 m_logger->log(QStringLiteral(
"Duplicate interceptor on property \"%1\"")
1002 qmlDuplicatePropertyBinding, objectBinding.location);
1005 foundInterceptors.insert(uniqueBindingId);
1007 }
else if (childScope->hasInterface(QStringLiteral(
"QQmlPropertyValueSource"))) {
1008 if (foundValueSources.contains(uniqueBindingId)) {
1009 if (!isConditionalBinding()) {
1010 m_logger->log(QStringLiteral(
"Duplicate value source on property \"%1\"")
1012 qmlDuplicatePropertyBinding, objectBinding.location);
1014 }
else if (foundObjects.contains(uniqueBindingId)
1015 || foundLiterals.contains(uniqueBindingId)) {
1016 if (!isConditionalBinding()) {
1017 m_logger->log(QStringLiteral(
"Cannot combine value source and binding on "
1020 qmlDuplicatePropertyBinding, objectBinding.location);
1023 foundValueSources.insert(uniqueBindingId);
1026 m_logger->log(QStringLiteral(
"On-binding for property \"%1\" has wrong type \"%2\"")
1029 qmlIncompatibleType, objectBinding.location);
1032 if (foundValueSources.contains(uniqueBindingId)) {
1033 if (!isConditionalBinding()) {
1035 QStringLiteral(
"Cannot combine value source and binding on property \"%1\"")
1037 qmlDuplicatePropertyBinding, objectBinding.location);
1040 foundObjects.insert(uniqueBindingId);
1048 QList<QQmlJSScope::ConstPtr> descendants;
1049 std::vector<QQmlJSScope::ConstPtr> toVisit;
1051 toVisit.push_back(scope);
1052 while (!toVisit.empty()) {
1053 const QQmlJSScope::ConstPtr s = toVisit.back();
1059 toVisit.insert(toVisit.end(), s->childScopesBegin(), s->childScopesEnd());
1066void QQmlJSImportVisitor::populatePropertyAliases()
1068 for (
const auto &alias : std::as_const(m_aliasDefinitions)) {
1069 const auto &[aliasScope, aliasName] = alias;
1070 if (aliasScope.isNull())
1073 auto property = aliasScope->ownProperty(aliasName);
1074 if (!property.isValid() || !property.aliasTargetScope())
1077 Property target(property.aliasTargetScope(), property.aliasTargetName());
1080 m_propertyAliases[target].append(alias);
1081 property = target.scope->property(target.name);
1082 target = Property(property.aliasTargetScope(), property.aliasTargetName());
1083 }
while (property.isAlias());
1087void QQmlJSImportVisitor::checkRequiredProperties()
1089 for (
const auto &required : std::as_const(m_requiredProperties)) {
1090 if (!required.scope->hasProperty(required.name)) {
1092 QStringLiteral(
"Property \"%1\" was marked as required but does not exist.")
1093 .arg(required.name),
1094 qmlRequired, required.location);
1098 const auto compType = m_rootScopeImports.type(u"Component"_s).scope;
1099 const auto isComponentRoot = [&](
const QQmlJSScope::ConstPtr &requiredScope) {
1100 if (requiredScope->isWrappedInImplicitComponent())
1102 if (
const auto s = requiredScope->parentScope(); s && s->baseType() == compType)
1107 const auto scopeRequiresProperty = [&](
const QQmlJSScope::ConstPtr &requiredScope,
1108 const QString &propName,
1109 const QQmlJSScope::ConstPtr &descendant) {
1110 if (!requiredScope->isPropertyLocallyRequired(propName))
1114 return QQmlJSScope::ownerOfProperty(requiredScope, propName).scope
1115 == QQmlJSScope::ownerOfProperty(descendant, propName).scope;
1118 const auto requiredHasBinding = [](
const QList<QQmlJSScope::ConstPtr> &scopesToSearch,
1119 const QQmlJSScope::ConstPtr &owner,
1120 const QString &propName) {
1121 for (
const auto &scope : scopesToSearch) {
1122 if (scope->property(propName).isAlias())
1124 const auto &[begin, end] = scope->ownPropertyBindings(propName);
1125 for (
auto it = begin; it != end; ++it) {
1127 const bool isRelevantBinding = QQmlSA::isRegularBindingType(it->bindingType())
1128 || it->bindingType() == QQmlSA::BindingType::Interceptor
1129 || it->bindingType() == QQmlSA::BindingType::ValueSource;
1130 if (!isRelevantBinding)
1132 if (QQmlJSScope::ownerOfProperty(scope, propName).scope == owner)
1140 const auto requiredUsedInRootAlias = [&](
const QQmlJSScope::ConstPtr &requiredScope,
1141 const QString &propName) {
1142 const Property target(requiredScope, propName);
1145 const auto allAliasesToTargetIt = m_propertyAliases.constFind(target);
1146 if (allAliasesToTargetIt == m_propertyAliases.constEnd())
1153 allAliasesToTargetIt->constBegin(), allAliasesToTargetIt->constEnd(),
1154 [](
const Property &property) {
return property.scope->isFileRootComponent(); });
1157 const auto requiredSetThroughAlias = [&](
const QList<QQmlJSScope::ConstPtr> &scopesToSearch,
1158 const QQmlJSScope::ConstPtr &requiredScope,
1159 const QString &propName) {
1160 const auto &propertyDefScope = QQmlJSScope::ownerOfProperty(requiredScope, propName);
1161 const auto &propertyAliases = m_propertyAliases[{ propertyDefScope.scope, propName }];
1162 for (
const auto &alias : propertyAliases) {
1163 for (
const auto &s : scopesToSearch) {
1164 if (s->hasOwnPropertyBindings(alias.name))
1171 const auto warn = [
this](
const QQmlJSScope::ConstPtr &prevRequiredScope,
1172 const QString &propName,
const QQmlJSScope::ConstPtr &defScope,
1173 const QQmlJSScope::ConstPtr &requiredScope,
1174 const QQmlJSScope::ConstPtr &descendant) {
1175 const auto &propertyScope = QQmlJSScope::ownerOfProperty(requiredScope, propName).scope;
1176 const QString propertyScopeName = !propertyScope.isNull()
1177 ? QQmlJSUtils::getScopeName(propertyScope, QQmlSA::ScopeType::QMLScope)
1180 std::optional<QQmlJSFixSuggestion> suggestion;
1182 QString message = QStringLiteral(
"Component is missing required property %1 from %2")
1184 .arg(propertyScopeName);
1185 if (requiredScope != descendant) {
1186 const QString requiredScopeName = prevRequiredScope
1187 ? QQmlJSUtils::getScopeName(prevRequiredScope, QQmlSA::ScopeType::QMLScope)
1190 if (!prevRequiredScope.isNull()) {
1191 if (
auto sourceScope = prevRequiredScope->baseType()) {
1192 suggestion = QQmlJSFixSuggestion{
1193 "%1:%2:%3: Property marked as required in %4."_L1
1194 .arg(sourceScope->filePath())
1195 .arg(sourceScope->sourceLocation().startLine)
1196 .arg(sourceScope->sourceLocation().startColumn)
1197 .arg(requiredScopeName),
1198 sourceScope->sourceLocation()
1202 if (sourceScope->isComposite())
1203 suggestion->setFilename(sourceScope->filePath());
1206 message +=
" (marked as required by %1)"_L1.arg(requiredScopeName);
1210 m_logger->log(message, qmlRequired, defScope->sourceLocation(),
true,
true, suggestion);
1213 populatePropertyAliases();
1215 for (
const auto &[_, defScope] : m_scopesByIrLocation.asKeyValueRange()) {
1216 if (defScope->isFileRootComponent() || defScope->isInlineComponent()
1217 || defScope->componentRootStatus() != QQmlJSScope::IsComponentRoot::No
1218 || defScope->scopeType() != QQmlSA::ScopeType::QMLScope) {
1222 QList<QQmlJSScope::ConstPtr> scopesToSearch;
1223 for (QQmlJSScope::ConstPtr scope = defScope; scope; scope = scope->baseType()) {
1224 const auto descendants = QList<QQmlJSScope::ConstPtr>()
1225 << scope << qmlScopeDescendants(scope);
1226 for (
const QQmlJSScope::ConstPtr &descendant : std::as_const(descendants)) {
1229 if (descendant != scope && descendant->isInlineComponent())
1231 scopesToSearch << descendant;
1232 const auto ownProperties = descendant->ownProperties();
1233 for (
auto propertyIt = ownProperties.constBegin();
1234 propertyIt != ownProperties.constEnd(); ++propertyIt) {
1235 const QString propName = propertyIt.key();
1236 if (descendant->hasOwnPropertyBindings(propName))
1239 QQmlJSScope::ConstPtr prevRequiredScope;
1240 for (
const QQmlJSScope::ConstPtr &requiredScope : std::as_const(scopesToSearch)) {
1243 if (isComponentRoot(requiredScope))
1246 if (!scopeRequiresProperty(requiredScope, propName, descendant)) {
1247 prevRequiredScope = requiredScope;
1251 if (requiredHasBinding(scopesToSearch, descendant, propName))
1254 if (requiredUsedInRootAlias(requiredScope, propName))
1257 if (requiredSetThroughAlias(scopesToSearch, requiredScope, propName))
1260 warn(prevRequiredScope, propName, defScope, requiredScope, descendant);
1261 prevRequiredScope = requiredScope;
1269void QQmlJSImportVisitor::processPropertyBindings()
1271 for (
auto it = m_propertyBindings.constBegin(); it != m_propertyBindings.constEnd(); ++it) {
1272 QQmlJSScope::Ptr scope = it.key();
1273 for (
auto &[visibilityScope, location, name] : it.value()) {
1274 if (!scope->hasProperty(name) && !m_logger->isDisabled()) {
1278 if (checkCustomParser(scope))
1282 std::optional<QQmlJSFixSuggestion> fixSuggestion;
1284 for (QQmlJSScope::ConstPtr baseScope = scope; !baseScope.isNull();
1285 baseScope = baseScope->baseType()) {
1286 if (
auto suggestion = QQmlJSUtils::didYouMean(
1287 name, baseScope->ownProperties().keys(), m_logger->filePath(), location);
1288 suggestion.has_value()) {
1289 fixSuggestion = suggestion;
1294 if (checkTypeResolved(scope))
1295 warnMissingPropertyForBinding(name, location, fixSuggestion);
1299 const auto property = scope->property(name);
1300 if (!property.type()) {
1301 m_logger->log(QStringLiteral(
"No type found for property \"%1\". This may be due "
1302 "to a missing import statement or incomplete "
1305 qmlMissingType, location);
1308 const auto &annotations = property.annotations();
1310 const auto deprecationAnn =
1311 std::find_if(annotations.cbegin(), annotations.cend(),
1312 [](
const QQmlJSAnnotation &ann) {
return ann.isDeprecation(); });
1314 if (deprecationAnn != annotations.cend()) {
1315 const auto deprecation = deprecationAnn->deprecation();
1317 QString message = QStringLiteral(
"Binding on deprecated property \"%1\"")
1318 .arg(property.propertyName());
1320 if (!deprecation.reason.isEmpty())
1321 message.append(QStringLiteral(
" (Reason: %1)").arg(deprecation.reason));
1323 m_logger->log(message, qmlDeprecated, location);
1329void QQmlJSImportVisitor::checkSignal(
1330 const QQmlJSScope::ConstPtr &signalScope,
const QQmlJS::SourceLocation &location,
1331 const QString &handlerName,
const QStringList &handlerParameters)
1333 const auto signal = QQmlSignalNames::handlerNameToSignalName(handlerName);
1335 std::optional<QQmlJSMetaMethod> signalMethod;
1336 const auto setSignalMethod = [&](
const QQmlJSScope::ConstPtr &scope,
const QString &name) {
1337 const auto methods = scope->methods(name, QQmlJSMetaMethodType::Signal);
1338 if (!methods.isEmpty())
1339 signalMethod = methods[0];
1342 if (signal.has_value()) {
1343 if (signalScope->hasMethod(*signal)) {
1344 setSignalMethod(signalScope, *signal);
1345 }
else if (
auto p = QQmlJSUtils::propertyFromChangedHandler(signalScope, handlerName)) {
1350 if (
auto notify = p->notify(); !notify.isEmpty()) {
1351 setSignalMethod(signalScope, notify);
1353 Q_ASSERT(!p->bindable().isEmpty());
1354 signalMethod = QQmlJSMetaMethod {};
1359 if (!signalMethod.has_value()) {
1364 if (signalScope->baseTypeName() == QStringLiteral(
"Connections")) {
1366 u"Implicitly defining \"%1\" as signal handler in Connections is deprecated. "
1367 u"Create a function instead: \"function %2(%3) { ... }\"."_s.arg(
1368 handlerName, handlerName, handlerParameters.join(u", ")),
1369 qmlUnqualified, location,
true,
true);
1373 auto baseType = QQmlJSScope::nonCompositeBaseType(signalScope);
1374 if (baseType && baseType->hasCustomParser())
1378 QStringLiteral(
"no matching signal found for handler \"%1\"").arg(handlerName),
1379 qmlUnqualified, location,
true,
true);
1383 const auto signalParameters = signalMethod->parameters();
1384 QHash<QString, qsizetype> parameterNameIndexes;
1386 for (
int i = 0, end = signalParameters.size(); i < end; i++) {
1387 auto &p = signalParameters[i];
1388 parameterNameIndexes[p.name()] = i;
1390 auto signalName = [&]() {
1392 return u" called %1"_s.arg(*signal);
1395 auto type = p.type();
1398 "Type %1 of parameter %2 in signal%3 was not found, but is required to compile "
1400 p.typeName(), p.name(), signalName(),
1401 handlerName, didYouAddAllImports),
1402 qmlSignalParameters, location);
1406 if (type->isComposite())
1414 auto parameterName = [&]() {
1415 if (p.name().isEmpty())
1417 return u" called %1"_s.arg(p.name());
1419 switch (type->accessSemantics()) {
1420 case QQmlJSScope::AccessSemantics::Reference:
1422 m_logger->log(QStringLiteral(
"Type %1 of parameter%2 in signal%3 should be "
1423 "passed by pointer to be able to compile %4. ")
1424 .arg(p.typeName(), parameterName(), signalName(),
1426 qmlSignalParameters, location);
1428 case QQmlJSScope::AccessSemantics::Value:
1429 case QQmlJSScope::AccessSemantics::Sequence:
1433 "Type %1 of parameter%2 in signal%3 should be passed by "
1434 "value or const reference to be able to compile %4. ")
1435 .arg(p.typeName(), parameterName(), signalName(),
1437 qmlSignalParameters, location);
1439 case QQmlJSScope::AccessSemantics::None:
1441 QStringLiteral(
"Type %1 of parameter%2 in signal%3 required by the "
1442 "compilation of %4 cannot be used. ")
1443 .arg(p.typeName(), parameterName(), signalName(), handlerName),
1444 qmlSignalParameters, location);
1449 if (handlerParameters.size() > signalParameters.size()) {
1450 m_logger->log(QStringLiteral(
"Signal handler for \"%2\" has more formal"
1451 " parameters than the signal it handles.")
1453 qmlSignalParameters, location);
1457 for (qsizetype i = 0, end = handlerParameters.size(); i < end; i++) {
1458 const QStringView handlerParameter = handlerParameters.at(i);
1459 auto it = parameterNameIndexes.constFind(handlerParameter.toString());
1460 if (it == parameterNameIndexes.constEnd())
1462 const qsizetype j = *it;
1467 m_logger->log(QStringLiteral(
"Parameter %1 to signal handler for \"%2\""
1468 " is called \"%3\". The signal has a parameter"
1469 " of the same name in position %4.")
1471 .arg(handlerName, handlerParameter)
1473 qmlSignalParameters, location);
1477void QQmlJSImportVisitor::addDefaultProperties()
1479 QQmlJSScope::ConstPtr parentScope = m_currentScope->parentScope();
1480 if (m_currentScope == m_exportedRootScope || parentScope->isArrayScope()
1481 || m_currentScope->isInlineComponent())
1484 m_pendingDefaultProperties[m_currentScope->parentScope()] << m_currentScope;
1486 if (checkCustomParser(parentScope))
1490
1491
1492
1493
1494
1495
1496
1497
1498
1500 parentScope = parentScope->baseType();
1502 const QString defaultPropertyName =
1503 parentScope ? parentScope->defaultPropertyName() : QString();
1505 if (defaultPropertyName.isEmpty())
1510 QQmlJSMetaPropertyBinding binding(m_currentScope->sourceLocation(), defaultPropertyName);
1511 binding.setObject(QQmlJSUtils::getScopeName(m_currentScope, QQmlSA::ScopeType::QMLScope),
1512 QQmlJSScope::ConstPtr(m_currentScope));
1513 m_bindings.append(UnfinishedBinding { m_currentScope->parentScope(), [=]() {
return binding; },
1514 QQmlJSScope::UnnamedPropertyTarget });
1517void QQmlJSImportVisitor::breakInheritanceCycles(
const QQmlJSScope::Ptr &originalScope)
1519 QList<QQmlJSScope::ConstPtr> scopes;
1520 for (QQmlJSScope::ConstPtr scope = originalScope; scope;) {
1521 if (scopes.contains(scope)) {
1522 QString inheritenceCycle;
1523 for (
const auto &seen : std::as_const(scopes)) {
1524 inheritenceCycle.append(seen->baseTypeName());
1525 inheritenceCycle.append(QLatin1String(
" -> "));
1527 inheritenceCycle.append(scopes.first()->baseTypeName());
1529 const QString message = QStringLiteral(
"%1 is part of an inheritance cycle: %2")
1530 .arg(originalScope->baseTypeName(), inheritenceCycle);
1531 m_logger->log(message, qmlInheritanceCycle, scope->sourceLocation());
1532 originalScope->clearBaseType();
1533 originalScope->setBaseTypeError(message);
1537 scopes.append(scope);
1539 const auto newScope = scope->baseType();
1540 if (newScope.isNull()) {
1541 const QString error = scope->baseTypeError();
1542 const QString name = scope->baseTypeName();
1543 if (!error.isEmpty()) {
1544 m_logger->log(error, qmlImport, scope->sourceLocation(),
true,
true);
1545 }
else if (!name.isEmpty() && !m_unresolvedTypes.hasSeen(scope)
1546 && !m_logger->isDisabled()) {
1548 name +
' '_L1 + wasNotFound +
' '_L1 + didYouAddAllImports,
1549 qmlImport, scope->sourceLocation(),
true,
true,
1550 QQmlJSUtils::didYouMean(scope->baseTypeName(),
1551 m_rootScopeImports.types().keys(),
1552 m_logger->filePath(),
1553 scope->sourceLocation()));
1561void QQmlJSImportVisitor::checkDeprecation(
const QQmlJSScope::ConstPtr &originalScope)
1563 for (QQmlJSScope::ConstPtr scope = originalScope; scope; scope = scope->baseType()) {
1564 for (
const QQmlJSAnnotation &annotation : scope->annotations()) {
1565 if (annotation.isDeprecation()) {
1566 QQQmlJSDeprecation deprecation = annotation.deprecation();
1569 QStringLiteral(
"Type \"%1\" is deprecated").arg(scope->internalName());
1571 if (!deprecation.reason.isEmpty())
1572 message.append(QStringLiteral(
" (Reason: %1)").arg(deprecation.reason));
1574 m_logger->log(message, qmlDeprecated, originalScope->sourceLocation());
1580void QQmlJSImportVisitor::checkGroupedAndAttachedScopes(QQmlJSScope::ConstPtr scope)
1584 if (checkCustomParser(scope))
1587 auto children = scope->childScopes();
1588 while (!children.isEmpty()) {
1589 auto childScope = children.takeFirst();
1590 const auto type = childScope->scopeType();
1592 case QQmlSA::ScopeType::GroupedPropertyScope:
1593 case QQmlSA::ScopeType::AttachedPropertyScope:
1594 if (!childScope->baseType()) {
1595 m_logger->log(QStringLiteral(
"unknown %1 property scope %2.")
1596 .arg(type == QQmlSA::ScopeType::GroupedPropertyScope
1597 ? QStringLiteral(
"grouped")
1598 : QStringLiteral(
"attached"),
1599 childScope->internalName()),
1600 qmlUnqualified, childScope->sourceLocation());
1602 children.append(childScope->childScopes());
1610void QQmlJSImportVisitor::checkForComponentTypeWithProperties(
const QQmlJSScope::ConstPtr &scope)
1612 const QQmlJSScope::ConstPtr base = scope->baseType();
1619 if (base->isComposite())
1622 if (base->internalName() !=
"QQmlComponent"_L1)
1625 const auto ownProperties = scope->ownProperties();
1626 for (
const auto &property : ownProperties) {
1627 m_logger->log(
"Component objects cannot declare new properties."_L1,
1628 qmlSyntax, property.sourceLocation());
1632bool QQmlJSImportVisitor::checkCustomParser(
const QQmlJSScope::ConstPtr &scope)
1634 return scope->isInCustomParserParent();
1637void QQmlJSImportVisitor::flushPendingSignalParameters()
1639 const QQmlJSMetaSignalHandler handler = m_signalHandlers[m_pendingSignalHandler];
1640 for (
const QString ¶meter : handler.signalParameters) {
1641 safeInsertJSIdentifier(m_currentScope, parameter,
1642 { QQmlJSScope::JavaScriptIdentifier::Injected,
1643 m_pendingSignalHandler, std::nullopt,
false });
1645 m_pendingSignalHandler = QQmlJS::SourceLocation();
1649
1650
1651
1652
1653
1654
1655QQmlJSMetaMethod::RelativeFunctionIndex
1656QQmlJSImportVisitor::addFunctionOrExpression(
const QQmlJSScope::ConstPtr &scope,
1657 const QString &name)
1659 auto &array = m_functionsAndExpressions[scope];
1660 array.emplaceBack(name);
1667 for (
const auto &function : std::as_const(m_functionStack))
1668 m_innerFunctions[function]++;
1669 m_functionStack.push({ scope, name });
1671 return QQmlJSMetaMethod::RelativeFunctionIndex {
int(array.size() - 1) };
1675
1676
1677
1678
1679
1680
1681
1682
1683void QQmlJSImportVisitor::forgetFunctionExpression(
const QString &name)
1685 auto nameToVerify = name.isEmpty() ? u"<anon>"_s : name;
1686 Q_UNUSED(nameToVerify);
1687 Q_ASSERT(!m_functionStack.isEmpty());
1688 Q_ASSERT(m_functionStack.top().name == nameToVerify);
1689 m_functionStack.pop();
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704int QQmlJSImportVisitor::synthesizeCompilationUnitRuntimeFunctionIndices(
1705 const QQmlJSScope::Ptr &scope,
int count)
const
1707 const auto suitableScope = [](
const QQmlJSScope::Ptr &scope) {
1708 const auto type = scope->scopeType();
1709 return type == QQmlSA::ScopeType::QMLScope
1710 || type == QQmlSA::ScopeType::GroupedPropertyScope
1711 || type == QQmlSA::ScopeType::AttachedPropertyScope;
1714 if (!suitableScope(scope))
1717 auto it = m_functionsAndExpressions.constFind(scope);
1718 if (it == m_functionsAndExpressions.cend())
1721 const auto &functionsAndExpressions = *it;
1722 for (
const QString &functionOrExpression : functionsAndExpressions) {
1723 scope->addOwnRuntimeFunctionIndex(
1724 static_cast<QQmlJSMetaMethod::AbsoluteFunctionIndex>(count));
1741 count += m_innerFunctions.value({ scope, functionOrExpression }, 0);
1747void QQmlJSImportVisitor::populateRuntimeFunctionIndicesForDocument()
const
1750 const auto synthesize = [&](
const QQmlJSScope::Ptr ¤t) {
1751 count = synthesizeCompilationUnitRuntimeFunctionIndices(current, count);
1753 QQmlJSUtils::traverseFollowingQmlIrObjectStructure(m_exportedRootScope, synthesize);
1756bool QQmlJSImportVisitor::visit(QQmlJS::AST::ExpressionStatement *ast)
1758 if (m_pendingSignalHandler.isValid()) {
1759 enterEnvironment(QQmlSA::ScopeType::SignalHandlerFunctionScope, u"signalhandler"_s,
1760 ast->firstSourceLocation());
1761 flushPendingSignalParameters();
1766void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ExpressionStatement *)
1768 if (m_currentScope->scopeType() == QQmlSA::ScopeType::SignalHandlerFunctionScope) {
1775 const QQmlJS::SourceLocation &srcLocation);
1778 QQmlJSLogger *logger)
1780 QStringView namespaceName{ superType };
1781 namespaceName = namespaceName.first(namespaceName.indexOf(u'.'));
1782 logger->log(u"Namespace '%1' of '%2' must start with an upper case letter."_s.arg(namespaceName)
1784 qmlUncreatableType, location,
true,
true);
1787bool QQmlJSImportVisitor::visit(UiObjectDefinition *definition)
1789 const QString superType = buildName(definition->qualifiedTypeNameId);
1791 const bool isRoot = !rootScopeIsValid();
1792 Q_ASSERT(!superType.isEmpty());
1797 const qsizetype indexOfTypeName = superType.lastIndexOf(u'.');
1798 const bool looksLikeGroupedProperty = superType.front().isLower();
1800 if (indexOfTypeName != -1 && looksLikeGroupedProperty) {
1801 logLowerCaseImport(superType, definition->qualifiedTypeNameId->identifierToken,
1805 if (!looksLikeGroupedProperty) {
1807 enterEnvironment(QQmlSA::ScopeType::QMLScope, superType,
1808 definition->firstSourceLocation());
1810 enterRootScope(QQmlSA::ScopeType::QMLScope, superType,
1811 definition->firstSourceLocation());
1812 m_currentScope->setIsRootFileComponentFlag(
true);
1815 const QTypeRevision revision = m_currentScope->baseTypeRevision();
1816 if (
auto base = m_currentScope->baseType(); base) {
1817 if (isRoot && base->internalName() == u"QQmlComponent") {
1818 m_logger->log(u"Qml top level type cannot be 'Component'."_s, qmlTopLevelComponent,
1819 definition->qualifiedTypeNameId->identifierToken,
true,
true);
1821 if (base->isSingleton() && m_currentScope->isComposite()) {
1822 m_logger->log(u"Singleton Type %1 is not creatable."_s.arg(
1823 m_currentScope->baseTypeName()),
1824 qmlUncreatableType, definition->qualifiedTypeNameId->identifierToken,
1827 }
else if (!base->isCreatable()) {
1829 m_logger->log(u"Type %1 is not creatable."_s.arg(m_currentScope->baseTypeName()),
1830 qmlUncreatableType, definition->qualifiedTypeNameId->identifierToken,
1834 if (m_nextIsInlineComponent) {
1835 Q_ASSERT(std::holds_alternative<InlineComponentNameType>(m_currentRootName));
1836 const QString &name = std::get<InlineComponentNameType>(m_currentRootName);
1837 m_currentScope->setIsInlineComponent(
true);
1838 m_currentScope->setInlineComponentName(name);
1839 m_currentScope->setOwnModuleName(m_exportedRootScope->moduleName());
1840 auto precedence = quint8(QQmlJS::PrecedenceValues::InlineComponent);
1841 m_rootScopeImports.setType(name, { m_currentScope, revision, precedence });
1842 m_nextIsInlineComponent =
false;
1845 addDefaultProperties();
1846 Q_ASSERT(m_currentScope->scopeType() == QQmlSA::ScopeType::QMLScope);
1847 m_qmlTypes.append(m_currentScope);
1849 m_objectDefinitionScopes << m_currentScope;
1851 enterEnvironmentNonUnique(QQmlSA::ScopeType::GroupedPropertyScope, superType,
1852 definition->firstSourceLocation());
1853 m_bindings.append(createNonUniqueScopeBinding(m_currentScope, superType,
1854 definition->firstSourceLocation()));
1855 QQmlJSScope::resolveTypes(m_currentScope, m_rootScopeImports.contextualTypes(),
1859 m_currentScope->setAnnotations(parseAnnotations(definition->annotations));
1864void QQmlJSImportVisitor::endVisit(UiObjectDefinition *)
1866 QQmlJSScope::resolveTypes(m_currentScope, m_rootScopeImports.contextualTypes(), usedTypes());
1870bool QQmlJSImportVisitor::visit(UiInlineComponent *component)
1872 if (!std::holds_alternative<RootDocumentNameType>(m_currentRootName)) {
1873 m_logger->log(u"Nested inline components are not supported"_s, qmlSyntax,
1874 component->firstSourceLocation());
1878 const auto it = m_seenInlineComponents.constFind(component->name);
1879 if (it != m_seenInlineComponents.cend()) {
1880 m_logger->log(
"Duplicate inline component '%1'"_L1.arg(it.key()),
1881 qmlDuplicateInlineComponent, component->firstSourceLocation());
1882 m_logger->log(
"Note: previous component named '%1' here"_L1.arg(it.key()),
1883 qmlDuplicateInlineComponent, it.value(),
true,
true, {},
1884 component->firstSourceLocation().startLine);
1886 m_seenInlineComponents[component->name] = component->firstSourceLocation();
1889 m_nextIsInlineComponent =
true;
1890 m_currentRootName = component->name.toString();
1894void QQmlJSImportVisitor::endVisit(UiInlineComponent *component)
1896 m_currentRootName = RootDocumentNameType();
1897 if (m_nextIsInlineComponent) {
1898 m_logger->log(u"Inline component declaration must be followed by a typename"_s,
1899 qmlSyntax, component->firstSourceLocation());
1901 m_nextIsInlineComponent =
false;
1904bool QQmlJSImportVisitor::visit(UiPublicMember *publicMember)
1906 switch (publicMember->type) {
1907 case UiPublicMember::Signal: {
1908 const QString signalName = publicMember->name.toString();
1909 UiParameterList *param = publicMember->parameters;
1910 QQmlJSMetaMethod method;
1911 method.setMethodType(QQmlJSMetaMethodType::Signal);
1912 method.setReturnTypeName(QStringLiteral(
"void"));
1913 method.setMethodName(signalName);
1914 method.setSourceLocation(combine(publicMember->firstSourceLocation(),
1915 publicMember->lastSourceLocation()));
1916 method.setOtherMethodIndex(
1917 QQmlJSMetaMethod::RelativeFunctionIndex(m_currentScope->ownMethods().size()));
1919 method.addParameter(
1920 QQmlJSMetaParameter(
1921 param->name.toString(),
1922 param->type ? param->type->toString() : QString()
1924 param = param->next;
1926 m_currentScope->addOwnMethod(method);
1929 case UiPublicMember::Property: {
1930 const QString propertyName = publicMember->name.toString();
1931 QString typeName = buildName(publicMember->memberType);
1932 if (typeName.contains(u'.') && typeName.front().isLower()) {
1933 logLowerCaseImport(typeName, publicMember->typeToken, m_logger);
1937 const bool isAlias = (typeName == u"alias"_s);
1939 auto tryParseAlias = [&]() {
1941 if (!publicMember->statement) {
1942 m_logger->log(QStringLiteral(
"Invalid alias expression - an initializer is needed."),
1943 qmlSyntax, publicMember->memberType->firstSourceLocation());
1946 const auto expression = cast<ExpressionStatement *>(publicMember->statement);
1947 auto node = expression ? expression->expression :
nullptr;
1948 auto fex = cast<FieldMemberExpression *>(node);
1951 aliasExpr.prepend(u'.' + fex->name.toString());
1952 fex = cast<FieldMemberExpression *>(node);
1955 if (
const auto idExpression = cast<IdentifierExpression *>(node)) {
1956 aliasExpr.prepend(idExpression->name.toString());
1960 m_logger->log(QStringLiteral(
"Invalid alias expression. Only IDs and field "
1961 "member expressions can be aliased."),
1962 qmlSyntax, publicMember->statement->firstSourceLocation());
1967 QQmlJSMetaProperty prop;
1968 prop.setPropertyName(propertyName);
1969 prop.setIsList(publicMember->typeModifier == QLatin1String(
"list"));
1970 prop.setIsWritable(!publicMember->isReadonly());
1971 prop.setIsFinal(publicMember->isFinal());
1972 prop.setIsVirtual(publicMember->isVirtual());
1973 prop.setIsOverride(publicMember->isOverride());
1974 prop.setAliasExpression(aliasExpr);
1975 prop.setSourceLocation(
1976 combine(publicMember->firstSourceLocation(), publicMember->colonToken));
1978 isAlias ? QQmlJSScope::ConstPtr() : m_rootScopeImports.type(typeName).scope;
1980 prop.setType(prop.isList() ? type->listType() : type);
1981 const QString internalName = type->internalName();
1982 prop.setTypeName(internalName.isEmpty() ? typeName : internalName);
1983 }
else if (!isAlias) {
1984 m_pendingPropertyTypes << PendingPropertyType { m_currentScope, prop.propertyName(),
1985 publicMember->firstSourceLocation() };
1986 prop.setTypeName(typeName);
1988 prop.setAnnotations(parseAnnotations(publicMember->annotations));
1989 if (publicMember->isDefaultMember())
1990 m_currentScope->setOwnDefaultPropertyName(propertyName);
1991 prop.setIndex(m_currentScope->ownProperties().size());
1992 m_currentScope->addOwnProperty(prop);
1994 QQmlJSMetaMethod method(
1995 QQmlSignalNames::propertyNameToChangedSignalName(propertyName), u"void"_s);
1996 method.setMethodType(QQmlJSMetaMethodType::Signal);
1997 method.setIsImplicitQmlPropertyChangeSignal(
true);
1998 method.setOtherMethodIndex(
1999 QQmlJSMetaMethod::RelativeFunctionIndex(m_currentScope->ownMethods().size()));
2000 m_currentScope->addOwnMethod(method);
2002 if (publicMember->isRequired())
2003 m_currentScope->setPropertyLocallyRequired(prop.propertyName(),
true);
2005 BindingExpressionParseResult parseResult = BindingExpressionParseResult::Invalid;
2009 parseBindingExpression(publicMember->name.toString(), publicMember->statement,
2015 if (parseResult == BindingExpressionParseResult::Script) {
2016 Q_ASSERT(!m_savedBindingOuterScope);
2017 m_savedBindingOuterScope = m_currentScope;
2018 enterEnvironment(QQmlSA::ScopeType::BindingFunctionScope, QStringLiteral(
"binding"),
2019 publicMember->statement->firstSourceLocation());
2029void QQmlJSImportVisitor::endVisit(UiPublicMember *publicMember)
2031 if (m_savedBindingOuterScope) {
2032 m_currentScope = m_savedBindingOuterScope;
2033 m_savedBindingOuterScope = {};
2035 forgetFunctionExpression(publicMember->name.toString());
2039bool QQmlJSImportVisitor::visit(UiRequired *required)
2041 const QString name = required->name.toString();
2043 m_requiredProperties << RequiredProperty { m_currentScope, name,
2044 required->firstSourceLocation() };
2046 m_currentScope->setPropertyLocallyRequired(name,
true);
2050void QQmlJSImportVisitor::visitFunctionExpressionHelper(QQmlJS::AST::FunctionExpression *fexpr)
2052 using namespace QQmlJS::AST;
2053 auto name = fexpr->name.toString();
2054 if (!name.isEmpty()) {
2055 QQmlJSMetaMethod method(name);
2056 method.setMethodType(QQmlJSMetaMethodType::Method);
2057 method.setSourceLocation(combine(fexpr->firstSourceLocation(), fexpr->lastSourceLocation()));
2059 if (!m_pendingMethodAnnotations.isEmpty()) {
2060 method.setAnnotations(m_pendingMethodAnnotations);
2061 m_pendingMethodAnnotations.clear();
2065 const bool parseTypes = m_scopesById.signaturesAreEnforced();
2067 bool formalsFullyTyped = parseTypes;
2068 bool anyFormalTyped =
false;
2069 PendingMethodTypeAnnotations pending{ m_currentScope, name, {} };
2072 for (
auto formals = fexpr->formals; formals; formals = formals->next) {
2073 PatternElement *e = formals->element;
2076 if (e->typeAnnotation && (e->bindingTarget || e->initializer))
2077 m_logger->log(
"Type annotations on default parameters are not supported"_L1,
2079 combine(e->firstSourceLocation(), e->lastSourceLocation()));
2082 if (
const auto *formals = parseTypes ? fexpr->formals :
nullptr) {
2083 const auto parameters = formals->formals();
2084 for (
const auto ¶meter : parameters) {
2085 const QString type = parameter.typeAnnotation
2086 ? parameter.typeAnnotation->type->toString()
2088 if (type.isEmpty()) {
2089 formalsFullyTyped =
false;
2090 method.addParameter(QQmlJSMetaParameter(parameter.id, QStringLiteral(
"var")));
2091 pending.locations.emplace_back();
2093 anyFormalTyped =
true;
2094 method.addParameter(QQmlJSMetaParameter(parameter.id, type));
2095 pending.locations.append(
2096 combine(parameter.typeAnnotation->firstSourceLocation(),
2097 parameter.typeAnnotation->lastSourceLocation()));
2103 method.setIsJavaScriptFunction(!formalsFullyTyped);
2109 if (parseTypes && fexpr->typeAnnotation) {
2110 method.setReturnTypeName(fexpr->typeAnnotation->type->toString());
2111 pending.locations.append(combine(fexpr->typeAnnotation->firstSourceLocation(),
2112 fexpr->typeAnnotation->lastSourceLocation()));
2113 }
else if (anyFormalTyped) {
2114 method.setReturnTypeName(QStringLiteral(
"void"));
2116 method.setReturnTypeName(QStringLiteral(
"var"));
2119 const auto &locs = pending.locations;
2120 if (std::any_of(locs.cbegin(), locs.cend(), [](
const auto &loc) {
return loc.isValid(); }))
2121 m_pendingMethodTypeAnnotations << pending;
2123 method.setJsFunctionIndex(addFunctionOrExpression(m_currentScope, method.methodName()));
2124 method.setOtherMethodIndex(
2125 QQmlJSMetaMethod::RelativeFunctionIndex(m_currentScope->ownMethods().size()));
2127 if (m_currentScope->scopeType() != QQmlSA::ScopeType::QMLScope) {
2129 const QQmlJS::SourceLocation functionLocation = fexpr->identifierToken.isValid()
2130 ? fexpr->identifierToken
2131 : fexpr->functionToken;
2132 safeInsertJSIdentifier(m_currentScope, name,
2133 { QQmlJSScope::JavaScriptIdentifier::LexicalScoped,
2134 functionLocation, method.returnTypeName(),
2137 m_currentScope->addOwnMethod(method);
2139 enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, name, fexpr->firstSourceLocation());
2141 addFunctionOrExpression(m_currentScope, QStringLiteral(
"<anon>"));
2142 enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, QStringLiteral(
"<anon>"),
2143 fexpr->firstSourceLocation());
2147bool QQmlJSImportVisitor::visit(QQmlJS::AST::FunctionExpression *fexpr)
2149 visitFunctionExpressionHelper(fexpr);
2153void QQmlJSImportVisitor::endVisit(QQmlJS::AST::FunctionExpression *fexpr)
2155 forgetFunctionExpression(fexpr->name.toString());
2159bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiSourceElement *srcElement)
2161 m_pendingMethodAnnotations = parseAnnotations(srcElement->annotations);
2165bool QQmlJSImportVisitor::visit(QQmlJS::AST::FunctionDeclaration *fdecl)
2167 if (!fdecl->name.isEmpty()) {
2168 const QString name = fdecl->name.toString();
2169 if (
auto previousDeclaration = m_currentScope->ownJSIdentifier(name)) {
2170 m_logger->log(
"Identifier '%1' has already been declared"_L1.arg(name), qmlSyntax,
2171 fdecl->identifierToken);
2172 m_logger->log(
"Note: previous declaration of '%1' here"_L1.arg(name), qmlSyntax,
2173 previousDeclaration->location);
2176 visitFunctionExpressionHelper(fdecl);
2180void QQmlJSImportVisitor::endVisit(QQmlJS::AST::FunctionDeclaration *fdecl)
2182 forgetFunctionExpression(fdecl->name.toString());
2186bool QQmlJSImportVisitor::visit(QQmlJS::AST::ClassExpression *ast)
2188 QQmlJSMetaProperty prop;
2189 prop.setPropertyName(ast->name.toString());
2190 m_currentScope->addOwnProperty(prop);
2191 enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, ast->name.toString(),
2192 ast->firstSourceLocation());
2196void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ClassExpression *)
2202 QQmlJS::AST::ArgumentList *args)
2204 QStringView contextString;
2205 QStringView mainString;
2206 QStringView commentString;
2207 auto registerContextString = [&](QStringView string) {
2208 contextString = string;
2211 auto registerMainString = [&](QStringView string) {
2212 mainString = string;
2215 auto registerCommentString = [&](QStringView string) {
2216 commentString = string;
2219 auto finalizeBinding = [&](QV4::CompiledData::Binding::Type type,
2220 QV4::CompiledData::TranslationData data) {
2221 if (type == QV4::CompiledData::Binding::Type_Translation) {
2222 binding.setTranslation(mainString, commentString, contextString, data.number);
2223 }
else if (type == QV4::CompiledData::Binding::Type_TranslationById) {
2224 binding.setTranslationId(mainString, data.number);
2226 binding.setStringLiteral(mainString);
2229 QmlIR::tryGeneratingTranslationBindingBase(
2231 registerMainString, registerCommentString, registerContextString, finalizeBinding);
2234QQmlJSImportVisitor::BindingExpressionParseResult
2235QQmlJSImportVisitor::parseBindingExpression(
2236 const QString &name,
const QQmlJS::AST::Statement *statement,
2237 const UiPublicMember *associatedPropertyDefinition)
2239 if (statement ==
nullptr)
2240 return BindingExpressionParseResult::Invalid;
2242 const auto *exprStatement = cast<
const ExpressionStatement *>(statement);
2244 if (exprStatement ==
nullptr) {
2245 QQmlJS::SourceLocation location = statement->firstSourceLocation();
2247 if (
const auto *block = cast<
const Block *>(statement); block && block->statements) {
2248 location = block->statements->firstSourceLocation();
2251 QQmlJSMetaPropertyBinding binding(location, name);
2252 binding.setScriptBinding(addFunctionOrExpression(m_currentScope, name),
2253 QQmlSA::ScriptBindingKind::PropertyBinding, ScriptValue_Function);
2254 m_bindings.append(UnfinishedBinding {
2256 [binding = std::move(binding)]() {
return binding; }
2258 return BindingExpressionParseResult::Script;
2261 auto expr = exprStatement->expression;
2262 QQmlJSMetaPropertyBinding binding(
2263 combine(expr->firstSourceLocation(), expr->lastSourceLocation()),
2266 ScriptBindingValueType scriptBindingValuetype = ScriptValue_Unknown;
2268 switch (expr->kind) {
2269 case Node::Kind_TrueLiteral:
2270 binding.setBoolLiteral(
true);
2272 case Node::Kind_FalseLiteral:
2273 binding.setBoolLiteral(
false);
2275 case Node::Kind_NullExpression:
2276 binding.setNullLiteral();
2278 case Node::Kind_IdentifierExpression: {
2279 auto idExpr = QQmlJS::AST::cast<QQmlJS::AST::IdentifierExpression *>(expr);
2281 if (idExpr->name == u"undefined")
2282 scriptBindingValuetype = ScriptValue_Undefined;
2285 case Node::Kind_FunctionDeclaration:
2286 case Node::Kind_FunctionExpression:
2287 case Node::Kind_Block: {
2288 scriptBindingValuetype = ScriptValue_Function;
2291 case Node::Kind_NumericLiteral:
2292 binding.setNumberLiteral(cast<NumericLiteral *>(expr)->value);
2294 case Node::Kind_StringLiteral:
2295 binding.setStringLiteral(cast<StringLiteral *>(expr)->value);
2297 case Node::Kind_RegExpLiteral:
2298 binding.setRegexpLiteral(cast<RegExpLiteral *>(expr)->pattern);
2300 case Node::Kind_TemplateLiteral: {
2301 auto templateLit = QQmlJS::AST::cast<QQmlJS::AST::TemplateLiteral *>(expr);
2302 Q_ASSERT(templateLit);
2303 if (templateLit->hasNoSubstitution) {
2304 binding.setStringLiteral(templateLit->value);
2306 binding.setScriptBinding(addFunctionOrExpression(m_currentScope, name),
2307 QQmlSA::ScriptBindingKind::PropertyBinding);
2308 for (QQmlJS::AST::TemplateLiteral *l = templateLit; l; l = l->next) {
2309 if (QQmlJS::AST::ExpressionNode *expression = l->expression)
2310 expression->accept(
this);
2316 if (QQmlJS::AST::UnaryMinusExpression *unaryMinus = QQmlJS::AST::cast<QQmlJS::AST::UnaryMinusExpression *>(expr)) {
2317 if (QQmlJS::AST::NumericLiteral *lit = QQmlJS::AST::cast<QQmlJS::AST::NumericLiteral *>(unaryMinus->expression))
2318 binding.setNumberLiteral(-lit->value);
2319 }
else if (QQmlJS::AST::CallExpression *call = QQmlJS::AST::cast<QQmlJS::AST::CallExpression *>(expr)) {
2320 if (QQmlJS::AST::IdentifierExpression *base = QQmlJS::AST::cast<QQmlJS::AST::IdentifierExpression *>(call->base))
2321 handleTranslationBinding(binding, base->name, call->arguments);
2326 if (!binding.isValid()) {
2328 binding.setScriptBinding(addFunctionOrExpression(m_currentScope, name),
2329 QQmlSA::ScriptBindingKind::PropertyBinding,
2330 scriptBindingValuetype);
2332 m_bindings.append(UnfinishedBinding { m_currentScope, [=]() {
return binding; } });
2335 if (binding.bindingType() == QQmlSA::BindingType::Translation
2336 || binding.bindingType() == QQmlSA::BindingType::TranslationById) {
2337 return BindingExpressionParseResult::Translation;
2339 if (!QQmlJSMetaPropertyBinding::isLiteralBinding(binding.bindingType()))
2340 return BindingExpressionParseResult::Script;
2342 if (associatedPropertyDefinition)
2343 handleLiteralBinding(binding, associatedPropertyDefinition);
2345 return BindingExpressionParseResult::Literal;
2348bool QQmlJSImportVisitor::isImportPrefix(QString prefix)
const
2350 if (prefix.isEmpty() || !prefix.front().isUpper())
2353 return m_rootScopeImports.isNullType(prefix);
2356void QQmlJSImportVisitor::handleIdDeclaration(QQmlJS::AST::UiScriptBinding *scriptBinding)
2358 if (m_currentScope->scopeType() != QQmlJSScope::ScopeType::QMLScope) {
2359 m_logger->log(u"id declarations are only allowed in objects"_s, qmlSyntax,
2360 scriptBinding->statement->firstSourceLocation());
2363 const auto *statement = cast<ExpressionStatement *>(scriptBinding->statement);
2365 m_logger->log(u"id must be followed by an identifier"_s, qmlSyntax,
2366 scriptBinding->statement->firstSourceLocation());
2369 const QString name = [&]() {
2370 if (
const auto *idExpression = cast<IdentifierExpression *>(statement->expression))
2371 return idExpression->name.toString();
2372 else if (
const auto *idString = cast<StringLiteral *>(statement->expression)) {
2373 m_logger->log(u"ids do not need quotation marks"_s, qmlSyntaxIdQuotation,
2374 idString->firstSourceLocation());
2375 return idString->value.toString();
2377 m_logger->log(u"Failed to parse id"_s, qmlSyntax,
2378 statement->expression->firstSourceLocation());
2382 if (!name.isEmpty() && !name.front().isLower() && name.front() != u'_') {
2383 m_logger->log(u"Id must start with a lower case letter or an '_'"_s, qmlSyntax,
2384 statement->expression->firstSourceLocation());
2387 m_currentScope->setIdSourceLocation(combine(scriptBinding->statement->firstSourceLocation(),
2388 scriptBinding->statement->lastSourceLocation()));
2389 if (m_scopesById.existsAnywhereInDocument(name)) {
2392 breakInheritanceCycles(m_currentScope);
2393 m_scopesById.possibleScopes(
2394 name, m_currentScope, QQmlJSScopesByIdOption::Default,
2395 [&](
const QQmlJSScope::ConstPtr &otherScopeWithID,
2396 QQmlJSScopesById::Confidence confidence) {
2398 Q_UNUSED(confidence);
2400 auto otherLocation = otherScopeWithID->sourceLocation();
2404 m_logger->log(u"Found a duplicated id. id %1 was first declared at %2:%3"_s.arg(
2405 name, QString::number(otherLocation.startLine),
2406 QString::number(otherLocation.startColumn)),
2407 qmlSyntaxDuplicateIds,
2408 scriptBinding->firstSourceLocation());
2409 return QQmlJSScopesById::CallbackResult::ContinueSearch;
2412 if (!name.isEmpty())
2413 m_scopesById.insert(name, m_currentScope);
2416void QQmlJSImportVisitor::handleLiteralBinding(
const QQmlJSMetaPropertyBinding &binding,
2417 const UiPublicMember *associatedPropertyDefinition)
2421 Q_UNUSED(associatedPropertyDefinition);
2425
2426
2427
2428
2429
2432 const QQmlJS::SourceLocation &srcLocation)
2434 const auto createBinding = [=]() {
2435 const QQmlJSScope::ScopeType type = scope->scopeType();
2442 const auto propertyBindings = scope->parentScope()->ownPropertyBindings(name);
2443 const bool alreadyHasBinding =
std::any_of(propertyBindings.first, propertyBindings.second,
2444 [&](
const QQmlJSMetaPropertyBinding &binding) {
2445 return binding.bindingType() == bindingType;
2447 if (alreadyHasBinding)
2448 return QQmlJSMetaPropertyBinding(QQmlJS::SourceLocation {});
2451 if (type == QQmlSA::ScopeType::GroupedPropertyScope)
2452 binding.setGroupBinding(
static_cast<QSharedPointer<QQmlJSScope>>(scope));
2454 binding.setAttachedBinding(
static_cast<QSharedPointer<QQmlJSScope>>(scope));
2457 return { scope->parentScope(), createBinding };
2460bool QQmlJSImportVisitor::visit(UiScriptBinding *scriptBinding)
2462 Q_ASSERT(!m_savedBindingOuterScope);
2463 Q_ASSERT(!m_thisScriptBindingIsJavaScript);
2464 m_savedBindingOuterScope = m_currentScope;
2465 const auto id = scriptBinding->qualifiedId;
2466 if (!id->next && id->name == QLatin1String(
"id")) {
2467 handleIdDeclaration(scriptBinding);
2474 for (; group->next; group = group->next) {
2475 const QString name = group->name.toString();
2479 if (group == id && isImportPrefix(name)) {
2480 prefix = name + u'.';
2484 const bool isAttachedProperty = name.front().isUpper();
2485 if (isAttachedProperty) {
2487 enterEnvironmentNonUnique(QQmlSA::ScopeType::AttachedPropertyScope, prefix + name,
2488 group->firstSourceLocation());
2491 enterEnvironmentNonUnique(QQmlSA::ScopeType::GroupedPropertyScope, prefix + name,
2492 group->firstSourceLocation());
2494 m_bindings.append(createNonUniqueScopeBinding(m_currentScope, prefix + name,
2495 group->firstSourceLocation()));
2500 const auto name = group->name.toString();
2504 const auto signal = QQmlSignalNames::handlerNameToSignalName(name);
2506 if (!signal.has_value() || m_currentScope->hasProperty(name)) {
2507 m_propertyBindings[m_currentScope].append(
2508 { m_savedBindingOuterScope, group->firstSourceLocation(), name });
2510 auto result = parseBindingExpression(name, scriptBinding->statement);
2511 m_thisScriptBindingIsJavaScript = (result == BindingExpressionParseResult::Script);
2513 const auto statement = scriptBinding->statement;
2514 QStringList signalParameters;
2516 if (ExpressionStatement *expr = cast<ExpressionStatement *>(statement)) {
2517 if (FunctionExpression *func = expr->expression->asFunctionDefinition()) {
2518 for (FormalParameterList *formal = func->formals; formal; formal = formal->next)
2519 signalParameters << formal->element->bindingIdentifier.toString();
2523 QQmlJSMetaMethod scopeSignal;
2524 const auto methods = m_currentScope->methods(*signal, QQmlJSMetaMethodType::Signal);
2525 if (!methods.isEmpty())
2526 scopeSignal = methods[0];
2528 const auto firstSourceLocation = statement->firstSourceLocation();
2529 bool hasMultilineStatementBody =
2530 statement->lastSourceLocation().startLine > firstSourceLocation.startLine;
2531 m_pendingSignalHandler = firstSourceLocation;
2532 m_signalHandlers.insert(firstSourceLocation,
2533 { scopeSignal.parameterNames(), hasMultilineStatementBody });
2537 const auto index = addFunctionOrExpression(m_currentScope, name);
2538 const auto createBinding = [
2540 scope = m_currentScope,
2541 signalName = *signal,
2544 firstSourceLocation,
2545 groupLocation = group->firstSourceLocation(),
2546 signalParameters]() {
2548 Q_ASSERT(scope->isFullyResolved());
2549 QQmlSA::ScriptBindingKind kind = QQmlSA::ScriptBindingKind::Invalid;
2550 const auto methods = scope->methods(signalName, QQmlJSMetaMethodType::Signal);
2551 if (!methods.isEmpty()) {
2552 kind = QQmlSA::ScriptBindingKind::SignalHandler;
2553 checkSignal(scope, groupLocation, name, signalParameters);
2554 }
else if (QQmlJSUtils::propertyFromChangedHandler(scope, name).has_value()) {
2555 kind = QQmlSA::ScriptBindingKind::ChangeHandler;
2556 checkSignal(scope, groupLocation, name, signalParameters);
2557 }
else if (scope->hasProperty(name)) {
2560 kind = QQmlSA::ScriptBindingKind::PropertyBinding;
2561 m_signalHandlers.remove(firstSourceLocation);
2564 checkSignal(scope, groupLocation, name, signalParameters);
2567 QQmlJSMetaPropertyBinding binding(firstSourceLocation, name);
2568 binding.setScriptBinding(index, kind, ScriptValue_Function);
2571 m_bindings.append(UnfinishedBinding { m_currentScope, createBinding });
2572 m_thisScriptBindingIsJavaScript =
true;
2578 while (m_currentScope->scopeType() == QQmlSA::ScopeType::GroupedPropertyScope
2579 || m_currentScope->scopeType() == QQmlSA::ScopeType::AttachedPropertyScope) {
2584 enterEnvironment(QQmlSA::ScopeType::SignalHandlerFunctionScope,
2586 scriptBinding->statement->firstSourceLocation());
2588 enterEnvironment(QQmlSA::ScopeType::BindingFunctionScope,
2590 scriptBinding->statement->firstSourceLocation());
2596void QQmlJSImportVisitor::endVisit(UiScriptBinding *)
2598 if (m_savedBindingOuterScope) {
2599 m_currentScope = m_savedBindingOuterScope;
2600 m_savedBindingOuterScope = {};
2606 if (m_thisScriptBindingIsJavaScript) {
2607 m_thisScriptBindingIsJavaScript =
false;
2608 Q_ASSERT(!m_functionStack.isEmpty());
2609 m_functionStack.pop();
2613bool QQmlJSImportVisitor::visit(UiArrayBinding *arrayBinding)
2615 createAttachedAndGroupedScopes(arrayBinding->qualifiedId);
2616 enterEnvironment(QQmlSA::ScopeType::QMLScope, buildName(arrayBinding->qualifiedId),
2617 arrayBinding->firstSourceLocation());
2618 m_currentScope->setIsArrayScope(
true);
2622void QQmlJSImportVisitor::endVisit(UiArrayBinding *arrayBinding)
2629 const auto children = m_currentScope->childScopes();
2632 const int scopesEnteredCounter = openAttachedAndGroupedScopes(arrayBinding->qualifiedId);
2633 auto guard = qScopeGuard([
this, scopesEnteredCounter]() {
2634 for (
int i = 0; i < scopesEnteredCounter; ++i)
2638 if (checkCustomParser(m_currentScope)) {
2644 auto group = arrayBinding->qualifiedId;
2645 for (; group->next; group = group->next) { }
2646 const QString propertyName = group->name.toString();
2649 for (
auto element = arrayBinding->members; element; element = element->next, ++i) {
2650 const auto &type = children[i];
2651 if ((type->scopeType() != QQmlSA::ScopeType::QMLScope)) {
2652 m_logger->log(u"Declaring an object which is not a Qml object"
2653 " as a list member."_s, qmlSyntax, element->firstSourceLocation());
2656 m_pendingPropertyObjectBindings
2657 << PendingPropertyObjectBinding { m_currentScope, type, propertyName,
2658 element->firstSourceLocation(),
false };
2659 QQmlJSMetaPropertyBinding binding(element->firstSourceLocation(), propertyName);
2660 binding.setObject(QQmlJSUtils::getScopeName(type, QQmlSA::ScopeType::QMLScope),
2661 QQmlJSScope::ConstPtr(type));
2662 m_bindings.append(UnfinishedBinding {
2664 [binding = std::move(binding)]() {
return binding; },
2665 QQmlJSScope::ListPropertyTarget
2670bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiEnumDeclaration *uied)
2672 QQmlJSMetaEnum qmlEnum(uied->name.toString());
2673 qmlEnum.setIsQml(
true);
2674 qmlEnum.setLineNumber(uied->enumToken.startLine);
2675 for (
const auto *member = uied->members; member; member = member->next) {
2676 qmlEnum.addKey(member->member.toString());
2677 qmlEnum.addValue(
int(member->value));
2679 m_currentScope->addOwnEnumeration(qmlEnum);
2683QList<QQmlJS::DiagnosticMessage> QQmlJSImportVisitor::importFromHost(
2684 const QString &path,
const QString &prefix,
const QQmlJS::SourceLocation &location)
2686 QFileInfo fileInfo(path);
2687 if (!fileInfo.exists()) {
2688 m_logger->log(
"File or directory you are trying to import does not exist: %1."_L1.arg(path),
2689 qmlImport, location);
2693 if (fileInfo.isFile()) {
2694 const auto scope = m_importer->importFile(path);
2695 const QString actualPrefix = prefix.isEmpty() ? scope->internalName() : prefix;
2696 auto precedence = quint8(QQmlJS::PrecedenceValues::Default);
2697 m_rootScopeImports.setType(actualPrefix, { scope, QTypeRevision(), precedence });
2698 addImportWithLocation(actualPrefix, location,
false);
2702 if (fileInfo.isDir()) {
2703 auto precedence = quint8(QQmlJS::PrecedenceValues::Default);
2704 auto scopes = m_importer->importDirectory(path, precedence, prefix);
2705 const auto types = scopes.types();
2706 const auto warnings = scopes.warnings();
2707 m_rootScopeImports.add(std::move(scopes));
2708 for (
auto it = types.keyBegin(), end = types.keyEnd(); it != end; it++)
2709 addImportWithLocation(*it, location, !warnings.isEmpty());
2714 "%1 is neither a file nor a directory. Are sure the import path is correct?"_L1.arg(
2716 qmlImport, location);
2720QList<QQmlJS::DiagnosticMessage> QQmlJSImportVisitor::importFromQrc(
2721 const QString &path,
const QString &prefix,
const QQmlJS::SourceLocation &location)
2723 Q_ASSERT(path.startsWith(u':'));
2724 const QQmlJSResourceFileMapper *mapper = m_importer->resourceFileMapper();
2728 const auto pathNoColon = QStringView(path).mid(1);
2729 if (mapper->isFile(pathNoColon)) {
2730 const auto entry = m_importer->resourceFileMapper()->entry(
2731 QQmlJSResourceFileMapper::resourceFileFilter(pathNoColon.toString()));
2732 const auto scope = m_importer->importFile(entry.filePath);
2733 const QString actualPrefix =
2734 prefix.isEmpty() ? QFileInfo(entry.resourcePath).baseName() : prefix;
2735 auto precedence = quint8(QQmlJS::PrecedenceValues::Default);
2736 m_rootScopeImports.setType(actualPrefix, { scope, QTypeRevision(), precedence });
2737 addImportWithLocation(actualPrefix, location,
false);
2741 auto scopes = m_importer->importDirectory(path, quint8(QQmlJS::PrecedenceValues::Default), prefix);
2742 const auto types = scopes.types();
2743 const auto warnings = scopes.warnings();
2744 m_rootScopeImports.add(std::move(scopes));
2745 for (
auto it = types.keyBegin(), end = types.keyEnd(); it != end; it++)
2746 addImportWithLocation(*it, location, !warnings.isEmpty());
2750bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiImport *import)
2753 QString prefix = QLatin1String(
"");
2754 if (import->asToken.isValid()) {
2755 prefix += import->importId;
2756 if (!import->importId.isEmpty() && !import->importId.front().isUpper()) {
2757 m_logger->log(u"Import qualifier '%1' must start with a capital letter."_s.arg(
2759 qmlImport, import->importIdToken,
true,
true);
2761 m_seenModuleQualifiers.append(prefix);
2764 const QString filename = import->fileName.toString();
2765 if (!filename.isEmpty()) {
2766 const QUrl url(filename);
2767 const QString scheme = url.scheme();
2768 const QQmlJS::SourceLocation importLocation = import->firstSourceLocation();
2769 if (scheme ==
""_L1) {
2770 QFileInfo fileInfo(url.path());
2771 QString absolute = fileInfo.isRelative()
2772 ? QDir::cleanPath(QDir(m_implicitImportDirectory).filePath(filename))
2774 auto warnings = absolute.startsWith(u':')
2775 ? importFromQrc(absolute, prefix, importLocation)
2776 : importFromHost(absolute, prefix, importLocation);
2777 processImportWarnings(
"path \"%1\""_L1.arg(url.path()), warnings, importLocation);
2779 }
else if (scheme ==
"file"_L1) {
2780 auto warnings = importFromHost(url.path(), prefix, importLocation);
2781 processImportWarnings(
"URL \"%1\""_L1.arg(url.path()), warnings, importLocation);
2783 }
else if (scheme ==
"qrc"_L1) {
2784 auto warnings = importFromQrc(
":"_L1 + url.path(), prefix, importLocation);
2785 processImportWarnings(
"URL \"%1\""_L1.arg(url.path()), warnings, importLocation);
2788 m_logger->log(
"Unknown import syntax. Imports can be paths, qrc urls or file urls"_L1,
2789 qmlImport, import->firstSourceLocation());
2793 const QString path = buildName(import->importUri);
2795 QStringList staticModulesProvided;
2797 auto imported = m_importer->importModule(
2798 path, quint8(QQmlJS::PrecedenceValues::Default), prefix,
2799 import->version ? import->version->version : QTypeRevision(), &staticModulesProvided);
2800 const auto types = imported.types();
2801 const auto warnings = imported.warnings();
2802 m_rootScopeImports.add(std::move(imported));
2803 for (
auto it = types.keyBegin(), end = types.keyEnd(); it != end; it++)
2804 addImportWithLocation(*it, import->firstSourceLocation(), !warnings.isEmpty());
2806 if (prefix.isEmpty()) {
2807 for (
const QString &staticModule : std::as_const(staticModulesProvided))
2808 addStaticImportWithLocation(path, import->firstSourceLocation(), path != staticModule);
2811 processImportWarnings(
2812 QStringLiteral(
"module \"%1\"").arg(path), warnings, import->firstSourceLocation());
2816#if QT_VERSION >= QT_VERSION_CHECK(6
, 6
, 0
)
2818void handlePragmaValues(QQmlJS::AST::UiPragma *pragma, F &&assign)
2820 for (
const QQmlJS::AST::UiPragmaValueList *v = pragma->values; v; v = v->next)
2825void handlePragmaValues(QQmlJS::AST::UiPragma *pragma, F &&assign)
2827 assign(pragma->value);
2831bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiPragma *pragma)
2833 if (pragma->name == u"Strict"_s) {
2838 if (!m_logger->wasCategoryChanged(qmlCompiler))
2839 m_logger->setCategorySeverity(qmlCompiler, QQmlJS::WarningSeverity::Warning);
2840 }
else if (pragma->name == u"ComponentBehavior") {
2841 handlePragmaValues(pragma, [
this, pragma](QStringView value) {
2842 if (value == u"Bound") {
2843 m_scopesById.setComponentsAreBound(
true);
2844 }
else if (value == u"Unbound") {
2845 m_scopesById.setComponentsAreBound(
false);
2847 m_logger->log(u"Unknown argument \"%1\" to pragma ComponentBehavior"_s.arg(value),
2848 qmlSyntax, pragma->firstSourceLocation());
2851 }
else if (pragma->name == u"FunctionSignatureBehavior") {
2852 handlePragmaValues(pragma, [
this, pragma](QStringView value) {
2853 if (value == u"Enforced") {
2854 m_scopesById.setSignaturesAreEnforced(
true);
2855 }
else if (value == u"Ignored") {
2856 m_scopesById.setSignaturesAreEnforced(
false);
2859 u"Unknown argument \"%1\" to pragma FunctionSignatureBehavior"_s.arg(value),
2860 qmlSyntax, pragma->firstSourceLocation());
2863 }
else if (pragma->name == u"ValueTypeBehavior") {
2864 handlePragmaValues(pragma, [
this, pragma](QStringView value) {
2865 if (value == u"Copy") {
2867 }
else if (value == u"Reference") {
2869 }
else if (value == u"Addressable") {
2870 m_scopesById.setValueTypesAreAddressable(
true);
2871 }
else if (value == u"Inaddressable") {
2872 m_scopesById.setValueTypesAreAddressable(
false);
2873 }
else if (value == u"Assertable") {
2874 m_scopesById.setValueTypesAreAssertable(
true);
2875 }
else if (value == u"Inassertable") {
2876 m_scopesById.setValueTypesAreAssertable(
false);
2878 m_logger->log(u"Unknown argument \"%1\" to pragma ValueTypeBehavior"_s.arg(value),
2879 qmlSyntax, pragma->firstSourceLocation());
2887void QQmlJSImportVisitor::throwRecursionDepthError()
2889 m_logger->log(QStringLiteral(
"Maximum statement or expression depth exceeded"),
2890 qmlRecursionDepthErrors, QQmlJS::SourceLocation());
2893bool QQmlJSImportVisitor::visit(QQmlJS::AST::ClassDeclaration *ast)
2895 enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, ast->name.toString(),
2896 ast->firstSourceLocation());
2900void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ClassDeclaration *)
2905bool QQmlJSImportVisitor::visit(QQmlJS::AST::ForStatement *ast)
2907 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"forloop"),
2908 ast->firstSourceLocation());
2912void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ForStatement *)
2917bool QQmlJSImportVisitor::visit(QQmlJS::AST::ForEachStatement *ast)
2919 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"foreachloop"),
2920 ast->firstSourceLocation());
2924void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ForEachStatement *)
2929bool QQmlJSImportVisitor::visit(QQmlJS::AST::Block *ast)
2931 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"block"),
2932 ast->firstSourceLocation());
2934 if (m_pendingSignalHandler.isValid())
2935 flushPendingSignalParameters();
2940void QQmlJSImportVisitor::endVisit(QQmlJS::AST::Block *)
2945bool QQmlJSImportVisitor::visit(QQmlJS::AST::CaseBlock *ast)
2947 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"case"),
2948 ast->firstSourceLocation());
2952void QQmlJSImportVisitor::endVisit(QQmlJS::AST::CaseBlock *)
2957bool QQmlJSImportVisitor::visit(QQmlJS::AST::Catch *catchStatement)
2959 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"catch"),
2960 catchStatement->firstSourceLocation());
2964void QQmlJSImportVisitor::endVisit(QQmlJS::AST::Catch *)
2969bool QQmlJSImportVisitor::visit(QQmlJS::AST::WithStatement *ast)
2971 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"with"),
2972 ast->firstSourceLocation());
2974 m_logger->log(QStringLiteral(
"with statements are strongly discouraged in QML "
2975 "and might cause false positives when analysing unqualified "
2977 qmlWith, ast->firstSourceLocation());
2982void QQmlJSImportVisitor::endVisit(QQmlJS::AST::WithStatement *)
2987bool QQmlJSImportVisitor::visit(QQmlJS::AST::FormalParameterList *fpl)
2989 const auto &boundedNames = fpl->boundNames();
2990 for (
auto const &boundName : boundedNames) {
2992 std::optional<QString> typeName;
2993 if (TypeAnnotation *annotation = boundName.typeAnnotation.data())
2994 if (Type *type = annotation->type)
2995 typeName = type->toString();
2996 safeInsertJSIdentifier(m_currentScope, boundName.id,
2997 { QQmlJSScope::JavaScriptIdentifier::Parameter,
2998 boundName.location, typeName,
false });
3003void QQmlJSImportVisitor::createAttachedAndGroupedScopes(UiQualifiedId *propertyName)
3005 bool needsResolution =
false;
3006 int scopesEnteredCounter = 0;
3008 for (
auto group = propertyName; group->next; group = group->next) {
3009 const QString idName = group->name.toString();
3011 if (idName.isEmpty())
3014 if (group == propertyName && isImportPrefix(idName)) {
3015 prefix = idName + u'.';
3019 const auto scopeKind = idName.front().isUpper() ? QQmlSA::ScopeType::AttachedPropertyScope
3020 : QQmlSA::ScopeType::GroupedPropertyScope;
3023 enterEnvironmentNonUnique(scopeKind, prefix + idName, group->firstSourceLocation());
3025 m_bindings.append(createNonUniqueScopeBinding(m_currentScope, prefix + idName,
3026 group->firstSourceLocation()));
3028 ++scopesEnteredCounter;
3029 needsResolution = needsResolution || !exists;
3034 for (
int i=0; i < scopesEnteredCounter; ++i) {
3039 if (needsResolution) {
3040 QQmlJSScope::resolveTypes(m_currentScope, m_rootScopeImports.contextualTypes(),
3045bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiObjectBinding *uiob)
3049 Q_ASSERT(uiob->qualifiedTypeNameId);
3051 const QString typeName = buildName(uiob->qualifiedTypeNameId);
3052 if (typeName.front().isLower() && typeName.contains(u'.')) {
3053 logLowerCaseImport(typeName, uiob->qualifiedTypeNameId->identifierToken, m_logger);
3056 createAttachedAndGroupedScopes(uiob->qualifiedId);
3058 enterEnvironment(QQmlSA::ScopeType::QMLScope, typeName,
3059 uiob->qualifiedTypeNameId->identifierToken);
3061 m_qmlTypes.append(m_currentScope);
3062 m_objectBindingScopes << m_currentScope;
3066int QQmlJSImportVisitor::openAttachedAndGroupedScopes(UiQualifiedId *propertyName)
3069 int scopesEnteredCounter = 0;
3070 auto group = propertyName;
3071 for (; group->next; group = group->next) {
3072 const QString idName = group->name.toString();
3074 if (idName.isEmpty())
3077 if (group == propertyName && isImportPrefix(idName)) {
3078 prefix = idName + u'.';
3082 const auto scopeKind = idName.front().isUpper() ? QQmlSA::ScopeType::AttachedPropertyScope
3083 : QQmlSA::ScopeType::GroupedPropertyScope;
3085 [[maybe_unused]]
bool exists =
3086 enterEnvironmentNonUnique(scopeKind, prefix + idName, group->firstSourceLocation());
3088 scopesEnteredCounter++;
3092 return scopesEnteredCounter;
3095void QQmlJSImportVisitor::endVisit(QQmlJS::AST::UiObjectBinding *uiob)
3097 QQmlJSScope::resolveTypes(m_currentScope, m_rootScopeImports.contextualTypes(), usedTypes());
3099 const QQmlJSScope::Ptr childScope = m_currentScope;
3102 const int scopesEnteredCounter = openAttachedAndGroupedScopes(uiob->qualifiedId);
3107 auto group = uiob->qualifiedId;
3108 for (; group->next; group = group->next) { }
3109 const QString propertyName = group->name.toString();
3111 if (m_currentScope->isNameDeferred(propertyName)) {
3112 bool foundIds =
false;
3113 QList<QQmlJSScope::ConstPtr> childScopes { childScope };
3115 while (!childScopes.isEmpty()) {
3116 const QQmlJSScope::ConstPtr scope = childScopes.takeFirst();
3117 m_scopesById.possibleIds(
3118 scope, scope, QQmlJSScopesByIdOption::Default,
3119 [&](
const QString &id, QQmlJSScopesById::Confidence confidence) {
3122 Q_UNUSED(confidence);
3124 return QQmlJSScopesById::CallbackResult::StopSearch;
3127 childScopes << scope->childScopes();
3132 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
3134 qmlDeferredPropertyId, uiob->firstSourceLocation());
3138 if (checkCustomParser(m_currentScope)) {
3142 m_pendingPropertyObjectBindings
3143 << PendingPropertyObjectBinding { m_currentScope, childScope, propertyName,
3144 uiob->firstSourceLocation(), uiob->hasOnToken };
3146 QQmlJSMetaPropertyBinding binding(uiob->firstSourceLocation(), propertyName);
3147 if (uiob->hasOnToken) {
3148 if (childScope->hasInterface(u"QQmlPropertyValueInterceptor"_s)) {
3149 binding.setInterceptor(QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope),
3150 QQmlJSScope::ConstPtr(childScope));
3152 binding.setValueSource(QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope),
3153 QQmlJSScope::ConstPtr(childScope));
3156 binding.setObject(QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope),
3157 QQmlJSScope::ConstPtr(childScope));
3159 m_bindings.append(UnfinishedBinding { m_currentScope, [=]() {
return binding; } });
3162 for (
int i = 0; i < scopesEnteredCounter; ++i)
3166bool QQmlJSImportVisitor::visit(ExportDeclaration *)
3168 Q_ASSERT(rootScopeIsValid());
3169 Q_ASSERT(m_exportedRootScope != m_globalScope);
3170 Q_ASSERT(m_currentScope == m_globalScope);
3171 m_currentScope = m_exportedRootScope;
3175void QQmlJSImportVisitor::endVisit(ExportDeclaration *)
3177 Q_ASSERT(rootScopeIsValid());
3178 m_currentScope = m_exportedRootScope->parentScope();
3179 Q_ASSERT(m_currentScope == m_globalScope);
3182bool QQmlJSImportVisitor::visit(ESModule *module)
3184 Q_ASSERT(!rootScopeIsValid());
3185 enterRootScope(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"module"),
3186 module->firstSourceLocation());
3187 m_currentScope->setIsScript(
true);
3188 importBaseModules();
3193void QQmlJSImportVisitor::endVisit(ESModule *)
3195 QQmlJSScope::resolveTypes(m_exportedRootScope, m_rootScopeImports.contextualTypes(),
3199bool QQmlJSImportVisitor::visit(Program *program)
3201 Q_ASSERT(m_globalScope == m_currentScope);
3202 Q_ASSERT(!rootScopeIsValid());
3203 enterRootScope(QQmlSA::ScopeType::JSFunctionScope, u"script"_s, program->firstSourceLocation());
3204 m_exportedRootScope->setIsScript(
true);
3205 importBaseModules();
3209void QQmlJSImportVisitor::endVisit(Program *)
3211 QQmlJSScope::resolveTypes(m_exportedRootScope, m_rootScopeImports.contextualTypes(),
3215bool QQmlJSImportVisitor::visit(QQmlJS::AST::PatternElement *element)
3218 if (element->isVariableDeclaration()) {
3219 QQmlJS::AST::BoundNames names;
3220 element->boundNames(&names);
3221 for (
const auto &name : std::as_const(names)) {
3222 std::optional<QString> typeName;
3223 if (TypeAnnotation *annotation = name.typeAnnotation.data())
3224 if (Type *type = annotation->type)
3225 typeName = type->toString();
3226 using Kind = QQmlJSScope::JavaScriptIdentifier::Kind;
3227 const Kind kind = (element->scope == QQmlJS::AST::VariableScope::Var)
3228 ? Kind::FunctionScoped
3229 : Kind::LexicalScoped;
3230 const QString variableName = name.id;
3231 if (kind == Kind::LexicalScoped) {
3232 const QQmlJS::SourceLocation location = element->firstSourceLocation();
3233 if (
auto previousDeclaration = m_currentScope->ownJSIdentifier(variableName)) {
3234 m_logger->log(
"Identifier '%1' has already been declared"_L1.arg(variableName), qmlSyntax,
3236 m_logger->log(
"Note: previous declaration of '%1' here"_L1.arg(variableName), qmlSyntax,
3237 previousDeclaration->location);
3240 const bool isConstVariable = element->scope == QQmlJS::AST::VariableScope::Const;
3241 const bool couldInsert = safeInsertJSIdentifier(m_currentScope,
3243 { (element->scope == QQmlJS::AST::VariableScope::Var)
3244 ? QQmlJSScope::JavaScriptIdentifier::FunctionScoped
3245 : QQmlJSScope::JavaScriptIdentifier::LexicalScoped,
3246 name.location, typeName,
3256bool QQmlJSImportVisitor::visit(IfStatement *statement)
3258 if (BinaryExpression *binary = cast<BinaryExpression *>(statement->expression)) {
3259 if (binary->op == QSOperator::Assign) {
3261 "Assignment in condition: did you mean to use \"===\" or \"==\" instead of \"=\"?"_L1,
3262 qmlAssignmentInCondition, binary->operatorToken);