157 target->setScopeType(QQmlSA::ScopeType::QMLScope);
158 target->setBaseTypeName(
"$InProcess$"_L1);
159 target->setFilePath(m_logger->filePath());
160 target->setIsComposite(
true);
161 if (!m_importer->registerScope(target)) {
162 qCDebug(lcImportVisitor)
163 <<
"Couldn't register scope into importer: scope will be created multiple times.";
171 target->resetForReparse();
174QQmlJSImportVisitor::QQmlJSImportVisitor(
175 const QQmlJSScope::Ptr &target, QQmlJSImporter *importer, QQmlJSLogger *logger,
176 const QString &implicitImportDirectory,
const QStringList &qmldirFiles)
177 : m_implicitImportDirectory(implicitImportDirectory),
178 m_qmldirFiles(qmldirFiles),
179 m_exportedRootScope(target),
180 m_importer(importer),
183 QQmlJS::ContextualTypes(
184 QQmlJS::ContextualTypes::QML, {}, {},
185 importer->builtinInternalNames().contextualTypes().arrayType()),
190 prepareTargetForVisit(target);
191 registerTargetIntoImporter(target);
194
195
196
197
198
199 auto globalScope = QQmlJSScope::create();
200 globalScope->setInternalName(u"global"_s);
201 globalScope->setScopeType(QQmlSA::ScopeType::JSFunctionScope);
203 QQmlJSScope::JavaScriptIdentifier globalJavaScript = {
204 QQmlJSScope::JavaScriptIdentifier::LexicalScoped, QQmlJS::SourceLocation(), std::nullopt,
208 QV4::Compiler::Codegen::forEachGlobalName([&](QLatin1StringView globalName) {
209 globalScope->insertJSIdentifier(globalName, globalJavaScript);
212 m_globalScope = globalScope;
213 m_currentScope = globalScope;
216QQmlJSImportVisitor::~QQmlJSImportVisitor() =
default;
218void QQmlJSImportVisitor::populateCurrentScope(
219 QQmlJSScope::ScopeType type,
const QString &name,
const QQmlJS::SourceLocation &location)
221 m_currentScope->setScopeType(type);
222 m_currentScope->setIsComposite(
true);
223 m_currentScope->setFilePath(m_logger->filePath());
224 m_currentScope->setSourceLocation(location);
225 setScopeName(m_currentScope, type, name);
226 m_scopesByIrLocation.insert({ location.startLine, location.startColumn }, m_currentScope);
229void QQmlJSImportVisitor::enterRootScope(QQmlJSScope::ScopeType type,
const QString &name,
const QQmlJS::SourceLocation &location)
231 Q_ASSERT(m_currentScope == m_globalScope);
232 QQmlJSScope::reparent(m_currentScope, m_exportedRootScope);
233 m_currentScope = m_exportedRootScope;
234 populateCurrentScope(type, name, location);
237void QQmlJSImportVisitor::enterEnvironment(QQmlJSScope::ScopeType type,
const QString &name,
238 const QQmlJS::SourceLocation &location)
240 QQmlJSScope::Ptr newScope = QQmlJSScope::create();
241 QQmlJSScope::reparent(m_currentScope, newScope);
242 m_currentScope = std::move(newScope);
243 populateCurrentScope(type, name, location);
246bool QQmlJSImportVisitor::enterEnvironmentNonUnique(QQmlJSScope::ScopeType type,
248 const QQmlJS::SourceLocation &location)
250 Q_ASSERT(type == QQmlSA::ScopeType::GroupedPropertyScope
251 || type == QQmlSA::ScopeType::AttachedPropertyScope);
253 const auto pred = [&](
const QQmlJSScope::ConstPtr &s) {
256 return s->internalName() == name;
258 const auto scopes = m_currentScope->childScopes();
261 auto it = std::find_if(scopes.begin(), scopes.end(), pred);
262 if (it == scopes.end()) {
264 enterEnvironment(type, name, location);
268 m_scopesByIrLocation.insert({ location.startLine, location.startColumn }, *it);
269 m_currentScope = *it;
273void QQmlJSImportVisitor::leaveEnvironment()
275 m_currentScope = m_currentScope->parentScope();
278void QQmlJSImportVisitor::warnUnresolvedType(
const QQmlJSScope::ConstPtr &type)
const
280 m_logger->log(QStringLiteral(
"Type %1 is used but it is not resolved")
281 .arg(QQmlJSUtils::getScopeName(type, type->scopeType())),
282 qmlUnresolvedType, type->sourceLocation());
285void QQmlJSImportVisitor::warnMissingPropertyForBinding(
286 const QString &property,
const QQmlJS::SourceLocation &location,
287 const std::optional<QQmlJSFixSuggestion> &fixSuggestion)
289 m_logger->log(QStringLiteral(
"Could not find property \"%1\".").arg(property),
290 qmlMissingProperty, location,
true,
true, fixSuggestion);
298void QQmlJSImportVisitor::resolveAliases()
300 QQueue<QQmlJSScope::Ptr> objects;
301 objects.enqueue(m_exportedRootScope);
303 qsizetype lastRequeueLength = std::numeric_limits<qsizetype>::max();
304 QQueue<QQmlJSScope::Ptr> requeue;
306 while (!objects.isEmpty()) {
307 const QQmlJSScope::Ptr object = objects.dequeue();
308 const auto properties = object->ownProperties();
310 bool doRequeue =
false;
311 for (
const auto &property : properties) {
312 if (!property.isAlias() || !property.type().isNull())
315 QStringList components = property.aliasExpression().split(u'.');
316 QQmlJSMetaProperty targetProperty;
318 bool foundProperty =
false;
321 QQmlJSScope::ConstPtr type = m_scopesById.scope(components.takeFirst(), object);
322 QQmlJSScope::ConstPtr typeScope;
323 if (!type.isNull()) {
324 foundProperty =
true;
331 while (type && !components.isEmpty()) {
332 const QString name = components.takeFirst();
334 if (!type->hasProperty(name)) {
335 foundProperty =
false;
340 const auto target = type->property(name);
341 if (!target.type() && target.isAlias())
344 type = target.type();
345 targetProperty = target;
353 m_logger->log(QStringLiteral(
"Cannot deduce type of alias \"%1\"")
354 .arg(property.propertyName()),
355 qmlMissingType, property.sourceLocation());
357 m_logger->log(QStringLiteral(
"Cannot resolve alias \"%1\"")
358 .arg(property.propertyName()),
359 qmlUnresolvedAlias, property.sourceLocation());
362 Q_ASSERT(property.index() >= 0);
363 object->addOwnProperty(property);
366 QQmlJSMetaProperty newProperty = property;
367 newProperty.setType(type);
369 newProperty.setIsList(targetProperty.isList());
370 newProperty.setIsWritable(targetProperty.isWritable());
371 newProperty.setIsFinal(targetProperty.isFinal());
372 newProperty.setIsPointer(targetProperty.isPointer());
374 const bool onlyId = !property.aliasExpression().contains(u'.');
376 newProperty.setAliasTargetScope(type);
377 newProperty.setAliasTargetName(QStringLiteral(
"id-only-alias"));
379 const auto &ownerScope = QQmlJSScope::ownerOfProperty(
380 typeScope, targetProperty.propertyName()).scope;
381 newProperty.setAliasTargetScope(ownerScope);
382 newProperty.setAliasTargetName(targetProperty.propertyName());
385 if (
const QString internalName = type->internalName(); !internalName.isEmpty())
386 newProperty.setTypeName(internalName);
388 Q_ASSERT(newProperty.index() >= 0);
389 object->addOwnProperty(newProperty);
390 m_aliasDefinitions.append({ object, property.propertyName() });
394 const auto childScopes = object->childScopes();
395 for (
const auto &childScope : childScopes)
396 objects.enqueue(childScope);
399 requeue.enqueue(object);
401 if (objects.isEmpty() && requeue.size() < lastRequeueLength) {
402 lastRequeueLength = requeue.size();
403 objects.swap(requeue);
407 while (!requeue.isEmpty()) {
408 const QQmlJSScope::Ptr object = requeue.dequeue();
409 const auto properties = object->ownProperties();
410 for (
const auto &property : properties) {
411 if (!property.isAlias() || property.type())
413 m_logger->log(QStringLiteral(
"Alias \"%1\" is part of an alias cycle")
414 .arg(property.propertyName()),
415 qmlAliasCycle, property.sourceLocation());
420void QQmlJSImportVisitor::resolveGroupProperties()
422 QQueue<QQmlJSScope::Ptr> objects;
423 objects.enqueue(m_exportedRootScope);
425 while (!objects.isEmpty()) {
426 const QQmlJSScope::Ptr object = objects.dequeue();
427 const auto childScopes = object->childScopes();
428 for (
const auto &childScope : childScopes) {
429 if (mayBeUnresolvedGroupedProperty(childScope)) {
430 const QString name = childScope->internalName();
431 if (object->isNameDeferred(name)) {
432 const QQmlJSScope::ConstPtr deferred = m_scopesById.scope(name, childScope);
433 if (!deferred.isNull()) {
434 QQmlJSScope::resolveGroup(
435 childScope, deferred, m_rootScopeImports.contextualTypes(),
438 }
else if (
const QQmlJSScope::ConstPtr propType = object->property(name).type()) {
439 QQmlJSScope::resolveGroup(
440 childScope, propType, m_rootScopeImports.contextualTypes(),
444 objects.enqueue(childScope);
449QString QQmlJSImportVisitor::implicitImportDirectory(
450 const QString &localFile, QQmlJSResourceFileMapper *mapper)
453 const auto resource = mapper->entry(
454 QQmlJSResourceFileMapper::localFileFilter(localFile));
455 if (resource.isValid()) {
456 return resource.resourcePath.contains(u'/')
457 ? (u':' + resource.resourcePath.left(
458 resource.resourcePath.lastIndexOf(u'/') + 1))
459 : QStringLiteral(
":/");
463 return QFileInfo(localFile).canonicalPath() + u'/';
466void QQmlJSImportVisitor::processImportWarnings(
467 const QString &what,
const QList<QQmlJS::DiagnosticMessage> &warnings,
468 const QQmlJS::SourceLocation &srcLocation)
470 if (warnings.isEmpty())
473 QList<QQmlJS::DiagnosticMessage> importWarnings = warnings;
476 auto fileSelectorWarningsIt = std::partition(importWarnings.begin(), importWarnings.end(),
477 [](
const QQmlJS::DiagnosticMessage &message) {
478 return message.type != QtMsgType::QtInfoMsg;
480 if (fileSelectorWarningsIt != importWarnings.end()) {
481 m_logger->log(QStringLiteral(
"Warnings occurred while importing %1:").arg(what), qmlImportFileSelector,
483 m_logger->processMessages(QSpan(fileSelectorWarningsIt, importWarnings.end()),
484 qmlImportFileSelector, srcLocation);
487 if (fileSelectorWarningsIt == importWarnings.begin())
490 m_logger->log(QStringLiteral(
"Warnings occurred while importing %1:").arg(what), qmlImport,
492 m_logger->processMessages(QSpan(importWarnings.begin(), fileSelectorWarningsIt), qmlImport,
496void QQmlJSImportVisitor::importBaseModules()
498 Q_ASSERT(m_rootScopeImports.isEmpty());
499 m_rootScopeImports = m_importer->importHardCodedBuiltins();
501 const QQmlJS::SourceLocation invalidLoc;
502 const auto types = m_rootScopeImports.types();
503 for (
auto it = types.keyBegin(), end = types.keyEnd(); it != end; it++)
504 addImportWithLocation(*it, invalidLoc,
false);
506 if (!m_qmldirFiles.isEmpty())
507 m_rootScopeImports.addWarnings(m_importer->importQmldirs(m_qmldirFiles));
511 if (!m_logger->filePath().endsWith(u".qmltypes"_s)) {
512 m_rootScopeImports.add(m_importer->importDirectory(m_implicitImportDirectory));
517 if (QQmlJSResourceFileMapper *mapper = m_importer->resourceFileMapper()) {
518 const QStringList resourcePaths = mapper->resourcePaths(QQmlJSResourceFileMapper::Filter {
519 m_logger->filePath(), QStringList(), QQmlJSResourceFileMapper::Resource });
520 for (
const QString &path : resourcePaths) {
521 const qsizetype lastSlash = path.lastIndexOf(QLatin1Char(
'/'));
524 m_rootScopeImports.add(m_importer->importDirectory(path.first(lastSlash)));
529 processImportWarnings(QStringLiteral(
"base modules"), m_rootScopeImports.warnings());
532bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiProgram *)
536 if (
auto elementName = QFileInfo(m_logger->filePath()).baseName();
537 !elementName.isEmpty() && elementName[0].isUpper()) {
538 m_rootScopeImports.setType(elementName, { m_exportedRootScope, QTypeRevision {} });
544void QQmlJSImportVisitor::endVisit(UiProgram *)
546 for (
const auto &scope : std::as_const(m_objectBindingScopes)) {
547 breakInheritanceCycles(scope);
548 checkDeprecation(scope);
551 for (
const auto &scope : std::as_const(m_objectDefinitionScopes)) {
552 if (m_pendingDefaultProperties.contains(scope))
554 breakInheritanceCycles(scope);
555 checkDeprecation(scope);
558 const auto &keys = m_pendingDefaultProperties.keys();
559 for (
const auto &scope : keys) {
560 breakInheritanceCycles(scope);
561 checkDeprecation(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 auto unusedImports = m_importLocations;
579 for (
const QString &type : std::as_const(m_usedTypes)) {
580 const auto &importLocations = m_importTypeLocationMap.values(type);
581 for (
const auto &importLocation : importLocations)
582 unusedImports.remove(importLocation);
585 if (unusedImports.isEmpty())
589 const auto &imports = m_importStaticModuleLocationMap.values();
590 for (
const QQmlJS::SourceLocation &import : imports)
591 unusedImports.remove(import);
593 for (
const auto &import : unusedImports) {
594 m_logger->log(QString::fromLatin1(
"Unused import"), qmlUnusedImports, import);
597 populateRuntimeFunctionIndicesForDocument();
602 ExpressionStatement *expr = cast<ExpressionStatement *>(statement);
604 if (!statement || !expr->expression)
607 switch (expr->expression->kind) {
608 case Node::Kind_StringLiteral:
609 return cast<StringLiteral *>(expr->expression)->value.toString();
610 case Node::Kind_NumericLiteral:
611 return cast<NumericLiteral *>(expr->expression)->value;
617QList<QQmlJSAnnotation> QQmlJSImportVisitor::parseAnnotations(QQmlJS::AST::UiAnnotationList *list)
620 QList<QQmlJSAnnotation> annotationList;
622 for (UiAnnotationList *item = list; item !=
nullptr; item = item->next) {
623 UiAnnotation *annotation = item->annotation;
625 QQmlJSAnnotation qqmljsAnnotation;
626 qqmljsAnnotation.name = buildName(annotation->qualifiedTypeNameId);
628 for (UiObjectMemberList *memberItem = annotation->initializer->members; memberItem !=
nullptr; memberItem = memberItem->next) {
629 switch (memberItem->member->kind) {
630 case Node::Kind_UiScriptBinding: {
631 auto *scriptBinding = QQmlJS::AST::cast<UiScriptBinding*>(memberItem->member);
632 qqmljsAnnotation.bindings[buildName(scriptBinding->qualifiedId)]
633 = bindingToVariant(scriptBinding->statement);
642 annotationList.append(qqmljsAnnotation);
645 return annotationList;
648void QQmlJSImportVisitor::setAllBindings()
650 using Key = std::pair<QQmlJSScope::ConstPtr, QString>;
651 QHash<Key, QQmlJS::SourceLocation> foundBindings;
653 for (
auto it = m_bindings.cbegin(); it != m_bindings.cend(); ++it) {
655 const QQmlJSScope::Ptr type = it->owner;
656 if (!checkTypeResolved(type))
665 if (!type->isFullyResolved())
667 auto binding = it->create();
668 if (!binding.isValid())
670 type->addOwnPropertyBinding(binding, it->specifier);
673 if (binding.hasInterceptor() || binding.hasValueSource())
675 const QString propertyName = binding.propertyName();
676 QQmlJSMetaProperty property = type->property(propertyName);
679
680
681
682
683
684 if (!property.isValid())
688 if (property.isList())
691 const Key key = std::make_pair(type, propertyName);
692 auto sourceLocationIt = foundBindings.constFind(key);
693 if (sourceLocationIt == foundBindings.constEnd()) {
694 foundBindings.insert(key, binding.sourceLocation());
698 const QQmlJS::SourceLocation location = binding.sourceLocation();
699 m_logger->log(
"Duplicate binding on property '%1'"_L1.arg(propertyName),
700 qmlDuplicatePropertyBinding, location);
701 m_logger->log(
"Note: previous binding on '%1' here"_L1.arg(propertyName),
702 qmlDuplicatePropertyBinding, *sourceLocationIt,
true,
true, {},
707void QQmlJSImportVisitor::processDefaultProperties()
709 for (
auto it = m_pendingDefaultProperties.constBegin();
710 it != m_pendingDefaultProperties.constEnd(); ++it) {
711 QQmlJSScope::ConstPtr parentScope = it.key();
714 if (checkCustomParser(parentScope))
718
719
720
721
722
723
724
725
726
728 parentScope = parentScope->baseType();
730 const QString defaultPropertyName =
731 parentScope ? parentScope->defaultPropertyName() : QString();
733 if (defaultPropertyName.isEmpty()) {
736 bool isComponent =
false;
737 for (QQmlJSScope::ConstPtr s = parentScope; s; s = s->baseType()) {
738 if (s->internalName() == QStringLiteral(
"QQmlComponent")) {
745 m_logger->log(QStringLiteral(
"Cannot assign to non-existent default property"),
746 qmlMissingProperty, it.value().constFirst()->sourceLocation());
752 const QQmlJSMetaProperty defaultProp = parentScope->property(defaultPropertyName);
753 auto propType = defaultProp.type();
754 const auto handleUnresolvedDefaultProperty = [&](
const QQmlJSScope::ConstPtr &) {
756 m_logger->log(QStringLiteral(
"Property \"%1\" has incomplete type \"%2\". You may be "
757 "missing an import.")
758 .arg(defaultPropertyName)
759 .arg(defaultProp.typeName()),
760 qmlUnresolvedType, it.value().constFirst()->sourceLocation());
763 const auto assignToUnknownProperty = [&]() {
766 for (
const QQmlJSScope::Ptr &scope : std::as_const(*it))
767 scope->setAssignedToUnknownProperty(
true);
770 if (propType.isNull()) {
771 handleUnresolvedDefaultProperty(propType);
772 assignToUnknownProperty();
776 if (it.value().size() > 1
777 && !defaultProp.isList()
778 && !propType->isListProperty()) {
780 QStringLiteral(
"Cannot assign multiple objects to a default non-list property"),
781 qmlNonListProperty, it.value().constFirst()->sourceLocation());
784 if (!checkTypeResolved(propType, handleUnresolvedDefaultProperty)) {
785 assignToUnknownProperty();
789 for (
const QQmlJSScope::Ptr &scope : std::as_const(*it)) {
790 if (!checkTypeResolved(scope))
795 if (propType->canAssign(scope)) {
796 scope->setIsWrappedInImplicitComponent(
797 causesImplicitComponentWrapping(defaultProp, scope));
801 m_logger->log(QStringLiteral(
"Cannot assign to default property of incompatible type"),
802 qmlIncompatibleType, scope->sourceLocation());
807void QQmlJSImportVisitor::processPropertyTypes()
809 for (
const PendingPropertyType &type : std::as_const(m_pendingPropertyTypes)) {
810 Q_ASSERT(type.scope->hasOwnProperty(type.name));
812 auto property = type.scope->ownProperty(type.name);
814 if (
const auto propertyType = QQmlJSScope::findType(
815 property.typeName(), m_rootScopeImports.contextualTypes()).scope) {
816 property.setType(propertyType);
817 type.scope->addOwnProperty(property);
819 QString msg = property.typeName() +
' '_L1 + wasNotFound +
' '_L1 + didYouAddAllImports;
820 if (property.typeName() ==
"list"_L1)
821 msg +=
" list is not a type. It requires an element type argument (eg. list<int>)"_L1;
822 m_logger->log(msg, qmlImport, type.location);
827void QQmlJSImportVisitor::processMethodTypes()
829 const auto isEnumUsedAsType = [&](QStringView typeName,
const QQmlJS::SourceLocation &loc) {
830 if (typeName ==
"enum"_L1) {
834 const auto split = typeName.tokenize(u'.').toContainer<QVarLengthArray<QStringView, 4>>();
835 if (split.size() != 2)
838 const QStringView scopeName = split[0];
839 const QStringView enumName = split[1];
841 if (
auto scope = QQmlJSScope::findType(scopeName.toString(),
842 m_rootScopeImports.contextualTypes()).scope) {
843 if (scope->enumeration(enumName.toString()).isValid()) {
845 "QML enumerations are not types. Use int, or use double if the enum's underlying type does not fit into int."_L1,
846 qmlEnumsAreNotTypes, loc);
853 for (
const auto &method : std::as_const(m_pendingMethodTypeAnnotations)) {
854 for (
auto [it, end] = method.scope->mutableOwnMethodsRange(method.methodName); it != end; ++it) {
855 const auto [parameterBegin, parameterEnd] = it->mutableParametersRange();
856 for (
auto parameter = parameterBegin; parameter != parameterEnd; ++parameter) {
857 const int parameterIndex = parameter - parameterBegin;
858 if (isEnumUsedAsType(parameter->typeName(), method.locations[parameterIndex]))
860 if (
const auto parameterType = QQmlJSScope::findType(
861 parameter->typeName(), m_rootScopeImports.contextualTypes()).scope) {
862 parameter->setType({ parameterType });
865 u"\"%1\" was not found for the type of parameter \"%2\" in method \"%3\"."_s
866 .arg(parameter->typeName(), parameter->name(), it->methodName()),
867 qmlUnresolvedType, method.locations[parameter - parameterBegin]);
871 if (isEnumUsedAsType(it->returnTypeName(), method.locations.last()))
873 if (
const auto returnType = QQmlJSScope::findType(
874 it->returnTypeName(), m_rootScopeImports.contextualTypes()).scope) {
875 it->setReturnType({ returnType });
877 m_logger->log(u"\"%1\" was not found for the return type of method \"%2\"."_s.arg(
878 it->returnTypeName(), it->methodName()),
879 qmlUnresolvedType, method.locations.last());
887
888
889
890
891
892
893
897 for (QStringView propertyName: possiblyGroupedProperty.tokenize(u".")) {
898 property = scope->property(propertyName.toString());
899 if (property.isValid())
900 scope = property.type();
907void QQmlJSImportVisitor::processPropertyBindingObjects()
909 QSet<std::pair<QQmlJSScope::Ptr, QString>> foundLiterals;
917 QSet<std::pair<QQmlJSScope::Ptr, QString>> visited;
918 for (
const PendingPropertyObjectBinding &objectBinding :
919 std::as_const(m_pendingPropertyObjectBindings)) {
921 const auto uniqueBindingId = std::make_pair(objectBinding.scope, objectBinding.name);
922 if (visited.contains(uniqueBindingId))
924 visited.insert(uniqueBindingId);
926 auto [existingBindingsBegin, existingBindingsEnd] =
927 uniqueBindingId.first->ownPropertyBindings(uniqueBindingId.second);
928 const bool hasLiteralBindings =
929 std::any_of(existingBindingsBegin, existingBindingsEnd,
930 [](
const QQmlJSMetaPropertyBinding &x) {
return x.hasLiteral(); });
931 if (hasLiteralBindings)
932 foundLiterals.insert(uniqueBindingId);
936 QSet<std::pair<QQmlJSScope::Ptr, QString>> foundObjects;
937 QSet<std::pair<QQmlJSScope::Ptr, QString>> foundInterceptors;
938 QSet<std::pair<QQmlJSScope::Ptr, QString>> foundValueSources;
940 for (
const PendingPropertyObjectBinding &objectBinding :
941 std::as_const(m_pendingPropertyObjectBindings)) {
942 const QString propertyName = objectBinding.name;
943 QQmlJSScope::Ptr childScope = objectBinding.childScope;
945 const auto assignToUnknownProperty = [&]() {
948 childScope->setAssignedToUnknownProperty(
true);
952 if (!checkTypeResolved(objectBinding.scope)) {
953 assignToUnknownProperty();
957 QQmlJSMetaProperty property = resolveProperty(propertyName, objectBinding.scope);
959 if (!property.isValid()) {
960 warnMissingPropertyForBinding(propertyName, objectBinding.location);
963 const auto handleUnresolvedProperty = [&](
const QQmlJSScope::ConstPtr &) {
965 m_logger->log(QStringLiteral(
"Property \"%1\" has incomplete type \"%2\". You may be "
966 "missing an import.")
968 .arg(property.typeName()),
969 qmlUnresolvedType, objectBinding.location);
972 if (property.type().isNull()) {
973 assignToUnknownProperty();
974 handleUnresolvedProperty(property.type());
979 if (!checkTypeResolved(property.type(), handleUnresolvedProperty)) {
980 assignToUnknownProperty();
982 }
else if (!checkTypeResolved(childScope)) {
986 if (!objectBinding.onToken && !property.type()->canAssign(childScope)) {
987 m_logger->log(QStringLiteral(
"Cannot assign object of type %1 to %2")
988 .arg(QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope))
989 .arg(property.typeName()),
990 qmlIncompatibleType, childScope->sourceLocation());
994 childScope->setIsWrappedInImplicitComponent(
995 causesImplicitComponentWrapping(property, childScope));
998 const auto uniqueBindingId = std::make_pair(objectBinding.scope, objectBinding.name);
999 const QString typeName = QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope);
1001 auto isConditionalBinding = [&]() ->
bool {
1003
1004
1005
1006
1007 return childScope->hasOwnPropertyBindings(u"enabled"_s)
1008 || childScope->hasOwnPropertyBindings(u"when"_s)
1009 || childScope->hasOwnPropertyBindings(u"running"_s);
1012 if (objectBinding.onToken) {
1013 if (childScope->hasInterface(QStringLiteral(
"QQmlPropertyValueInterceptor"))) {
1014 if (foundInterceptors.contains(uniqueBindingId)) {
1015 if (!isConditionalBinding()) {
1016 m_logger->log(QStringLiteral(
"Duplicate interceptor on property \"%1\"")
1018 qmlDuplicatePropertyBinding, objectBinding.location);
1021 foundInterceptors.insert(uniqueBindingId);
1023 }
else if (childScope->hasInterface(QStringLiteral(
"QQmlPropertyValueSource"))) {
1024 if (foundValueSources.contains(uniqueBindingId)) {
1025 if (!isConditionalBinding()) {
1026 m_logger->log(QStringLiteral(
"Duplicate value source on property \"%1\"")
1028 qmlDuplicatePropertyBinding, objectBinding.location);
1030 }
else if (foundObjects.contains(uniqueBindingId)
1031 || foundLiterals.contains(uniqueBindingId)) {
1032 if (!isConditionalBinding()) {
1033 m_logger->log(QStringLiteral(
"Cannot combine value source and binding on "
1036 qmlDuplicatePropertyBinding, objectBinding.location);
1039 foundValueSources.insert(uniqueBindingId);
1042 m_logger->log(QStringLiteral(
"On-binding for property \"%1\" has wrong type \"%2\"")
1045 qmlIncompatibleType, objectBinding.location);
1048 if (foundValueSources.contains(uniqueBindingId)) {
1049 if (!isConditionalBinding()) {
1051 QStringLiteral(
"Cannot combine value source and binding on property \"%1\"")
1053 qmlDuplicatePropertyBinding, objectBinding.location);
1056 foundObjects.insert(uniqueBindingId);
1064 QList<QQmlJSScope::ConstPtr> descendants;
1065 std::vector<QQmlJSScope::ConstPtr> toVisit;
1067 toVisit.push_back(scope);
1068 while (!toVisit.empty()) {
1069 const QQmlJSScope::ConstPtr s = toVisit.back();
1075 toVisit.insert(toVisit.end(), s->childScopesBegin(), s->childScopesEnd());
1082void QQmlJSImportVisitor::populatePropertyAliases()
1084 for (
const auto &alias : std::as_const(m_aliasDefinitions)) {
1085 const auto &[aliasScope, aliasName] = alias;
1086 if (aliasScope.isNull())
1089 auto property = aliasScope->ownProperty(aliasName);
1090 if (!property.isValid() || !property.aliasTargetScope())
1093 Property target(property.aliasTargetScope(), property.aliasTargetName());
1096 m_propertyAliases[target].append(alias);
1097 property = target.scope->property(target.name);
1098 target = Property(property.aliasTargetScope(), property.aliasTargetName());
1099 }
while (property.isAlias());
1103void QQmlJSImportVisitor::checkRequiredProperties()
1105 for (
const auto &required : std::as_const(m_requiredProperties)) {
1106 if (!required.scope->hasProperty(required.name)) {
1108 QStringLiteral(
"Property \"%1\" was marked as required but does not exist.")
1109 .arg(required.name),
1110 qmlRequired, required.location);
1114 const auto compType = m_rootScopeImports.type(u"Component"_s).scope;
1115 const auto isInComponent = [&](
const QQmlJSScope::ConstPtr &requiredScope) {
1116 for (
auto s = requiredScope; s; s = s->parentScope()) {
1117 if (s->isWrappedInImplicitComponent() || s->baseType() == compType)
1123 const auto scopeRequiresProperty = [&](
const QQmlJSScope::ConstPtr &requiredScope,
1124 const QString &propName,
1125 const QQmlJSScope::ConstPtr &descendant) {
1126 if (!requiredScope->isPropertyLocallyRequired(propName))
1130 return QQmlJSScope::ownerOfProperty(requiredScope, propName).scope
1131 == QQmlJSScope::ownerOfProperty(descendant, propName).scope;
1134 const auto requiredHasBinding = [](
const QList<QQmlJSScope::ConstPtr> &scopesToSearch,
1135 const QQmlJSScope::ConstPtr &owner,
1136 const QString &propName) {
1137 for (
const auto &scope : scopesToSearch) {
1138 if (scope->property(propName).isAlias())
1140 const auto &[begin, end] = scope->ownPropertyBindings(propName);
1141 for (
auto it = begin; it != end; ++it) {
1143 const bool isRelevantBinding = QQmlSA::isRegularBindingType(it->bindingType())
1144 || it->bindingType() == QQmlSA::BindingType::Interceptor
1145 || it->bindingType() == QQmlSA::BindingType::ValueSource;
1146 if (!isRelevantBinding)
1148 if (QQmlJSScope::ownerOfProperty(scope, propName).scope == owner)
1156 const auto requiredUsedInRootAlias = [&](
const QQmlJSScope::ConstPtr &requiredScope,
1157 const QString &propName) {
1158 const Property target(requiredScope, propName);
1161 const auto allAliasesToTargetIt = m_propertyAliases.constFind(target);
1162 if (allAliasesToTargetIt == m_propertyAliases.constEnd())
1169 allAliasesToTargetIt->constBegin(), allAliasesToTargetIt->constEnd(),
1170 [](
const Property &property) {
return property.scope->isFileRootComponent(); });
1173 const auto requiredSetThroughAlias = [&](
const QList<QQmlJSScope::ConstPtr> &scopesToSearch,
1174 const QQmlJSScope::ConstPtr &requiredScope,
1175 const QString &propName) {
1176 const auto &propertyDefScope = QQmlJSScope::ownerOfProperty(requiredScope, propName);
1177 const auto &propertyAliases = m_propertyAliases[{ propertyDefScope.scope, propName }];
1178 for (
const auto &alias : propertyAliases) {
1179 for (
const auto &s : scopesToSearch) {
1180 if (s->hasOwnPropertyBindings(alias.name))
1187 const auto warn = [
this](
const QQmlJSScope::ConstPtr &prevRequiredScope,
1188 const QString &propName,
const QQmlJSScope::ConstPtr &defScope,
1189 const QQmlJSScope::ConstPtr &requiredScope,
1190 const QQmlJSScope::ConstPtr &descendant) {
1191 const auto &propertyScope = QQmlJSScope::ownerOfProperty(requiredScope, propName).scope;
1192 const QString propertyScopeName = !propertyScope.isNull()
1193 ? QQmlJSUtils::getScopeName(propertyScope, QQmlSA::ScopeType::QMLScope)
1196 std::optional<QQmlJSFixSuggestion> suggestion;
1198 QString message = QStringLiteral(
"Component is missing required property %1 from %2")
1200 .arg(propertyScopeName);
1201 if (requiredScope != descendant) {
1202 const QString requiredScopeName = prevRequiredScope
1203 ? QQmlJSUtils::getScopeName(prevRequiredScope, QQmlSA::ScopeType::QMLScope)
1206 if (!prevRequiredScope.isNull()) {
1207 if (
auto sourceScope = prevRequiredScope->baseType()) {
1208 suggestion = QQmlJSFixSuggestion{
1209 "%1:%2:%3: Property marked as required in %4."_L1
1210 .arg(sourceScope->filePath())
1211 .arg(sourceScope->sourceLocation().startLine)
1212 .arg(sourceScope->sourceLocation().startColumn)
1213 .arg(requiredScopeName),
1214 sourceScope->sourceLocation()
1218 if (sourceScope->isComposite())
1219 suggestion->setFilename(sourceScope->filePath());
1222 message +=
" (marked as required by %1)"_L1.arg(requiredScopeName);
1226 m_logger->log(message, qmlRequired, defScope->sourceLocation(),
true,
true, suggestion);
1229 populatePropertyAliases();
1231 for (
const auto &[_, defScope] : m_scopesByIrLocation.asKeyValueRange()) {
1232 if (defScope->isFileRootComponent() || defScope->isInlineComponent()
1233 || defScope->componentRootStatus() != QQmlJSScope::IsComponentRoot::No
1234 || defScope->scopeType() != QQmlSA::ScopeType::QMLScope) {
1238 QList<QQmlJSScope::ConstPtr> scopesToSearch;
1239 for (QQmlJSScope::ConstPtr scope = defScope; scope; scope = scope->baseType()) {
1240 const auto descendants = QList<QQmlJSScope::ConstPtr>()
1241 << scope << qmlScopeDescendants(scope);
1242 for (
const QQmlJSScope::ConstPtr &descendant : std::as_const(descendants)) {
1245 if (descendant != scope && descendant->isInlineComponent())
1247 scopesToSearch << descendant;
1248 const auto ownProperties = descendant->ownProperties();
1249 for (
auto propertyIt = ownProperties.constBegin();
1250 propertyIt != ownProperties.constEnd(); ++propertyIt) {
1251 const QString propName = propertyIt.key();
1252 if (descendant->hasOwnPropertyBindings(propName))
1255 QQmlJSScope::ConstPtr prevRequiredScope;
1256 for (
const QQmlJSScope::ConstPtr &requiredScope : std::as_const(scopesToSearch)) {
1257 if (isInComponent(requiredScope))
1260 if (!scopeRequiresProperty(requiredScope, propName, descendant)) {
1261 prevRequiredScope = requiredScope;
1265 if (requiredHasBinding(scopesToSearch, descendant, propName))
1268 if (requiredUsedInRootAlias(requiredScope, propName))
1271 if (requiredSetThroughAlias(scopesToSearch, requiredScope, propName))
1274 warn(prevRequiredScope, propName, defScope, requiredScope, descendant);
1275 prevRequiredScope = requiredScope;
1283void QQmlJSImportVisitor::processPropertyBindings()
1285 for (
auto it = m_propertyBindings.constBegin(); it != m_propertyBindings.constEnd(); ++it) {
1286 QQmlJSScope::Ptr scope = it.key();
1287 for (
auto &[visibilityScope, location, name] : it.value()) {
1288 if (!scope->hasProperty(name) && !m_logger->isDisabled()) {
1292 if (checkCustomParser(scope))
1296 std::optional<QQmlJSFixSuggestion> fixSuggestion;
1298 for (QQmlJSScope::ConstPtr baseScope = scope; !baseScope.isNull();
1299 baseScope = baseScope->baseType()) {
1300 if (
auto suggestion = QQmlJSUtils::didYouMean(
1301 name, baseScope->ownProperties().keys(), location);
1302 suggestion.has_value()) {
1303 fixSuggestion = suggestion;
1308 warnMissingPropertyForBinding(name, location, fixSuggestion);
1312 const auto property = scope->property(name);
1313 if (!property.type()) {
1314 m_logger->log(QStringLiteral(
"No type found for property \"%1\". This may be due "
1315 "to a missing import statement or incomplete "
1318 qmlMissingType, location);
1321 const auto &annotations = property.annotations();
1323 const auto deprecationAnn =
1324 std::find_if(annotations.cbegin(), annotations.cend(),
1325 [](
const QQmlJSAnnotation &ann) {
return ann.isDeprecation(); });
1327 if (deprecationAnn != annotations.cend()) {
1328 const auto deprecation = deprecationAnn->deprecation();
1330 QString message = QStringLiteral(
"Binding on deprecated property \"%1\"")
1331 .arg(property.propertyName());
1333 if (!deprecation.reason.isEmpty())
1334 message.append(QStringLiteral(
" (Reason: %1)").arg(deprecation.reason));
1336 m_logger->log(message, qmlDeprecated, location);
1342void QQmlJSImportVisitor::checkSignal(
1343 const QQmlJSScope::ConstPtr &signalScope,
const QQmlJS::SourceLocation &location,
1344 const QString &handlerName,
const QStringList &handlerParameters)
1346 const auto signal = QQmlSignalNames::handlerNameToSignalName(handlerName);
1348 std::optional<QQmlJSMetaMethod> signalMethod;
1349 const auto setSignalMethod = [&](
const QQmlJSScope::ConstPtr &scope,
const QString &name) {
1350 const auto methods = scope->methods(name, QQmlJSMetaMethodType::Signal);
1351 if (!methods.isEmpty())
1352 signalMethod = methods[0];
1355 if (signal.has_value()) {
1356 if (signalScope->hasMethod(*signal)) {
1357 setSignalMethod(signalScope, *signal);
1358 }
else if (
auto p = QQmlJSUtils::propertyFromChangedHandler(signalScope, handlerName)) {
1363 if (
auto notify = p->notify(); !notify.isEmpty()) {
1364 setSignalMethod(signalScope, notify);
1366 Q_ASSERT(!p->bindable().isEmpty());
1367 signalMethod = QQmlJSMetaMethod {};
1372 if (!signalMethod.has_value()) {
1377 if (signalScope->baseTypeName() == QStringLiteral(
"Connections")) {
1379 u"Implicitly defining \"%1\" as signal handler in Connections is deprecated. "
1380 u"Create a function instead: \"function %2(%3) { ... }\"."_s.arg(
1381 handlerName, handlerName, handlerParameters.join(u", ")),
1382 qmlUnqualified, location,
true,
true);
1386 auto baseType = QQmlJSScope::nonCompositeBaseType(signalScope);
1387 if (baseType && baseType->hasCustomParser())
1391 QStringLiteral(
"no matching signal found for handler \"%1\"").arg(handlerName),
1392 qmlUnqualified, location,
true,
true);
1396 const auto signalParameters = signalMethod->parameters();
1397 QHash<QString, qsizetype> parameterNameIndexes;
1399 for (
int i = 0, end = signalParameters.size(); i < end; i++) {
1400 auto &p = signalParameters[i];
1401 parameterNameIndexes[p.name()] = i;
1403 auto signalName = [&]() {
1405 return u" called %1"_s.arg(*signal);
1408 auto type = p.type();
1411 "Type %1 of parameter %2 in signal%3 was not found, but is required to compile "
1413 p.typeName(), p.name(), signalName(),
1414 handlerName, didYouAddAllImports),
1415 qmlSignalParameters, location);
1419 if (type->isComposite())
1427 auto parameterName = [&]() {
1428 if (p.name().isEmpty())
1430 return u" called %1"_s.arg(p.name());
1432 switch (type->accessSemantics()) {
1433 case QQmlJSScope::AccessSemantics::Reference:
1435 m_logger->log(QStringLiteral(
"Type %1 of parameter%2 in signal%3 should be "
1436 "passed by pointer to be able to compile %4. ")
1437 .arg(p.typeName(), parameterName(), signalName(),
1439 qmlSignalParameters, location);
1441 case QQmlJSScope::AccessSemantics::Value:
1442 case QQmlJSScope::AccessSemantics::Sequence:
1446 "Type %1 of parameter%2 in signal%3 should be passed by "
1447 "value or const reference to be able to compile %4. ")
1448 .arg(p.typeName(), parameterName(), signalName(),
1450 qmlSignalParameters, location);
1452 case QQmlJSScope::AccessSemantics::None:
1454 QStringLiteral(
"Type %1 of parameter%2 in signal%3 required by the "
1455 "compilation of %4 cannot be used. ")
1456 .arg(p.typeName(), parameterName(), signalName(), handlerName),
1457 qmlSignalParameters, location);
1462 if (handlerParameters.size() > signalParameters.size()) {
1463 m_logger->log(QStringLiteral(
"Signal handler for \"%2\" has more formal"
1464 " parameters than the signal it handles.")
1466 qmlSignalParameters, location);
1470 for (qsizetype i = 0, end = handlerParameters.size(); i < end; i++) {
1471 const QStringView handlerParameter = handlerParameters.at(i);
1472 auto it = parameterNameIndexes.constFind(handlerParameter.toString());
1473 if (it == parameterNameIndexes.constEnd())
1475 const qsizetype j = *it;
1480 m_logger->log(QStringLiteral(
"Parameter %1 to signal handler for \"%2\""
1481 " is called \"%3\". The signal has a parameter"
1482 " of the same name in position %4.")
1484 .arg(handlerName, handlerParameter)
1486 qmlSignalParameters, location);
1490void QQmlJSImportVisitor::addDefaultProperties()
1492 QQmlJSScope::ConstPtr parentScope = m_currentScope->parentScope();
1493 if (m_currentScope == m_exportedRootScope || parentScope->isArrayScope()
1494 || m_currentScope->isInlineComponent())
1497 m_pendingDefaultProperties[m_currentScope->parentScope()] << m_currentScope;
1499 if (checkCustomParser(parentScope))
1503
1504
1505
1506
1507
1508
1509
1510
1511
1513 parentScope = parentScope->baseType();
1515 const QString defaultPropertyName =
1516 parentScope ? parentScope->defaultPropertyName() : QString();
1518 if (defaultPropertyName.isEmpty())
1523 QQmlJSMetaPropertyBinding binding(m_currentScope->sourceLocation(), defaultPropertyName);
1524 binding.setObject(QQmlJSUtils::getScopeName(m_currentScope, QQmlSA::ScopeType::QMLScope),
1525 QQmlJSScope::ConstPtr(m_currentScope));
1526 m_bindings.append(UnfinishedBinding { m_currentScope->parentScope(), [=]() {
return binding; },
1527 QQmlJSScope::UnnamedPropertyTarget });
1530void QQmlJSImportVisitor::breakInheritanceCycles(
const QQmlJSScope::Ptr &originalScope)
1532 QList<QQmlJSScope::ConstPtr> scopes;
1533 for (QQmlJSScope::ConstPtr scope = originalScope; scope;) {
1534 if (scopes.contains(scope)) {
1535 QString inheritenceCycle;
1536 for (
const auto &seen : std::as_const(scopes)) {
1537 inheritenceCycle.append(seen->baseTypeName());
1538 inheritenceCycle.append(QLatin1String(
" -> "));
1540 inheritenceCycle.append(scopes.first()->baseTypeName());
1542 const QString message = QStringLiteral(
"%1 is part of an inheritance cycle: %2")
1543 .arg(scope->internalName(), inheritenceCycle);
1544 m_logger->log(message, qmlInheritanceCycle, scope->sourceLocation());
1545 originalScope->clearBaseType();
1546 originalScope->setBaseTypeError(message);
1550 scopes.append(scope);
1552 const auto newScope = scope->baseType();
1553 if (newScope.isNull()) {
1554 const QString error = scope->baseTypeError();
1555 const QString name = scope->baseTypeName();
1556 if (!error.isEmpty()) {
1557 m_logger->log(error, qmlImport, scope->sourceLocation(),
true,
true);
1558 }
else if (!name.isEmpty() && !m_unresolvedTypes.hasSeen(scope)
1559 && !m_logger->isDisabled()) {
1561 name +
' '_L1 + wasNotFound +
' '_L1 + didYouAddAllImports,
1562 qmlImport, scope->sourceLocation(),
true,
true,
1563 QQmlJSUtils::didYouMean(scope->baseTypeName(),
1564 m_rootScopeImports.types().keys(),
1565 scope->sourceLocation()));
1573void QQmlJSImportVisitor::checkDeprecation(
const QQmlJSScope::ConstPtr &originalScope)
1575 for (QQmlJSScope::ConstPtr scope = originalScope; scope; scope = scope->baseType()) {
1576 for (
const QQmlJSAnnotation &annotation : scope->annotations()) {
1577 if (annotation.isDeprecation()) {
1578 QQQmlJSDeprecation deprecation = annotation.deprecation();
1581 QStringLiteral(
"Type \"%1\" is deprecated").arg(scope->internalName());
1583 if (!deprecation.reason.isEmpty())
1584 message.append(QStringLiteral(
" (Reason: %1)").arg(deprecation.reason));
1586 m_logger->log(message, qmlDeprecated, originalScope->sourceLocation());
1592void QQmlJSImportVisitor::checkGroupedAndAttachedScopes(QQmlJSScope::ConstPtr scope)
1596 if (checkCustomParser(scope))
1599 auto children = scope->childScopes();
1600 while (!children.isEmpty()) {
1601 auto childScope = children.takeFirst();
1602 const auto type = childScope->scopeType();
1604 case QQmlSA::ScopeType::GroupedPropertyScope:
1605 case QQmlSA::ScopeType::AttachedPropertyScope:
1606 if (!childScope->baseType()) {
1607 m_logger->log(QStringLiteral(
"unknown %1 property scope %2.")
1608 .arg(type == QQmlSA::ScopeType::GroupedPropertyScope
1609 ? QStringLiteral(
"grouped")
1610 : QStringLiteral(
"attached"),
1611 childScope->internalName()),
1612 qmlUnqualified, childScope->sourceLocation());
1614 children.append(childScope->childScopes());
1622bool QQmlJSImportVisitor::checkCustomParser(
const QQmlJSScope::ConstPtr &scope)
1624 return scope->isInCustomParserParent();
1627void QQmlJSImportVisitor::flushPendingSignalParameters()
1629 const QQmlJSMetaSignalHandler handler = m_signalHandlers[m_pendingSignalHandler];
1630 for (
const QString ¶meter : handler.signalParameters) {
1631 safeInsertJSIdentifier(m_currentScope, parameter,
1632 { QQmlJSScope::JavaScriptIdentifier::Injected,
1633 m_pendingSignalHandler, std::nullopt,
false });
1635 m_pendingSignalHandler = QQmlJS::SourceLocation();
1639
1640
1641
1642
1643
1644
1645QQmlJSMetaMethod::RelativeFunctionIndex
1646QQmlJSImportVisitor::addFunctionOrExpression(
const QQmlJSScope::ConstPtr &scope,
1647 const QString &name)
1649 auto &array = m_functionsAndExpressions[scope];
1650 array.emplaceBack(name);
1657 for (
const auto &function : std::as_const(m_functionStack))
1658 m_innerFunctions[function]++;
1659 m_functionStack.push({ scope, name });
1661 return QQmlJSMetaMethod::RelativeFunctionIndex {
int(array.size() - 1) };
1665
1666
1667
1668
1669
1670
1671
1672
1673void QQmlJSImportVisitor::forgetFunctionExpression(
const QString &name)
1675 auto nameToVerify = name.isEmpty() ? u"<anon>"_s : name;
1676 Q_UNUSED(nameToVerify);
1677 Q_ASSERT(!m_functionStack.isEmpty());
1678 Q_ASSERT(m_functionStack.top().name == nameToVerify);
1679 m_functionStack.pop();
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694int QQmlJSImportVisitor::synthesizeCompilationUnitRuntimeFunctionIndices(
1695 const QQmlJSScope::Ptr &scope,
int count)
const
1697 const auto suitableScope = [](
const QQmlJSScope::Ptr &scope) {
1698 const auto type = scope->scopeType();
1699 return type == QQmlSA::ScopeType::QMLScope
1700 || type == QQmlSA::ScopeType::GroupedPropertyScope
1701 || type == QQmlSA::ScopeType::AttachedPropertyScope;
1704 if (!suitableScope(scope))
1707 auto it = m_functionsAndExpressions.constFind(scope);
1708 if (it == m_functionsAndExpressions.cend())
1711 const auto &functionsAndExpressions = *it;
1712 for (
const QString &functionOrExpression : functionsAndExpressions) {
1713 scope->addOwnRuntimeFunctionIndex(
1714 static_cast<QQmlJSMetaMethod::AbsoluteFunctionIndex>(count));
1731 count += m_innerFunctions.value({ scope, functionOrExpression }, 0);
1737void QQmlJSImportVisitor::populateRuntimeFunctionIndicesForDocument()
const
1740 const auto synthesize = [&](
const QQmlJSScope::Ptr ¤t) {
1741 count = synthesizeCompilationUnitRuntimeFunctionIndices(current, count);
1743 QQmlJSUtils::traverseFollowingQmlIrObjectStructure(m_exportedRootScope, synthesize);
1746bool QQmlJSImportVisitor::visit(QQmlJS::AST::ExpressionStatement *ast)
1748 if (m_pendingSignalHandler.isValid()) {
1749 enterEnvironment(QQmlSA::ScopeType::SignalHandlerFunctionScope, u"signalhandler"_s,
1750 ast->firstSourceLocation());
1751 flushPendingSignalParameters();
1756void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ExpressionStatement *)
1758 if (m_currentScope->scopeType() == QQmlSA::ScopeType::SignalHandlerFunctionScope) {
1765 const QQmlJS::SourceLocation &srcLocation);
1768 QQmlJSLogger *logger)
1770 QStringView namespaceName{ superType };
1771 namespaceName = namespaceName.first(namespaceName.indexOf(u'.'));
1772 logger->log(u"Namespace '%1' of '%2' must start with an upper case letter."_s.arg(namespaceName)
1774 qmlUncreatableType, location,
true,
true);
1777bool QQmlJSImportVisitor::visit(UiObjectDefinition *definition)
1779 const QString superType = buildName(definition->qualifiedTypeNameId);
1781 const bool isRoot = !rootScopeIsValid();
1782 Q_ASSERT(!superType.isEmpty());
1787 const qsizetype indexOfTypeName = superType.lastIndexOf(u'.');
1788 const bool looksLikeGroupedProperty = superType.front().isLower();
1790 if (indexOfTypeName != -1 && looksLikeGroupedProperty) {
1791 logLowerCaseImport(superType, definition->qualifiedTypeNameId->identifierToken,
1795 if (!looksLikeGroupedProperty) {
1797 enterEnvironment(QQmlSA::ScopeType::QMLScope, superType,
1798 definition->firstSourceLocation());
1800 enterRootScope(QQmlSA::ScopeType::QMLScope, superType,
1801 definition->firstSourceLocation());
1802 m_currentScope->setIsRootFileComponentFlag(
true);
1803 m_currentScope->setIsSingleton(m_rootIsSingleton);
1806 const QTypeRevision revision = m_currentScope->baseTypeRevision();
1807 if (
auto base = m_currentScope->baseType(); base) {
1808 if (isRoot && base->internalName() == u"QQmlComponent") {
1809 m_logger->log(u"Qml top level type cannot be 'Component'."_s, qmlTopLevelComponent,
1810 definition->qualifiedTypeNameId->identifierToken,
true,
true);
1812 if (base->isSingleton() && m_currentScope->isComposite()) {
1813 m_logger->log(u"Singleton Type %1 is not creatable."_s.arg(
1814 m_currentScope->baseTypeName()),
1815 qmlUncreatableType, definition->qualifiedTypeNameId->identifierToken,
1818 }
else if (!base->isCreatable()) {
1820 m_logger->log(u"Type %1 is not creatable."_s.arg(m_currentScope->baseTypeName()),
1821 qmlUncreatableType, definition->qualifiedTypeNameId->identifierToken,
1825 if (m_nextIsInlineComponent) {
1826 Q_ASSERT(std::holds_alternative<InlineComponentNameType>(m_currentRootName));
1827 const QString &name = std::get<InlineComponentNameType>(m_currentRootName);
1828 m_currentScope->setIsInlineComponent(
true);
1829 m_currentScope->setInlineComponentName(name);
1830 m_currentScope->setOwnModuleName(m_exportedRootScope->moduleName());
1831 m_rootScopeImports.setType(name, { m_currentScope, revision });
1832 m_nextIsInlineComponent =
false;
1835 addDefaultProperties();
1836 Q_ASSERT(m_currentScope->scopeType() == QQmlSA::ScopeType::QMLScope);
1837 m_qmlTypes.append(m_currentScope);
1839 m_objectDefinitionScopes << m_currentScope;
1841 enterEnvironmentNonUnique(QQmlSA::ScopeType::GroupedPropertyScope, superType,
1842 definition->firstSourceLocation());
1843 m_bindings.append(createNonUniqueScopeBinding(m_currentScope, superType,
1844 definition->firstSourceLocation()));
1845 QQmlJSScope::resolveTypes(
1846 m_currentScope, m_rootScopeImports.contextualTypes(), &m_usedTypes);
1849 m_currentScope->setAnnotations(parseAnnotations(definition->annotations));
1854void QQmlJSImportVisitor::endVisit(UiObjectDefinition *)
1856 QQmlJSScope::resolveTypes(m_currentScope, m_rootScopeImports.contextualTypes(), &m_usedTypes);
1860bool QQmlJSImportVisitor::visit(UiInlineComponent *component)
1862 if (!std::holds_alternative<RootDocumentNameType>(m_currentRootName)) {
1863 m_logger->log(u"Nested inline components are not supported"_s, qmlSyntax,
1864 component->firstSourceLocation());
1868 const auto it = m_seenInlineComponents.constFind(component->name);
1869 if (it != m_seenInlineComponents.cend()) {
1870 m_logger->log(
"Duplicate inline component '%1'"_L1.arg(it.key()),
1871 qmlDuplicateInlineComponent, component->firstSourceLocation());
1872 m_logger->log(
"Note: previous component named '%1' here"_L1.arg(it.key()),
1873 qmlDuplicateInlineComponent, it.value(),
true,
true, {},
1874 component->firstSourceLocation().startLine);
1876 m_seenInlineComponents[component->name] = component->firstSourceLocation();
1879 m_nextIsInlineComponent =
true;
1880 m_currentRootName = component->name.toString();
1884void QQmlJSImportVisitor::endVisit(UiInlineComponent *component)
1886 m_currentRootName = RootDocumentNameType();
1887 if (m_nextIsInlineComponent) {
1888 m_logger->log(u"Inline component declaration must be followed by a typename"_s,
1889 qmlSyntax, component->firstSourceLocation());
1891 m_nextIsInlineComponent =
false;
1894bool QQmlJSImportVisitor::visit(UiPublicMember *publicMember)
1896 switch (publicMember->type) {
1897 case UiPublicMember::Signal: {
1898 const QString signalName = publicMember->name.toString();
1899 UiParameterList *param = publicMember->parameters;
1900 QQmlJSMetaMethod method;
1901 method.setMethodType(QQmlJSMetaMethodType::Signal);
1902 method.setReturnTypeName(QStringLiteral(
"void"));
1903 method.setMethodName(signalName);
1904 method.setSourceLocation(combine(publicMember->firstSourceLocation(),
1905 publicMember->lastSourceLocation()));
1907 method.addParameter(
1908 QQmlJSMetaParameter(
1909 param->name.toString(),
1910 param->type ? param->type->toString() : QString()
1912 param = param->next;
1914 m_currentScope->addOwnMethod(method);
1917 case UiPublicMember::Property: {
1918 const QString propertyName = publicMember->name.toString();
1919 QString typeName = buildName(publicMember->memberType);
1920 if (typeName.contains(u'.') && typeName.front().isLower()) {
1921 logLowerCaseImport(typeName, publicMember->typeToken, m_logger);
1925 const bool isAlias = (typeName == u"alias"_s);
1927 auto tryParseAlias = [&]() {
1929 if (!publicMember->statement) {
1930 m_logger->log(QStringLiteral(
"Invalid alias expression - an initializer is needed."),
1931 qmlSyntax, publicMember->memberType->firstSourceLocation());
1934 const auto expression = cast<ExpressionStatement *>(publicMember->statement);
1935 auto node = expression ? expression->expression :
nullptr;
1936 auto fex = cast<FieldMemberExpression *>(node);
1939 aliasExpr.prepend(u'.' + fex->name.toString());
1940 fex = cast<FieldMemberExpression *>(node);
1943 if (
const auto idExpression = cast<IdentifierExpression *>(node)) {
1944 aliasExpr.prepend(idExpression->name.toString());
1948 m_logger->log(QStringLiteral(
"Invalid alias expression. Only IDs and field "
1949 "member expressions can be aliased."),
1950 qmlSyntax, publicMember->statement->firstSourceLocation());
1955 if (m_rootScopeImports.hasType(typeName)
1956 && !m_rootScopeImports.type(typeName).scope.isNull()) {
1957 if (m_importTypeLocationMap.contains(typeName))
1958 m_usedTypes.insert(typeName);
1961 QQmlJSMetaProperty prop;
1962 prop.setPropertyName(propertyName);
1963 prop.setIsList(publicMember->typeModifier == QLatin1String(
"list"));
1964 prop.setIsWritable(!publicMember->isReadonly());
1965 prop.setIsFinal(publicMember->isFinal());
1966 prop.setIsVirtual(publicMember->isVirtual());
1967 prop.setIsOverride(publicMember->isOverride());
1968 prop.setAliasExpression(aliasExpr);
1969 prop.setSourceLocation(
1970 combine(publicMember->firstSourceLocation(), publicMember->colonToken));
1972 isAlias ? QQmlJSScope::ConstPtr() : m_rootScopeImports.type(typeName).scope;
1974 prop.setType(prop.isList() ? type->listType() : type);
1975 const QString internalName = type->internalName();
1976 prop.setTypeName(internalName.isEmpty() ? typeName : internalName);
1977 }
else if (!isAlias) {
1978 m_pendingPropertyTypes << PendingPropertyType { m_currentScope, prop.propertyName(),
1979 publicMember->firstSourceLocation() };
1980 prop.setTypeName(typeName);
1982 prop.setAnnotations(parseAnnotations(publicMember->annotations));
1983 if (publicMember->isDefaultMember())
1984 m_currentScope->setOwnDefaultPropertyName(prop.propertyName());
1985 prop.setIndex(m_currentScope->ownProperties().size());
1986 m_currentScope->insertPropertyIdentifier(prop);
1987 if (publicMember->isRequired())
1988 m_currentScope->setPropertyLocallyRequired(prop.propertyName(),
true);
1990 BindingExpressionParseResult parseResult = BindingExpressionParseResult::Invalid;
1994 parseBindingExpression(publicMember->name.toString(), publicMember->statement,
2000 if (parseResult == BindingExpressionParseResult::Script) {
2001 Q_ASSERT(!m_savedBindingOuterScope);
2002 m_savedBindingOuterScope = m_currentScope;
2003 enterEnvironment(QQmlSA::ScopeType::BindingFunctionScope, QStringLiteral(
"binding"),
2004 publicMember->statement->firstSourceLocation());
2014void QQmlJSImportVisitor::endVisit(UiPublicMember *publicMember)
2016 if (m_savedBindingOuterScope) {
2017 m_currentScope = m_savedBindingOuterScope;
2018 m_savedBindingOuterScope = {};
2020 forgetFunctionExpression(publicMember->name.toString());
2024bool QQmlJSImportVisitor::visit(UiRequired *required)
2026 const QString name = required->name.toString();
2028 m_requiredProperties << RequiredProperty { m_currentScope, name,
2029 required->firstSourceLocation() };
2031 m_currentScope->setPropertyLocallyRequired(name,
true);
2035void QQmlJSImportVisitor::visitFunctionExpressionHelper(QQmlJS::AST::FunctionExpression *fexpr)
2037 using namespace QQmlJS::AST;
2038 auto name = fexpr->name.toString();
2039 if (!name.isEmpty()) {
2040 QQmlJSMetaMethod method(name);
2041 method.setMethodType(QQmlJSMetaMethodType::Method);
2042 method.setSourceLocation(combine(fexpr->firstSourceLocation(), fexpr->lastSourceLocation()));
2044 if (!m_pendingMethodAnnotations.isEmpty()) {
2045 method.setAnnotations(m_pendingMethodAnnotations);
2046 m_pendingMethodAnnotations.clear();
2050 const bool parseTypes = m_scopesById.signaturesAreEnforced();
2052 bool formalsFullyTyped = parseTypes;
2053 bool anyFormalTyped =
false;
2054 PendingMethodTypeAnnotations pending{ m_currentScope, name, {} };
2057 for (
auto formals = fexpr->formals; formals; formals = formals->next) {
2058 PatternElement *e = formals->element;
2061 if (e->typeAnnotation && (e->bindingTarget || e->initializer))
2062 m_logger->log(
"Type annotations on default parameters are not supported"_L1,
2064 combine(e->firstSourceLocation(), e->lastSourceLocation()));
2067 if (
const auto *formals = parseTypes ? fexpr->formals :
nullptr) {
2068 const auto parameters = formals->formals();
2069 for (
const auto ¶meter : parameters) {
2070 const QString type = parameter.typeAnnotation
2071 ? parameter.typeAnnotation->type->toString()
2073 if (type.isEmpty()) {
2074 formalsFullyTyped =
false;
2075 method.addParameter(QQmlJSMetaParameter(parameter.id, QStringLiteral(
"var")));
2076 pending.locations.emplace_back();
2078 anyFormalTyped =
true;
2079 method.addParameter(QQmlJSMetaParameter(parameter.id, type));
2080 pending.locations.append(
2081 combine(parameter.typeAnnotation->firstSourceLocation(),
2082 parameter.typeAnnotation->lastSourceLocation()));
2088 method.setIsJavaScriptFunction(!formalsFullyTyped);
2094 if (parseTypes && fexpr->typeAnnotation) {
2095 method.setReturnTypeName(fexpr->typeAnnotation->type->toString());
2096 pending.locations.append(combine(fexpr->typeAnnotation->firstSourceLocation(),
2097 fexpr->typeAnnotation->lastSourceLocation()));
2098 }
else if (anyFormalTyped) {
2099 method.setReturnTypeName(QStringLiteral(
"void"));
2101 method.setReturnTypeName(QStringLiteral(
"var"));
2104 const auto &locs = pending.locations;
2105 if (std::any_of(locs.cbegin(), locs.cend(), [](
const auto &loc) {
return loc.isValid(); }))
2106 m_pendingMethodTypeAnnotations << pending;
2108 method.setJsFunctionIndex(addFunctionOrExpression(m_currentScope, method.methodName()));
2110 if (m_currentScope->scopeType() != QQmlSA::ScopeType::QMLScope) {
2112 const QQmlJS::SourceLocation functionLocation = fexpr->identifierToken.isValid()
2113 ? fexpr->identifierToken
2114 : fexpr->functionToken;
2115 safeInsertJSIdentifier(m_currentScope, name,
2116 { QQmlJSScope::JavaScriptIdentifier::LexicalScoped,
2117 functionLocation, method.returnTypeName(),
2120 m_currentScope->addOwnMethod(method);
2122 enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, name, fexpr->firstSourceLocation());
2124 addFunctionOrExpression(m_currentScope, QStringLiteral(
"<anon>"));
2125 enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, QStringLiteral(
"<anon>"),
2126 fexpr->firstSourceLocation());
2130bool QQmlJSImportVisitor::visit(QQmlJS::AST::FunctionExpression *fexpr)
2132 visitFunctionExpressionHelper(fexpr);
2136void QQmlJSImportVisitor::endVisit(QQmlJS::AST::FunctionExpression *fexpr)
2138 forgetFunctionExpression(fexpr->name.toString());
2142bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiSourceElement *srcElement)
2144 m_pendingMethodAnnotations = parseAnnotations(srcElement->annotations);
2148bool QQmlJSImportVisitor::visit(QQmlJS::AST::FunctionDeclaration *fdecl)
2150 if (!fdecl->name.isEmpty()) {
2151 const QString name = fdecl->name.toString();
2152 if (
auto previousDeclaration = m_currentScope->ownJSIdentifier(name)) {
2153 m_logger->log(
"Identifier '%1' has already been declared"_L1.arg(name), qmlSyntax,
2154 fdecl->identifierToken);
2155 m_logger->log(
"Note: previous declaration of '%1' here"_L1.arg(name), qmlSyntax,
2156 previousDeclaration->location);
2159 visitFunctionExpressionHelper(fdecl);
2163void QQmlJSImportVisitor::endVisit(QQmlJS::AST::FunctionDeclaration *fdecl)
2165 forgetFunctionExpression(fdecl->name.toString());
2169bool QQmlJSImportVisitor::visit(QQmlJS::AST::ClassExpression *ast)
2171 QQmlJSMetaProperty prop;
2172 prop.setPropertyName(ast->name.toString());
2173 m_currentScope->addOwnProperty(prop);
2174 enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, ast->name.toString(),
2175 ast->firstSourceLocation());
2179void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ClassExpression *)
2185 QQmlJS::AST::ArgumentList *args)
2187 QStringView contextString;
2188 QStringView mainString;
2189 QStringView commentString;
2190 auto registerContextString = [&](QStringView string) {
2191 contextString = string;
2194 auto registerMainString = [&](QStringView string) {
2195 mainString = string;
2198 auto registerCommentString = [&](QStringView string) {
2199 commentString = string;
2202 auto finalizeBinding = [&](QV4::CompiledData::Binding::Type type,
2203 QV4::CompiledData::TranslationData data) {
2204 if (type == QV4::CompiledData::Binding::Type_Translation) {
2205 binding.setTranslation(mainString, commentString, contextString, data.number);
2206 }
else if (type == QV4::CompiledData::Binding::Type_TranslationById) {
2207 binding.setTranslationId(mainString, data.number);
2209 binding.setStringLiteral(mainString);
2212 QmlIR::tryGeneratingTranslationBindingBase(
2214 registerMainString, registerCommentString, registerContextString, finalizeBinding);
2217QQmlJSImportVisitor::BindingExpressionParseResult
2218QQmlJSImportVisitor::parseBindingExpression(
2219 const QString &name,
const QQmlJS::AST::Statement *statement,
2220 const UiPublicMember *associatedPropertyDefinition)
2222 if (statement ==
nullptr)
2223 return BindingExpressionParseResult::Invalid;
2225 const auto *exprStatement = cast<
const ExpressionStatement *>(statement);
2227 if (exprStatement ==
nullptr) {
2228 QQmlJS::SourceLocation location = statement->firstSourceLocation();
2230 if (
const auto *block = cast<
const Block *>(statement); block && block->statements) {
2231 location = block->statements->firstSourceLocation();
2234 QQmlJSMetaPropertyBinding binding(location, name);
2235 binding.setScriptBinding(addFunctionOrExpression(m_currentScope, name),
2236 QQmlSA::ScriptBindingKind::PropertyBinding, ScriptValue_Function);
2237 m_bindings.append(UnfinishedBinding {
2239 [binding = std::move(binding)]() {
return binding; }
2241 return BindingExpressionParseResult::Script;
2244 auto expr = exprStatement->expression;
2245 QQmlJSMetaPropertyBinding binding(
2246 combine(expr->firstSourceLocation(), expr->lastSourceLocation()),
2249 ScriptBindingValueType scriptBindingValuetype = ScriptValue_Unknown;
2251 switch (expr->kind) {
2252 case Node::Kind_TrueLiteral:
2253 binding.setBoolLiteral(
true);
2255 case Node::Kind_FalseLiteral:
2256 binding.setBoolLiteral(
false);
2258 case Node::Kind_NullExpression:
2259 binding.setNullLiteral();
2261 case Node::Kind_IdentifierExpression: {
2262 auto idExpr = QQmlJS::AST::cast<QQmlJS::AST::IdentifierExpression *>(expr);
2264 if (idExpr->name == u"undefined")
2265 scriptBindingValuetype = ScriptValue_Undefined;
2268 case Node::Kind_FunctionDeclaration:
2269 case Node::Kind_FunctionExpression:
2270 case Node::Kind_Block: {
2271 scriptBindingValuetype = ScriptValue_Function;
2274 case Node::Kind_NumericLiteral:
2275 binding.setNumberLiteral(cast<NumericLiteral *>(expr)->value);
2277 case Node::Kind_StringLiteral:
2278 binding.setStringLiteral(cast<StringLiteral *>(expr)->value);
2280 case Node::Kind_RegExpLiteral:
2281 binding.setRegexpLiteral(cast<RegExpLiteral *>(expr)->pattern);
2283 case Node::Kind_TemplateLiteral: {
2284 auto templateLit = QQmlJS::AST::cast<QQmlJS::AST::TemplateLiteral *>(expr);
2285 Q_ASSERT(templateLit);
2286 if (templateLit->hasNoSubstitution) {
2287 binding.setStringLiteral(templateLit->value);
2289 binding.setScriptBinding(addFunctionOrExpression(m_currentScope, name),
2290 QQmlSA::ScriptBindingKind::PropertyBinding);
2291 for (QQmlJS::AST::TemplateLiteral *l = templateLit; l; l = l->next) {
2292 if (QQmlJS::AST::ExpressionNode *expression = l->expression)
2293 expression->accept(
this);
2299 if (QQmlJS::AST::UnaryMinusExpression *unaryMinus = QQmlJS::AST::cast<QQmlJS::AST::UnaryMinusExpression *>(expr)) {
2300 if (QQmlJS::AST::NumericLiteral *lit = QQmlJS::AST::cast<QQmlJS::AST::NumericLiteral *>(unaryMinus->expression))
2301 binding.setNumberLiteral(-lit->value);
2302 }
else if (QQmlJS::AST::CallExpression *call = QQmlJS::AST::cast<QQmlJS::AST::CallExpression *>(expr)) {
2303 if (QQmlJS::AST::IdentifierExpression *base = QQmlJS::AST::cast<QQmlJS::AST::IdentifierExpression *>(call->base))
2304 handleTranslationBinding(binding, base->name, call->arguments);
2309 if (!binding.isValid()) {
2311 binding.setScriptBinding(addFunctionOrExpression(m_currentScope, name),
2312 QQmlSA::ScriptBindingKind::PropertyBinding,
2313 scriptBindingValuetype);
2315 m_bindings.append(UnfinishedBinding { m_currentScope, [=]() {
return binding; } });
2318 if (binding.bindingType() == QQmlSA::BindingType::Translation
2319 || binding.bindingType() == QQmlSA::BindingType::TranslationById) {
2320 return BindingExpressionParseResult::Translation;
2322 if (!QQmlJSMetaPropertyBinding::isLiteralBinding(binding.bindingType()))
2323 return BindingExpressionParseResult::Script;
2325 if (associatedPropertyDefinition)
2326 handleLiteralBinding(binding, associatedPropertyDefinition);
2328 return BindingExpressionParseResult::Literal;
2331bool QQmlJSImportVisitor::isImportPrefix(QString prefix)
const
2333 if (prefix.isEmpty() || !prefix.front().isUpper())
2336 return m_rootScopeImports.isNullType(prefix);
2339void QQmlJSImportVisitor::handleIdDeclaration(QQmlJS::AST::UiScriptBinding *scriptBinding)
2341 if (m_currentScope->scopeType() != QQmlJSScope::ScopeType::QMLScope) {
2342 m_logger->log(u"id declarations are only allowed in objects"_s, qmlSyntax,
2343 scriptBinding->statement->firstSourceLocation());
2346 const auto *statement = cast<ExpressionStatement *>(scriptBinding->statement);
2348 m_logger->log(u"id must be followed by an identifier"_s, qmlSyntax,
2349 scriptBinding->statement->firstSourceLocation());
2352 const QString name = [&]() {
2353 if (
const auto *idExpression = cast<IdentifierExpression *>(statement->expression))
2354 return idExpression->name.toString();
2355 else if (
const auto *idString = cast<StringLiteral *>(statement->expression)) {
2356 m_logger->log(u"ids do not need quotation marks"_s, qmlSyntaxIdQuotation,
2357 idString->firstSourceLocation());
2358 return idString->value.toString();
2360 m_logger->log(u"Failed to parse id"_s, qmlSyntax,
2361 statement->expression->firstSourceLocation());
2365 if (!name.isEmpty() && !name.front().isLower() && name.front() != u'_') {
2366 m_logger->log(u"Id must start with a lower case letter or an '_'"_s, qmlSyntax,
2367 statement->expression->firstSourceLocation());
2370 m_currentScope->setIdSourceLocation(combine(scriptBinding->statement->firstSourceLocation(),
2371 scriptBinding->statement->lastSourceLocation()));
2372 if (m_scopesById.existsAnywhereInDocument(name)) {
2375 breakInheritanceCycles(m_currentScope);
2376 m_scopesById.possibleScopes(
2377 name, m_currentScope, Default,
2378 [&](
const QQmlJSScope::ConstPtr &otherScopeWithID,
2379 QQmlJSScopesById::Confidence confidence) {
2381 Q_UNUSED(confidence);
2383 auto otherLocation = otherScopeWithID->sourceLocation();
2387 m_logger->log(u"Found a duplicated id. id %1 was first declared at %2:%3"_s.arg(
2388 name, QString::number(otherLocation.startLine),
2389 QString::number(otherLocation.startColumn)),
2390 qmlSyntaxDuplicateIds,
2391 scriptBinding->firstSourceLocation());
2392 return QQmlJSScopesById::CallbackResult::ContinueSearch;
2395 if (!name.isEmpty())
2396 m_scopesById.insert(name, m_currentScope);
2399void QQmlJSImportVisitor::handleLiteralBinding(
const QQmlJSMetaPropertyBinding &binding,
2400 const UiPublicMember *associatedPropertyDefinition)
2404 Q_UNUSED(associatedPropertyDefinition);
2408
2409
2410
2411
2412
2415 const QQmlJS::SourceLocation &srcLocation)
2417 const auto createBinding = [=]() {
2418 const QQmlJSScope::ScopeType type = scope->scopeType();
2425 const auto propertyBindings = scope->parentScope()->ownPropertyBindings(name);
2426 const bool alreadyHasBinding =
std::any_of(propertyBindings.first, propertyBindings.second,
2427 [&](
const QQmlJSMetaPropertyBinding &binding) {
2428 return binding.bindingType() == bindingType;
2430 if (alreadyHasBinding)
2431 return QQmlJSMetaPropertyBinding(QQmlJS::SourceLocation {});
2434 if (type == QQmlSA::ScopeType::GroupedPropertyScope)
2435 binding.setGroupBinding(
static_cast<QSharedPointer<QQmlJSScope>>(scope));
2437 binding.setAttachedBinding(
static_cast<QSharedPointer<QQmlJSScope>>(scope));
2440 return { scope->parentScope(), createBinding };
2443bool QQmlJSImportVisitor::visit(UiScriptBinding *scriptBinding)
2445 Q_ASSERT(!m_savedBindingOuterScope);
2446 Q_ASSERT(!m_thisScriptBindingIsJavaScript);
2447 m_savedBindingOuterScope = m_currentScope;
2448 const auto id = scriptBinding->qualifiedId;
2449 if (!id->next && id->name == QLatin1String(
"id")) {
2450 handleIdDeclaration(scriptBinding);
2457 for (; group->next; group = group->next) {
2458 const QString name = group->name.toString();
2462 if (group == id && isImportPrefix(name)) {
2463 prefix = name + u'.';
2467 const bool isAttachedProperty = name.front().isUpper();
2468 if (isAttachedProperty) {
2470 enterEnvironmentNonUnique(QQmlSA::ScopeType::AttachedPropertyScope, prefix + name,
2471 group->firstSourceLocation());
2474 enterEnvironmentNonUnique(QQmlSA::ScopeType::GroupedPropertyScope, prefix + name,
2475 group->firstSourceLocation());
2477 m_bindings.append(createNonUniqueScopeBinding(m_currentScope, prefix + name,
2478 group->firstSourceLocation()));
2483 const auto name = group->name.toString();
2487 const auto signal = QQmlSignalNames::handlerNameToSignalName(name);
2489 if (!signal.has_value() || m_currentScope->hasProperty(name)) {
2490 m_propertyBindings[m_currentScope].append(
2491 { m_savedBindingOuterScope, group->firstSourceLocation(), name });
2493 auto result = parseBindingExpression(name, scriptBinding->statement);
2494 m_thisScriptBindingIsJavaScript = (result == BindingExpressionParseResult::Script);
2496 const auto statement = scriptBinding->statement;
2497 QStringList signalParameters;
2499 if (ExpressionStatement *expr = cast<ExpressionStatement *>(statement)) {
2500 if (FunctionExpression *func = expr->expression->asFunctionDefinition()) {
2501 for (FormalParameterList *formal = func->formals; formal; formal = formal->next)
2502 signalParameters << formal->element->bindingIdentifier.toString();
2506 QQmlJSMetaMethod scopeSignal;
2507 const auto methods = m_currentScope->methods(*signal, QQmlJSMetaMethodType::Signal);
2508 if (!methods.isEmpty())
2509 scopeSignal = methods[0];
2511 const auto firstSourceLocation = statement->firstSourceLocation();
2512 bool hasMultilineStatementBody =
2513 statement->lastSourceLocation().startLine > firstSourceLocation.startLine;
2514 m_pendingSignalHandler = firstSourceLocation;
2515 m_signalHandlers.insert(firstSourceLocation,
2516 { scopeSignal.parameterNames(), hasMultilineStatementBody });
2520 const auto index = addFunctionOrExpression(m_currentScope, name);
2521 const auto createBinding = [
2523 scope = m_currentScope,
2524 signalName = *signal,
2527 firstSourceLocation,
2528 groupLocation = group->firstSourceLocation(),
2529 signalParameters]() {
2531 Q_ASSERT(scope->isFullyResolved());
2532 QQmlSA::ScriptBindingKind kind = QQmlSA::ScriptBindingKind::Invalid;
2533 const auto methods = scope->methods(signalName, QQmlJSMetaMethodType::Signal);
2534 if (!methods.isEmpty()) {
2535 kind = QQmlSA::ScriptBindingKind::SignalHandler;
2536 checkSignal(scope, groupLocation, name, signalParameters);
2537 }
else if (QQmlJSUtils::propertyFromChangedHandler(scope, name).has_value()) {
2538 kind = QQmlSA::ScriptBindingKind::ChangeHandler;
2539 checkSignal(scope, groupLocation, name, signalParameters);
2540 }
else if (scope->hasProperty(name)) {
2543 kind = QQmlSA::ScriptBindingKind::PropertyBinding;
2544 m_signalHandlers.remove(firstSourceLocation);
2547 checkSignal(scope, groupLocation, name, signalParameters);
2550 QQmlJSMetaPropertyBinding binding(firstSourceLocation, name);
2551 binding.setScriptBinding(index, kind, ScriptValue_Function);
2554 m_bindings.append(UnfinishedBinding { m_currentScope, createBinding });
2555 m_thisScriptBindingIsJavaScript =
true;
2561 while (m_currentScope->scopeType() == QQmlSA::ScopeType::GroupedPropertyScope
2562 || m_currentScope->scopeType() == QQmlSA::ScopeType::AttachedPropertyScope) {
2567 enterEnvironment(QQmlSA::ScopeType::SignalHandlerFunctionScope,
2569 scriptBinding->statement->firstSourceLocation());
2571 enterEnvironment(QQmlSA::ScopeType::BindingFunctionScope,
2573 scriptBinding->statement->firstSourceLocation());
2579void QQmlJSImportVisitor::endVisit(UiScriptBinding *)
2581 if (m_savedBindingOuterScope) {
2582 m_currentScope = m_savedBindingOuterScope;
2583 m_savedBindingOuterScope = {};
2589 if (m_thisScriptBindingIsJavaScript) {
2590 m_thisScriptBindingIsJavaScript =
false;
2591 Q_ASSERT(!m_functionStack.isEmpty());
2592 m_functionStack.pop();
2596bool QQmlJSImportVisitor::visit(UiArrayBinding *arrayBinding)
2598 enterEnvironment(QQmlSA::ScopeType::QMLScope, buildName(arrayBinding->qualifiedId),
2599 arrayBinding->firstSourceLocation());
2600 m_currentScope->setIsArrayScope(
true);
2607void QQmlJSImportVisitor::endVisit(UiArrayBinding *arrayBinding)
2614 const auto children = m_currentScope->childScopes();
2615 const auto propertyName = QQmlJSUtils::getScopeName(m_currentScope, QQmlSA::ScopeType::QMLScope);
2618 if (checkCustomParser(m_currentScope)) {
2625 for (
auto element = arrayBinding->members; element; element = element->next, ++i) {
2626 const auto &type = children[i];
2627 if ((type->scopeType() != QQmlSA::ScopeType::QMLScope)) {
2628 m_logger->log(u"Declaring an object which is not a Qml object"
2629 " as a list member."_s, qmlSyntax, element->firstSourceLocation());
2632 m_pendingPropertyObjectBindings
2633 << PendingPropertyObjectBinding { m_currentScope, type, propertyName,
2634 element->firstSourceLocation(),
false };
2635 QQmlJSMetaPropertyBinding binding(element->firstSourceLocation(), propertyName);
2636 binding.setObject(QQmlJSUtils::getScopeName(type, QQmlSA::ScopeType::QMLScope),
2637 QQmlJSScope::ConstPtr(type));
2638 m_bindings.append(UnfinishedBinding {
2640 [binding = std::move(binding)]() {
return binding; },
2641 QQmlJSScope::ListPropertyTarget
2646bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiEnumDeclaration *uied)
2648 QQmlJSMetaEnum qmlEnum(uied->name.toString());
2649 qmlEnum.setIsQml(
true);
2650 qmlEnum.setLineNumber(uied->enumToken.startLine);
2651 for (
const auto *member = uied->members; member; member = member->next) {
2652 qmlEnum.addKey(member->member.toString());
2653 qmlEnum.addValue(
int(member->value));
2655 m_currentScope->addOwnEnumeration(qmlEnum);
2659void QQmlJSImportVisitor::addImportWithLocation(
2660 const QString &name,
const QQmlJS::SourceLocation &loc,
bool hadWarnings)
2662 if (m_importTypeLocationMap.contains(name)
2663 && m_importTypeLocationMap.values(name).contains(loc)) {
2667 m_importTypeLocationMap.insert(name, loc);
2672 if (!hadWarnings && loc.isValid())
2673 m_importLocations.insert(loc);
2676QList<QQmlJS::DiagnosticMessage> QQmlJSImportVisitor::importFromHost(
2677 const QString &path,
const QString &prefix,
const QQmlJS::SourceLocation &location)
2679 QFileInfo fileInfo(path);
2680 if (!fileInfo.exists()) {
2681 m_logger->log(
"File or directory you are trying to import does not exist: %1."_L1.arg(path),
2682 qmlImport, location);
2686 if (fileInfo.isFile()) {
2687 const auto scope = m_importer->importFile(path);
2688 const QString actualPrefix = prefix.isEmpty() ? scope->internalName() : prefix;
2689 m_rootScopeImports.setType(actualPrefix, { scope, QTypeRevision() });
2690 addImportWithLocation(actualPrefix, location,
false);
2694 if (fileInfo.isDir()) {
2695 auto scopes = m_importer->importDirectory(path, prefix);
2696 const auto types = scopes.types();
2697 const auto warnings = scopes.warnings();
2698 m_rootScopeImports.add(std::move(scopes));
2699 for (
auto it = types.keyBegin(), end = types.keyEnd(); it != end; it++)
2700 addImportWithLocation(*it, location, !warnings.isEmpty());
2705 "%1 is neither a file nor a directory. Are sure the import path is correct?"_L1.arg(
2707 qmlImport, location);
2711QList<QQmlJS::DiagnosticMessage> QQmlJSImportVisitor::importFromQrc(
2712 const QString &path,
const QString &prefix,
const QQmlJS::SourceLocation &location)
2714 Q_ASSERT(path.startsWith(u':'));
2715 const QQmlJSResourceFileMapper *mapper = m_importer->resourceFileMapper();
2719 const auto pathNoColon = QStringView(path).mid(1);
2720 if (mapper->isFile(pathNoColon)) {
2721 const auto entry = m_importer->resourceFileMapper()->entry(
2722 QQmlJSResourceFileMapper::resourceFileFilter(pathNoColon.toString()));
2723 const auto scope = m_importer->importFile(entry.filePath);
2724 const QString actualPrefix =
2725 prefix.isEmpty() ? QFileInfo(entry.resourcePath).baseName() : prefix;
2726 m_rootScopeImports.setType(actualPrefix, { scope, QTypeRevision() });
2727 addImportWithLocation(actualPrefix, location,
false);
2731 auto scopes = m_importer->importDirectory(path, prefix);
2732 const auto types = scopes.types();
2733 const auto warnings = scopes.warnings();
2734 m_rootScopeImports.add(std::move(scopes));
2735 for (
auto it = types.keyBegin(), end = types.keyEnd(); it != end; it++)
2736 addImportWithLocation(*it, location, !warnings.isEmpty());
2740bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiImport *import)
2743 QString prefix = QLatin1String(
"");
2744 if (import->asToken.isValid()) {
2745 prefix += import->importId;
2746 if (!import->importId.isEmpty() && !import->importId.front().isUpper()) {
2747 m_logger->log(u"Import qualifier '%1' must start with a capital letter."_s.arg(
2749 qmlImport, import->importIdToken,
true,
true);
2751 m_seenModuleQualifiers.append(prefix);
2754 const QString filename = import->fileName.toString();
2755 if (!filename.isEmpty()) {
2756 const QUrl url(filename);
2757 const QString scheme = url.scheme();
2758 const QQmlJS::SourceLocation importLocation = import->firstSourceLocation();
2759 if (scheme ==
""_L1) {
2760 QFileInfo fileInfo(url.path());
2761 QString absolute = fileInfo.isRelative()
2762 ? QDir::cleanPath(QDir(m_implicitImportDirectory).filePath(filename))
2764 auto warnings = absolute.startsWith(u':')
2765 ? importFromQrc(absolute, prefix, importLocation)
2766 : importFromHost(absolute, prefix, importLocation);
2767 processImportWarnings(
"path \"%1\""_L1.arg(url.path()), warnings, importLocation);
2769 }
else if (scheme ==
"file"_L1) {
2770 auto warnings = importFromHost(url.path(), prefix, importLocation);
2771 processImportWarnings(
"URL \"%1\""_L1.arg(url.path()), warnings, importLocation);
2773 }
else if (scheme ==
"qrc"_L1) {
2774 auto warnings = importFromQrc(
":"_L1 + url.path(), prefix, importLocation);
2775 processImportWarnings(
"URL \"%1\""_L1.arg(url.path()), warnings, importLocation);
2778 m_logger->log(
"Unknown import syntax. Imports can be paths, qrc urls or file urls"_L1,
2779 qmlImport, import->firstSourceLocation());
2783 const QString path = buildName(import->importUri);
2785 QStringList staticModulesProvided;
2787 auto imported = m_importer->importModule(
2788 path, prefix, import->version ? import->version->version : QTypeRevision(),
2789 &staticModulesProvided);
2790 const auto types = imported.types();
2791 const auto warnings = imported.warnings();
2792 m_rootScopeImports.add(std::move(imported));
2793 for (
auto it = types.keyBegin(), end = types.keyEnd(); it != end; it++)
2794 addImportWithLocation(*it, import->firstSourceLocation(), !warnings.isEmpty());
2796 if (prefix.isEmpty()) {
2797 for (
const QString &staticModule : std::as_const(staticModulesProvided)) {
2799 if (path != staticModule && m_importStaticModuleLocationMap.contains(staticModule))
2802 m_importStaticModuleLocationMap[staticModule] = import->firstSourceLocation();
2806 processImportWarnings(
2807 QStringLiteral(
"module \"%1\"").arg(path), warnings, import->firstSourceLocation());
2811#if QT_VERSION >= QT_VERSION_CHECK(6
, 6
, 0
)
2813void handlePragmaValues(QQmlJS::AST::UiPragma *pragma, F &&assign)
2815 for (
const QQmlJS::AST::UiPragmaValueList *v = pragma->values; v; v = v->next)
2820void handlePragmaValues(QQmlJS::AST::UiPragma *pragma, F &&assign)
2822 assign(pragma->value);
2826bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiPragma *pragma)
2828 if (pragma->name == u"Strict"_s) {
2833 if (!m_logger->wasCategoryChanged(qmlCompiler))
2834 m_logger->setCategorySeverity(qmlCompiler, QQmlJS::WarningSeverity::Warning);
2835 }
else if (pragma->name == u"Singleton") {
2836 m_rootIsSingleton =
true;
2837 }
else if (pragma->name == u"ComponentBehavior") {
2838 handlePragmaValues(pragma, [
this, pragma](QStringView value) {
2839 if (value == u"Bound") {
2840 m_scopesById.setComponentsAreBound(
true);
2841 }
else if (value == u"Unbound") {
2842 m_scopesById.setComponentsAreBound(
false);
2844 m_logger->log(u"Unknown argument \"%1\" to pragma ComponentBehavior"_s.arg(value),
2845 qmlSyntax, pragma->firstSourceLocation());
2848 }
else if (pragma->name == u"FunctionSignatureBehavior") {
2849 handlePragmaValues(pragma, [
this, pragma](QStringView value) {
2850 if (value == u"Enforced") {
2851 m_scopesById.setSignaturesAreEnforced(
true);
2852 }
else if (value == u"Ignored") {
2853 m_scopesById.setSignaturesAreEnforced(
false);
2856 u"Unknown argument \"%1\" to pragma FunctionSignatureBehavior"_s.arg(value),
2857 qmlSyntax, pragma->firstSourceLocation());
2860 }
else if (pragma->name == u"ValueTypeBehavior") {
2861 handlePragmaValues(pragma, [
this, pragma](QStringView value) {
2862 if (value == u"Copy") {
2864 }
else if (value == u"Reference") {
2866 }
else if (value == u"Addressable") {
2867 m_scopesById.setValueTypesAreAddressable(
true);
2868 }
else if (value == u"Inaddressable") {
2869 m_scopesById.setValueTypesAreAddressable(
false);
2871 m_logger->log(u"Unknown argument \"%1\" to pragma ValueTypeBehavior"_s.arg(value),
2872 qmlSyntax, pragma->firstSourceLocation());
2880void QQmlJSImportVisitor::throwRecursionDepthError()
2882 m_logger->log(QStringLiteral(
"Maximum statement or expression depth exceeded"),
2883 qmlRecursionDepthErrors, QQmlJS::SourceLocation());
2886bool QQmlJSImportVisitor::visit(QQmlJS::AST::ClassDeclaration *ast)
2888 enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, ast->name.toString(),
2889 ast->firstSourceLocation());
2893void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ClassDeclaration *)
2898bool QQmlJSImportVisitor::visit(QQmlJS::AST::ForStatement *ast)
2900 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"forloop"),
2901 ast->firstSourceLocation());
2905void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ForStatement *)
2910bool QQmlJSImportVisitor::visit(QQmlJS::AST::ForEachStatement *ast)
2912 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"foreachloop"),
2913 ast->firstSourceLocation());
2917void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ForEachStatement *)
2922bool QQmlJSImportVisitor::visit(QQmlJS::AST::Block *ast)
2924 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"block"),
2925 ast->firstSourceLocation());
2927 if (m_pendingSignalHandler.isValid())
2928 flushPendingSignalParameters();
2933void QQmlJSImportVisitor::endVisit(QQmlJS::AST::Block *)
2938bool QQmlJSImportVisitor::visit(QQmlJS::AST::CaseBlock *ast)
2940 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"case"),
2941 ast->firstSourceLocation());
2945void QQmlJSImportVisitor::endVisit(QQmlJS::AST::CaseBlock *)
2950bool QQmlJSImportVisitor::visit(QQmlJS::AST::Catch *catchStatement)
2952 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"catch"),
2953 catchStatement->firstSourceLocation());
2957void QQmlJSImportVisitor::endVisit(QQmlJS::AST::Catch *)
2962bool QQmlJSImportVisitor::visit(QQmlJS::AST::WithStatement *ast)
2964 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"with"),
2965 ast->firstSourceLocation());
2967 m_logger->log(QStringLiteral(
"with statements are strongly discouraged in QML "
2968 "and might cause false positives when analysing unqualified "
2970 qmlWith, ast->firstSourceLocation());
2975void QQmlJSImportVisitor::endVisit(QQmlJS::AST::WithStatement *)
2980bool QQmlJSImportVisitor::visit(QQmlJS::AST::FormalParameterList *fpl)
2982 const auto &boundedNames = fpl->boundNames();
2983 for (
auto const &boundName : boundedNames) {
2985 std::optional<QString> typeName;
2986 if (TypeAnnotation *annotation = boundName.typeAnnotation.data())
2987 if (Type *type = annotation->type)
2988 typeName = type->toString();
2989 safeInsertJSIdentifier(m_currentScope, boundName.id,
2990 { QQmlJSScope::JavaScriptIdentifier::Parameter,
2991 boundName.location, typeName,
false });
2996bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiObjectBinding *uiob)
3000 Q_ASSERT(uiob->qualifiedTypeNameId);
3002 bool needsResolution =
false;
3003 int scopesEnteredCounter = 0;
3005 const QString typeName = buildName(uiob->qualifiedTypeNameId);
3006 if (typeName.front().isLower() && typeName.contains(u'.')) {
3007 logLowerCaseImport(typeName, uiob->qualifiedTypeNameId->identifierToken, m_logger);
3011 for (
auto group = uiob->qualifiedId; group->next; group = group->next) {
3012 const QString idName = group->name.toString();
3014 if (idName.isEmpty())
3017 if (group == uiob->qualifiedId && isImportPrefix(idName)) {
3018 prefix = idName + u'.';
3022 const auto scopeKind = idName.front().isUpper() ? QQmlSA::ScopeType::AttachedPropertyScope
3023 : QQmlSA::ScopeType::GroupedPropertyScope;
3026 enterEnvironmentNonUnique(scopeKind, prefix + idName, group->firstSourceLocation());
3028 m_bindings.append(createNonUniqueScopeBinding(m_currentScope, prefix + idName,
3029 group->firstSourceLocation()));
3031 ++scopesEnteredCounter;
3032 needsResolution = needsResolution || !exists;
3037 for (
int i=0; i < scopesEnteredCounter; ++i) {
3042 if (needsResolution) {
3043 QQmlJSScope::resolveTypes(
3044 m_currentScope, m_rootScopeImports.contextualTypes(), &m_usedTypes);
3047 enterEnvironment(QQmlSA::ScopeType::QMLScope, typeName,
3048 uiob->qualifiedTypeNameId->identifierToken);
3050 m_qmlTypes.append(m_currentScope);
3051 m_objectBindingScopes << m_currentScope;
3055void QQmlJSImportVisitor::endVisit(QQmlJS::AST::UiObjectBinding *uiob)
3057 QQmlJSScope::resolveTypes(m_currentScope, m_rootScopeImports.contextualTypes(), &m_usedTypes);
3059 const QQmlJSScope::Ptr childScope = m_currentScope;
3062 auto group = uiob->qualifiedId;
3063 int scopesEnteredCounter = 0;
3066 for (; group->next; group = group->next) {
3067 const QString idName = group->name.toString();
3069 if (idName.isEmpty())
3072 if (group == uiob->qualifiedId && isImportPrefix(idName)) {
3073 prefix = idName + u'.';
3077 const auto scopeKind = idName.front().isUpper() ? QQmlSA::ScopeType::AttachedPropertyScope
3078 : QQmlSA::ScopeType::GroupedPropertyScope;
3080 [[maybe_unused]]
bool exists =
3081 enterEnvironmentNonUnique(scopeKind, prefix + idName, group->firstSourceLocation());
3083 scopesEnteredCounter++;
3091 const QString propertyName = group->name.toString();
3093 if (m_currentScope->isNameDeferred(propertyName)) {
3094 bool foundIds =
false;
3095 QList<QQmlJSScope::ConstPtr> childScopes { childScope };
3097 while (!childScopes.isEmpty()) {
3098 const QQmlJSScope::ConstPtr scope = childScopes.takeFirst();
3099 m_scopesById.possibleIds(
3100 scope, scope, Default,
3101 [&](
const QString &id, QQmlJSScopesById::Confidence confidence) {
3104 Q_UNUSED(confidence);
3106 return QQmlJSScopesById::CallbackResult::StopSearch;
3109 childScopes << scope->childScopes();
3114 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
3116 qmlDeferredPropertyId, uiob->firstSourceLocation());
3120 if (checkCustomParser(m_currentScope)) {
3124 m_pendingPropertyObjectBindings
3125 << PendingPropertyObjectBinding { m_currentScope, childScope, propertyName,
3126 uiob->firstSourceLocation(), uiob->hasOnToken };
3128 QQmlJSMetaPropertyBinding binding(uiob->firstSourceLocation(), propertyName);
3129 if (uiob->hasOnToken) {
3130 if (childScope->hasInterface(u"QQmlPropertyValueInterceptor"_s)) {
3131 binding.setInterceptor(QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope),
3132 QQmlJSScope::ConstPtr(childScope));
3134 binding.setValueSource(QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope),
3135 QQmlJSScope::ConstPtr(childScope));
3138 binding.setObject(QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope),
3139 QQmlJSScope::ConstPtr(childScope));
3141 m_bindings.append(UnfinishedBinding { m_currentScope, [=]() {
return binding; } });
3144 for (
int i = 0; i < scopesEnteredCounter; ++i)
3148bool QQmlJSImportVisitor::visit(ExportDeclaration *)
3150 Q_ASSERT(rootScopeIsValid());
3151 Q_ASSERT(m_exportedRootScope != m_globalScope);
3152 Q_ASSERT(m_currentScope == m_globalScope);
3153 m_currentScope = m_exportedRootScope;
3157void QQmlJSImportVisitor::endVisit(ExportDeclaration *)
3159 Q_ASSERT(rootScopeIsValid());
3160 m_currentScope = m_exportedRootScope->parentScope();
3161 Q_ASSERT(m_currentScope == m_globalScope);
3164bool QQmlJSImportVisitor::visit(ESModule *module)
3166 Q_ASSERT(!rootScopeIsValid());
3167 enterRootScope(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"module"),
3168 module->firstSourceLocation());
3169 m_currentScope->setIsScript(
true);
3170 importBaseModules();
3175void QQmlJSImportVisitor::endVisit(ESModule *)
3177 QQmlJSScope::resolveTypes(
3178 m_exportedRootScope, m_rootScopeImports.contextualTypes(), &m_usedTypes);
3181bool QQmlJSImportVisitor::visit(Program *program)
3183 Q_ASSERT(m_globalScope == m_currentScope);
3184 Q_ASSERT(!rootScopeIsValid());
3185 enterRootScope(QQmlSA::ScopeType::JSFunctionScope, u"script"_s, program->firstSourceLocation());
3186 m_exportedRootScope->setIsScript(
true);
3187 importBaseModules();
3191void QQmlJSImportVisitor::endVisit(Program *)
3193 QQmlJSScope::resolveTypes(
3194 m_exportedRootScope, m_rootScopeImports.contextualTypes(), &m_usedTypes);
3197void QQmlJSImportVisitor::endVisit(QQmlJS::AST::FieldMemberExpression *fieldMember)
3201 const QString name = fieldMember->name.toString();
3202 if (m_importTypeLocationMap.contains(name)) {
3203 const QQmlJSImportedScope type = m_rootScopeImports.type(name);
3204 if (type.scope.isNull()) {
3205 if (m_rootScopeImports.hasType(name))
3206 m_usedTypes.insert(name);
3207 }
else if (!type.scope->ownAttachedTypeName().isEmpty()) {
3208 m_usedTypes.insert(name);
3213bool QQmlJSImportVisitor::visit(QQmlJS::AST::IdentifierExpression *idexp)
3215 const QString name = idexp->name.toString();
3216 if (m_importTypeLocationMap.contains(name)) {
3217 m_usedTypes.insert(name);
3223bool QQmlJSImportVisitor::visit(QQmlJS::AST::PatternElement *element)
3226 if (element->isVariableDeclaration()) {
3227 QQmlJS::AST::BoundNames names;
3228 element->boundNames(&names);
3229 for (
const auto &name : std::as_const(names)) {
3230 std::optional<QString> typeName;
3231 if (TypeAnnotation *annotation = name.typeAnnotation.data())
3232 if (Type *type = annotation->type)
3233 typeName = type->toString();
3234 using Kind = QQmlJSScope::JavaScriptIdentifier::Kind;
3235 const Kind kind = (element->scope == QQmlJS::AST::VariableScope::Var)
3236 ? Kind::FunctionScoped
3237 : Kind::LexicalScoped;
3238 const QString variableName = name.id;
3239 if (kind == Kind::LexicalScoped) {
3240 const QQmlJS::SourceLocation location = element->firstSourceLocation();
3241 if (
auto previousDeclaration = m_currentScope->ownJSIdentifier(variableName)) {
3242 m_logger->log(
"Identifier '%1' has already been declared"_L1.arg(variableName), qmlSyntax,
3244 m_logger->log(
"Note: previous declaration of '%1' here"_L1.arg(variableName), qmlSyntax,
3245 previousDeclaration->location);
3248 const bool isConstVariable = element->scope == QQmlJS::AST::VariableScope::Const;
3249 const bool couldInsert = safeInsertJSIdentifier(m_currentScope,
3251 { (element->scope == QQmlJS::AST::VariableScope::Var)
3252 ? QQmlJSScope::JavaScriptIdentifier::FunctionScoped
3253 : QQmlJSScope::JavaScriptIdentifier::LexicalScoped,
3254 name.location, typeName,
3264bool QQmlJSImportVisitor::visit(IfStatement *statement)
3266 if (BinaryExpression *binary = cast<BinaryExpression *>(statement->expression)) {
3267 if (binary->op == QSOperator::Assign) {
3269 "Assignment in condition: did you mean to use \"===\" or \"==\" instead of \"=\"?"_L1,
3270 qmlAssignmentInCondition, binary->operatorToken);