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);
549 checkForComponentTypeWithProperties(scope);
552 for (
const auto &scope : std::as_const(m_objectDefinitionScopes)) {
553 if (m_pendingDefaultProperties.contains(scope))
555 breakInheritanceCycles(scope);
556 checkDeprecation(scope);
557 checkForComponentTypeWithProperties(scope);
560 const auto &keys = m_pendingDefaultProperties.keys();
561 for (
const auto &scope : keys) {
562 breakInheritanceCycles(scope);
563 checkDeprecation(scope);
564 checkForComponentTypeWithProperties(scope);
568 resolveGroupProperties();
570 for (
const auto &scope : std::as_const(m_objectDefinitionScopes))
571 checkGroupedAndAttachedScopes(scope);
574 processDefaultProperties();
575 processPropertyTypes();
576 processMethodTypes();
577 processPropertyBindings();
578 processPropertyBindingObjects();
579 checkRequiredProperties();
581 auto unusedImports = m_importLocations;
582 for (
const QString &type : std::as_const(m_usedTypes)) {
583 const auto &importLocations = m_importTypeLocationMap.values(type);
584 for (
const auto &importLocation : importLocations)
585 unusedImports.remove(importLocation);
588 if (unusedImports.isEmpty())
592 const auto &imports = m_importStaticModuleLocationMap.values();
593 for (
const QQmlJS::SourceLocation &import : imports)
594 unusedImports.remove(import);
596 for (
const auto &import : unusedImports) {
597 m_logger->log(QString::fromLatin1(
"Unused import"), qmlUnusedImports, import);
600 populateRuntimeFunctionIndicesForDocument();
605 ExpressionStatement *expr = cast<ExpressionStatement *>(statement);
607 if (!statement || !expr->expression)
610 switch (expr->expression->kind) {
611 case Node::Kind_StringLiteral:
612 return cast<StringLiteral *>(expr->expression)->value.toString();
613 case Node::Kind_NumericLiteral:
614 return cast<NumericLiteral *>(expr->expression)->value;
620QList<QQmlJSAnnotation> QQmlJSImportVisitor::parseAnnotations(QQmlJS::AST::UiAnnotationList *list)
623 QList<QQmlJSAnnotation> annotationList;
625 for (UiAnnotationList *item = list; item !=
nullptr; item = item->next) {
626 UiAnnotation *annotation = item->annotation;
628 QQmlJSAnnotation qqmljsAnnotation;
629 qqmljsAnnotation.name = buildName(annotation->qualifiedTypeNameId);
631 for (UiObjectMemberList *memberItem = annotation->initializer->members; memberItem !=
nullptr; memberItem = memberItem->next) {
632 switch (memberItem->member->kind) {
633 case Node::Kind_UiScriptBinding: {
634 auto *scriptBinding = QQmlJS::AST::cast<UiScriptBinding*>(memberItem->member);
635 qqmljsAnnotation.bindings[buildName(scriptBinding->qualifiedId)]
636 = bindingToVariant(scriptBinding->statement);
645 annotationList.append(qqmljsAnnotation);
648 return annotationList;
651void QQmlJSImportVisitor::setAllBindings()
653 using Key = std::pair<QQmlJSScope::ConstPtr, QString>;
654 QHash<Key, QQmlJS::SourceLocation> foundBindings;
656 for (
auto it = m_bindings.cbegin(); it != m_bindings.cend(); ++it) {
658 const QQmlJSScope::Ptr type = it->owner;
659 if (!checkTypeResolved(type))
668 if (!type->isFullyResolved())
670 auto binding = it->create();
671 if (!binding.isValid())
673 type->addOwnPropertyBinding(binding, it->specifier);
676 if (binding.hasInterceptor() || binding.hasValueSource())
678 const QString propertyName = binding.propertyName();
679 QQmlJSMetaProperty property = type->property(propertyName);
682
683
684
685
686
687 if (!property.isValid())
691 if (property.isList())
694 const Key key = std::make_pair(type, propertyName);
695 auto sourceLocationIt = foundBindings.constFind(key);
696 if (sourceLocationIt == foundBindings.constEnd()) {
697 foundBindings.insert(key, binding.sourceLocation());
701 const QQmlJS::SourceLocation location = binding.sourceLocation();
702 m_logger->log(
"Duplicate binding on property '%1'"_L1.arg(propertyName),
703 qmlDuplicatePropertyBinding, location);
704 m_logger->log(
"Note: previous binding on '%1' here"_L1.arg(propertyName),
705 qmlDuplicatePropertyBinding, *sourceLocationIt,
true,
true, {},
710void QQmlJSImportVisitor::processDefaultProperties()
712 for (
auto it = m_pendingDefaultProperties.constBegin();
713 it != m_pendingDefaultProperties.constEnd(); ++it) {
714 QQmlJSScope::ConstPtr parentScope = it.key();
717 if (checkCustomParser(parentScope))
721
722
723
724
725
726
727
728
729
731 parentScope = parentScope->baseType();
733 const QString defaultPropertyName =
734 parentScope ? parentScope->defaultPropertyName() : QString();
736 if (defaultPropertyName.isEmpty()) {
739 bool isComponent =
false;
740 for (QQmlJSScope::ConstPtr s = parentScope; s; s = s->baseType()) {
741 if (s->internalName() == QStringLiteral(
"QQmlComponent")) {
748 m_logger->log(QStringLiteral(
"Cannot assign to non-existent default property"),
749 qmlMissingProperty, it.value().constFirst()->sourceLocation());
755 const QQmlJSMetaProperty defaultProp = parentScope->property(defaultPropertyName);
756 auto propType = defaultProp.type();
757 const auto handleUnresolvedDefaultProperty = [&](
const QQmlJSScope::ConstPtr &) {
759 m_logger->log(QStringLiteral(
"Property \"%1\" has incomplete type \"%2\". You may be "
760 "missing an import.")
761 .arg(defaultPropertyName)
762 .arg(defaultProp.typeName()),
763 qmlUnresolvedType, it.value().constFirst()->sourceLocation());
766 const auto assignToUnknownProperty = [&]() {
769 for (
const QQmlJSScope::Ptr &scope : std::as_const(*it))
770 scope->setAssignedToUnknownProperty(
true);
773 if (propType.isNull()) {
774 handleUnresolvedDefaultProperty(propType);
775 assignToUnknownProperty();
779 if (it.value().size() > 1
780 && !defaultProp.isList()
781 && !propType->isListProperty()) {
783 QStringLiteral(
"Cannot assign multiple objects to a default non-list property"),
784 qmlNonListProperty, it.value().constFirst()->sourceLocation());
787 if (!checkTypeResolved(propType, handleUnresolvedDefaultProperty)) {
788 assignToUnknownProperty();
792 for (
const QQmlJSScope::Ptr &scope : std::as_const(*it)) {
793 if (!checkTypeResolved(scope))
798 if (propType->canAssign(scope)) {
799 scope->setIsWrappedInImplicitComponent(
800 causesImplicitComponentWrapping(defaultProp, scope));
804 m_logger->log(QStringLiteral(
"Cannot assign to default property of incompatible type"),
805 qmlIncompatibleType, scope->sourceLocation());
810void QQmlJSImportVisitor::processPropertyTypes()
812 for (
const PendingPropertyType &type : std::as_const(m_pendingPropertyTypes)) {
813 Q_ASSERT(type.scope->hasOwnProperty(type.name));
815 auto property = type.scope->ownProperty(type.name);
817 if (
const auto propertyType = QQmlJSScope::findType(
818 property.typeName(), m_rootScopeImports.contextualTypes()).scope) {
819 property.setType(propertyType);
820 type.scope->addOwnProperty(property);
822 QString msg = property.typeName() +
' '_L1 + wasNotFound +
' '_L1 + didYouAddAllImports;
823 if (property.typeName() ==
"list"_L1)
824 msg +=
" list is not a type. It requires an element type argument (eg. list<int>)"_L1;
825 m_logger->log(msg, qmlImport, type.location);
830void QQmlJSImportVisitor::processMethodTypes()
832 const auto isEnumUsedAsType = [&](QStringView typeName,
const QQmlJS::SourceLocation &loc) {
833 if (typeName ==
"enum"_L1) {
837 const auto split = typeName.tokenize(u'.').toContainer<QVarLengthArray<QStringView, 4>>();
838 if (split.size() != 2)
841 const QStringView scopeName = split[0];
842 const QStringView enumName = split[1];
844 if (
auto scope = QQmlJSScope::findType(scopeName.toString(),
845 m_rootScopeImports.contextualTypes()).scope) {
846 if (scope->enumeration(enumName.toString()).isValid()) {
848 "QML enumerations are not types. Use int, or use double if the enum's underlying type does not fit into int."_L1,
849 qmlEnumsAreNotTypes, loc);
856 for (
const auto &method : std::as_const(m_pendingMethodTypeAnnotations)) {
857 for (
auto [it, end] = method.scope->mutableOwnMethodsRange(method.methodName); it != end; ++it) {
858 const auto [parameterBegin, parameterEnd] = it->mutableParametersRange();
859 for (
auto parameter = parameterBegin; parameter != parameterEnd; ++parameter) {
860 const int parameterIndex = parameter - parameterBegin;
861 if (isEnumUsedAsType(parameter->typeName(), method.locations[parameterIndex]))
863 if (
const auto parameterType = QQmlJSScope::findType(
864 parameter->typeName(), m_rootScopeImports.contextualTypes()).scope) {
865 parameter->setType({ parameterType });
868 u"\"%1\" was not found for the type of parameter \"%2\" in method \"%3\"."_s
869 .arg(parameter->typeName(), parameter->name(), it->methodName()),
870 qmlUnresolvedType, method.locations[parameter - parameterBegin]);
874 if (isEnumUsedAsType(it->returnTypeName(), method.locations.last()))
876 if (
const auto returnType = QQmlJSScope::findType(
877 it->returnTypeName(), m_rootScopeImports.contextualTypes()).scope) {
878 it->setReturnType({ returnType });
880 m_logger->log(u"\"%1\" was not found for the return type of method \"%2\"."_s.arg(
881 it->returnTypeName(), it->methodName()),
882 qmlUnresolvedType, method.locations.last());
890
891
892
893
894
895
896
900 for (QStringView propertyName: possiblyGroupedProperty.tokenize(u".")) {
901 property = scope->property(propertyName.toString());
902 if (property.isValid())
903 scope = property.type();
910void QQmlJSImportVisitor::processPropertyBindingObjects()
912 QSet<std::pair<QQmlJSScope::Ptr, QString>> foundLiterals;
920 QSet<std::pair<QQmlJSScope::Ptr, QString>> visited;
921 for (
const PendingPropertyObjectBinding &objectBinding :
922 std::as_const(m_pendingPropertyObjectBindings)) {
924 const auto uniqueBindingId = std::make_pair(objectBinding.scope, objectBinding.name);
925 if (visited.contains(uniqueBindingId))
927 visited.insert(uniqueBindingId);
929 auto [existingBindingsBegin, existingBindingsEnd] =
930 uniqueBindingId.first->ownPropertyBindings(uniqueBindingId.second);
931 const bool hasLiteralBindings =
932 std::any_of(existingBindingsBegin, existingBindingsEnd,
933 [](
const QQmlJSMetaPropertyBinding &x) {
return x.hasLiteral(); });
934 if (hasLiteralBindings)
935 foundLiterals.insert(uniqueBindingId);
939 QSet<std::pair<QQmlJSScope::Ptr, QString>> foundObjects;
940 QSet<std::pair<QQmlJSScope::Ptr, QString>> foundInterceptors;
941 QSet<std::pair<QQmlJSScope::Ptr, QString>> foundValueSources;
943 for (
const PendingPropertyObjectBinding &objectBinding :
944 std::as_const(m_pendingPropertyObjectBindings)) {
945 const QString propertyName = objectBinding.name;
946 QQmlJSScope::Ptr childScope = objectBinding.childScope;
948 const auto assignToUnknownProperty = [&]() {
951 childScope->setAssignedToUnknownProperty(
true);
955 if (!checkTypeResolved(objectBinding.scope)) {
956 assignToUnknownProperty();
960 QQmlJSMetaProperty property = resolveProperty(propertyName, objectBinding.scope);
962 if (!property.isValid()) {
963 warnMissingPropertyForBinding(propertyName, objectBinding.location);
966 const auto handleUnresolvedProperty = [&](
const QQmlJSScope::ConstPtr &) {
968 m_logger->log(QStringLiteral(
"Property \"%1\" has incomplete type \"%2\". You may be "
969 "missing an import.")
971 .arg(property.typeName()),
972 qmlUnresolvedType, objectBinding.location);
975 if (property.type().isNull()) {
976 assignToUnknownProperty();
977 handleUnresolvedProperty(property.type());
982 if (!checkTypeResolved(property.type(), handleUnresolvedProperty)) {
983 assignToUnknownProperty();
985 }
else if (!checkTypeResolved(childScope)) {
989 if (!objectBinding.onToken && !property.type()->canAssign(childScope)) {
990 m_logger->log(QStringLiteral(
"Cannot assign object of type %1 to %2")
991 .arg(QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope))
992 .arg(property.typeName()),
993 qmlIncompatibleType, childScope->sourceLocation());
997 childScope->setIsWrappedInImplicitComponent(
998 causesImplicitComponentWrapping(property, childScope));
1001 const auto uniqueBindingId = std::make_pair(objectBinding.scope, objectBinding.name);
1002 const QString typeName = QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope);
1004 auto isConditionalBinding = [&]() ->
bool {
1006
1007
1008
1009
1010 return childScope->hasOwnPropertyBindings(u"enabled"_s)
1011 || childScope->hasOwnPropertyBindings(u"when"_s)
1012 || childScope->hasOwnPropertyBindings(u"running"_s);
1015 if (objectBinding.onToken) {
1016 if (childScope->hasInterface(QStringLiteral(
"QQmlPropertyValueInterceptor"))) {
1017 if (foundInterceptors.contains(uniqueBindingId)) {
1018 if (!isConditionalBinding()) {
1019 m_logger->log(QStringLiteral(
"Duplicate interceptor on property \"%1\"")
1021 qmlDuplicatePropertyBinding, objectBinding.location);
1024 foundInterceptors.insert(uniqueBindingId);
1026 }
else if (childScope->hasInterface(QStringLiteral(
"QQmlPropertyValueSource"))) {
1027 if (foundValueSources.contains(uniqueBindingId)) {
1028 if (!isConditionalBinding()) {
1029 m_logger->log(QStringLiteral(
"Duplicate value source on property \"%1\"")
1031 qmlDuplicatePropertyBinding, objectBinding.location);
1033 }
else if (foundObjects.contains(uniqueBindingId)
1034 || foundLiterals.contains(uniqueBindingId)) {
1035 if (!isConditionalBinding()) {
1036 m_logger->log(QStringLiteral(
"Cannot combine value source and binding on "
1039 qmlDuplicatePropertyBinding, objectBinding.location);
1042 foundValueSources.insert(uniqueBindingId);
1045 m_logger->log(QStringLiteral(
"On-binding for property \"%1\" has wrong type \"%2\"")
1048 qmlIncompatibleType, objectBinding.location);
1051 if (foundValueSources.contains(uniqueBindingId)) {
1052 if (!isConditionalBinding()) {
1054 QStringLiteral(
"Cannot combine value source and binding on property \"%1\"")
1056 qmlDuplicatePropertyBinding, objectBinding.location);
1059 foundObjects.insert(uniqueBindingId);
1067 QList<QQmlJSScope::ConstPtr> descendants;
1068 std::vector<QQmlJSScope::ConstPtr> toVisit;
1070 toVisit.push_back(scope);
1071 while (!toVisit.empty()) {
1072 const QQmlJSScope::ConstPtr s = toVisit.back();
1078 toVisit.insert(toVisit.end(), s->childScopesBegin(), s->childScopesEnd());
1085void QQmlJSImportVisitor::populatePropertyAliases()
1087 for (
const auto &alias : std::as_const(m_aliasDefinitions)) {
1088 const auto &[aliasScope, aliasName] = alias;
1089 if (aliasScope.isNull())
1092 auto property = aliasScope->ownProperty(aliasName);
1093 if (!property.isValid() || !property.aliasTargetScope())
1096 Property target(property.aliasTargetScope(), property.aliasTargetName());
1099 m_propertyAliases[target].append(alias);
1100 property = target.scope->property(target.name);
1101 target = Property(property.aliasTargetScope(), property.aliasTargetName());
1102 }
while (property.isAlias());
1106void QQmlJSImportVisitor::checkRequiredProperties()
1108 for (
const auto &required : std::as_const(m_requiredProperties)) {
1109 if (!required.scope->hasProperty(required.name)) {
1111 QStringLiteral(
"Property \"%1\" was marked as required but does not exist.")
1112 .arg(required.name),
1113 qmlRequired, required.location);
1117 const auto compType = m_rootScopeImports.type(u"Component"_s).scope;
1118 const auto isComponentRoot = [&](
const QQmlJSScope::ConstPtr &requiredScope) {
1119 if (requiredScope->isWrappedInImplicitComponent())
1121 if (
const auto s = requiredScope->parentScope(); s && s->baseType() == compType)
1126 const auto scopeRequiresProperty = [&](
const QQmlJSScope::ConstPtr &requiredScope,
1127 const QString &propName,
1128 const QQmlJSScope::ConstPtr &descendant) {
1129 if (!requiredScope->isPropertyLocallyRequired(propName))
1133 return QQmlJSScope::ownerOfProperty(requiredScope, propName).scope
1134 == QQmlJSScope::ownerOfProperty(descendant, propName).scope;
1137 const auto requiredHasBinding = [](
const QList<QQmlJSScope::ConstPtr> &scopesToSearch,
1138 const QQmlJSScope::ConstPtr &owner,
1139 const QString &propName) {
1140 for (
const auto &scope : scopesToSearch) {
1141 if (scope->property(propName).isAlias())
1143 const auto &[begin, end] = scope->ownPropertyBindings(propName);
1144 for (
auto it = begin; it != end; ++it) {
1146 const bool isRelevantBinding = QQmlSA::isRegularBindingType(it->bindingType())
1147 || it->bindingType() == QQmlSA::BindingType::Interceptor
1148 || it->bindingType() == QQmlSA::BindingType::ValueSource;
1149 if (!isRelevantBinding)
1151 if (QQmlJSScope::ownerOfProperty(scope, propName).scope == owner)
1159 const auto requiredUsedInRootAlias = [&](
const QQmlJSScope::ConstPtr &requiredScope,
1160 const QString &propName) {
1161 const Property target(requiredScope, propName);
1164 const auto allAliasesToTargetIt = m_propertyAliases.constFind(target);
1165 if (allAliasesToTargetIt == m_propertyAliases.constEnd())
1172 allAliasesToTargetIt->constBegin(), allAliasesToTargetIt->constEnd(),
1173 [](
const Property &property) {
return property.scope->isFileRootComponent(); });
1176 const auto requiredSetThroughAlias = [&](
const QList<QQmlJSScope::ConstPtr> &scopesToSearch,
1177 const QQmlJSScope::ConstPtr &requiredScope,
1178 const QString &propName) {
1179 const auto &propertyDefScope = QQmlJSScope::ownerOfProperty(requiredScope, propName);
1180 const auto &propertyAliases = m_propertyAliases[{ propertyDefScope.scope, propName }];
1181 for (
const auto &alias : propertyAliases) {
1182 for (
const auto &s : scopesToSearch) {
1183 if (s->hasOwnPropertyBindings(alias.name))
1190 const auto warn = [
this](
const QQmlJSScope::ConstPtr &prevRequiredScope,
1191 const QString &propName,
const QQmlJSScope::ConstPtr &defScope,
1192 const QQmlJSScope::ConstPtr &requiredScope,
1193 const QQmlJSScope::ConstPtr &descendant) {
1194 const auto &propertyScope = QQmlJSScope::ownerOfProperty(requiredScope, propName).scope;
1195 const QString propertyScopeName = !propertyScope.isNull()
1196 ? QQmlJSUtils::getScopeName(propertyScope, QQmlSA::ScopeType::QMLScope)
1199 std::optional<QQmlJSFixSuggestion> suggestion;
1201 QString message = QStringLiteral(
"Component is missing required property %1 from %2")
1203 .arg(propertyScopeName);
1204 if (requiredScope != descendant) {
1205 const QString requiredScopeName = prevRequiredScope
1206 ? QQmlJSUtils::getScopeName(prevRequiredScope, QQmlSA::ScopeType::QMLScope)
1209 if (!prevRequiredScope.isNull()) {
1210 if (
auto sourceScope = prevRequiredScope->baseType()) {
1211 suggestion = QQmlJSFixSuggestion{
1212 "%1:%2:%3: Property marked as required in %4."_L1
1213 .arg(sourceScope->filePath())
1214 .arg(sourceScope->sourceLocation().startLine)
1215 .arg(sourceScope->sourceLocation().startColumn)
1216 .arg(requiredScopeName),
1217 sourceScope->sourceLocation()
1221 if (sourceScope->isComposite())
1222 suggestion->setFilename(sourceScope->filePath());
1225 message +=
" (marked as required by %1)"_L1.arg(requiredScopeName);
1229 m_logger->log(message, qmlRequired, defScope->sourceLocation(),
true,
true, suggestion);
1232 populatePropertyAliases();
1234 for (
const auto &[_, defScope] : m_scopesByIrLocation.asKeyValueRange()) {
1235 if (defScope->isFileRootComponent() || defScope->isInlineComponent()
1236 || defScope->componentRootStatus() != QQmlJSScope::IsComponentRoot::No
1237 || defScope->scopeType() != QQmlSA::ScopeType::QMLScope) {
1241 QList<QQmlJSScope::ConstPtr> scopesToSearch;
1242 for (QQmlJSScope::ConstPtr scope = defScope; scope; scope = scope->baseType()) {
1243 const auto descendants = QList<QQmlJSScope::ConstPtr>()
1244 << scope << qmlScopeDescendants(scope);
1245 for (
const QQmlJSScope::ConstPtr &descendant : std::as_const(descendants)) {
1248 if (descendant != scope && descendant->isInlineComponent())
1250 scopesToSearch << descendant;
1251 const auto ownProperties = descendant->ownProperties();
1252 for (
auto propertyIt = ownProperties.constBegin();
1253 propertyIt != ownProperties.constEnd(); ++propertyIt) {
1254 const QString propName = propertyIt.key();
1255 if (descendant->hasOwnPropertyBindings(propName))
1258 QQmlJSScope::ConstPtr prevRequiredScope;
1259 for (
const QQmlJSScope::ConstPtr &requiredScope : std::as_const(scopesToSearch)) {
1262 if (isComponentRoot(requiredScope))
1265 if (!scopeRequiresProperty(requiredScope, propName, descendant)) {
1266 prevRequiredScope = requiredScope;
1270 if (requiredHasBinding(scopesToSearch, descendant, propName))
1273 if (requiredUsedInRootAlias(requiredScope, propName))
1276 if (requiredSetThroughAlias(scopesToSearch, requiredScope, propName))
1279 warn(prevRequiredScope, propName, defScope, requiredScope, descendant);
1280 prevRequiredScope = requiredScope;
1288void QQmlJSImportVisitor::processPropertyBindings()
1290 for (
auto it = m_propertyBindings.constBegin(); it != m_propertyBindings.constEnd(); ++it) {
1291 QQmlJSScope::Ptr scope = it.key();
1292 for (
auto &[visibilityScope, location, name] : it.value()) {
1293 if (!scope->hasProperty(name) && !m_logger->isDisabled()) {
1297 if (checkCustomParser(scope))
1301 std::optional<QQmlJSFixSuggestion> fixSuggestion;
1303 for (QQmlJSScope::ConstPtr baseScope = scope; !baseScope.isNull();
1304 baseScope = baseScope->baseType()) {
1305 if (
auto suggestion = QQmlJSUtils::didYouMean(
1306 name, baseScope->ownProperties().keys(), location);
1307 suggestion.has_value()) {
1308 fixSuggestion = suggestion;
1313 warnMissingPropertyForBinding(name, location, fixSuggestion);
1317 const auto property = scope->property(name);
1318 if (!property.type()) {
1319 m_logger->log(QStringLiteral(
"No type found for property \"%1\". This may be due "
1320 "to a missing import statement or incomplete "
1323 qmlMissingType, location);
1326 const auto &annotations = property.annotations();
1328 const auto deprecationAnn =
1329 std::find_if(annotations.cbegin(), annotations.cend(),
1330 [](
const QQmlJSAnnotation &ann) {
return ann.isDeprecation(); });
1332 if (deprecationAnn != annotations.cend()) {
1333 const auto deprecation = deprecationAnn->deprecation();
1335 QString message = QStringLiteral(
"Binding on deprecated property \"%1\"")
1336 .arg(property.propertyName());
1338 if (!deprecation.reason.isEmpty())
1339 message.append(QStringLiteral(
" (Reason: %1)").arg(deprecation.reason));
1341 m_logger->log(message, qmlDeprecated, location);
1347void QQmlJSImportVisitor::checkSignal(
1348 const QQmlJSScope::ConstPtr &signalScope,
const QQmlJS::SourceLocation &location,
1349 const QString &handlerName,
const QStringList &handlerParameters)
1351 const auto signal = QQmlSignalNames::handlerNameToSignalName(handlerName);
1353 std::optional<QQmlJSMetaMethod> signalMethod;
1354 const auto setSignalMethod = [&](
const QQmlJSScope::ConstPtr &scope,
const QString &name) {
1355 const auto methods = scope->methods(name, QQmlJSMetaMethodType::Signal);
1356 if (!methods.isEmpty())
1357 signalMethod = methods[0];
1360 if (signal.has_value()) {
1361 if (signalScope->hasMethod(*signal)) {
1362 setSignalMethod(signalScope, *signal);
1363 }
else if (
auto p = QQmlJSUtils::propertyFromChangedHandler(signalScope, handlerName)) {
1368 if (
auto notify = p->notify(); !notify.isEmpty()) {
1369 setSignalMethod(signalScope, notify);
1371 Q_ASSERT(!p->bindable().isEmpty());
1372 signalMethod = QQmlJSMetaMethod {};
1377 if (!signalMethod.has_value()) {
1382 if (signalScope->baseTypeName() == QStringLiteral(
"Connections")) {
1384 u"Implicitly defining \"%1\" as signal handler in Connections is deprecated. "
1385 u"Create a function instead: \"function %2(%3) { ... }\"."_s.arg(
1386 handlerName, handlerName, handlerParameters.join(u", ")),
1387 qmlUnqualified, location,
true,
true);
1391 auto baseType = QQmlJSScope::nonCompositeBaseType(signalScope);
1392 if (baseType && baseType->hasCustomParser())
1396 QStringLiteral(
"no matching signal found for handler \"%1\"").arg(handlerName),
1397 qmlUnqualified, location,
true,
true);
1401 const auto signalParameters = signalMethod->parameters();
1402 QHash<QString, qsizetype> parameterNameIndexes;
1404 for (
int i = 0, end = signalParameters.size(); i < end; i++) {
1405 auto &p = signalParameters[i];
1406 parameterNameIndexes[p.name()] = i;
1408 auto signalName = [&]() {
1410 return u" called %1"_s.arg(*signal);
1413 auto type = p.type();
1416 "Type %1 of parameter %2 in signal%3 was not found, but is required to compile "
1418 p.typeName(), p.name(), signalName(),
1419 handlerName, didYouAddAllImports),
1420 qmlSignalParameters, location);
1424 if (type->isComposite())
1432 auto parameterName = [&]() {
1433 if (p.name().isEmpty())
1435 return u" called %1"_s.arg(p.name());
1437 switch (type->accessSemantics()) {
1438 case QQmlJSScope::AccessSemantics::Reference:
1440 m_logger->log(QStringLiteral(
"Type %1 of parameter%2 in signal%3 should be "
1441 "passed by pointer to be able to compile %4. ")
1442 .arg(p.typeName(), parameterName(), signalName(),
1444 qmlSignalParameters, location);
1446 case QQmlJSScope::AccessSemantics::Value:
1447 case QQmlJSScope::AccessSemantics::Sequence:
1451 "Type %1 of parameter%2 in signal%3 should be passed by "
1452 "value or const reference to be able to compile %4. ")
1453 .arg(p.typeName(), parameterName(), signalName(),
1455 qmlSignalParameters, location);
1457 case QQmlJSScope::AccessSemantics::None:
1459 QStringLiteral(
"Type %1 of parameter%2 in signal%3 required by the "
1460 "compilation of %4 cannot be used. ")
1461 .arg(p.typeName(), parameterName(), signalName(), handlerName),
1462 qmlSignalParameters, location);
1467 if (handlerParameters.size() > signalParameters.size()) {
1468 m_logger->log(QStringLiteral(
"Signal handler for \"%2\" has more formal"
1469 " parameters than the signal it handles.")
1471 qmlSignalParameters, location);
1475 for (qsizetype i = 0, end = handlerParameters.size(); i < end; i++) {
1476 const QStringView handlerParameter = handlerParameters.at(i);
1477 auto it = parameterNameIndexes.constFind(handlerParameter.toString());
1478 if (it == parameterNameIndexes.constEnd())
1480 const qsizetype j = *it;
1485 m_logger->log(QStringLiteral(
"Parameter %1 to signal handler for \"%2\""
1486 " is called \"%3\". The signal has a parameter"
1487 " of the same name in position %4.")
1489 .arg(handlerName, handlerParameter)
1491 qmlSignalParameters, location);
1495void QQmlJSImportVisitor::addDefaultProperties()
1497 QQmlJSScope::ConstPtr parentScope = m_currentScope->parentScope();
1498 if (m_currentScope == m_exportedRootScope || parentScope->isArrayScope()
1499 || m_currentScope->isInlineComponent())
1502 m_pendingDefaultProperties[m_currentScope->parentScope()] << m_currentScope;
1504 if (checkCustomParser(parentScope))
1508
1509
1510
1511
1512
1513
1514
1515
1516
1518 parentScope = parentScope->baseType();
1520 const QString defaultPropertyName =
1521 parentScope ? parentScope->defaultPropertyName() : QString();
1523 if (defaultPropertyName.isEmpty())
1528 QQmlJSMetaPropertyBinding binding(m_currentScope->sourceLocation(), defaultPropertyName);
1529 binding.setObject(QQmlJSUtils::getScopeName(m_currentScope, QQmlSA::ScopeType::QMLScope),
1530 QQmlJSScope::ConstPtr(m_currentScope));
1531 m_bindings.append(UnfinishedBinding { m_currentScope->parentScope(), [=]() {
return binding; },
1532 QQmlJSScope::UnnamedPropertyTarget });
1535void QQmlJSImportVisitor::breakInheritanceCycles(
const QQmlJSScope::Ptr &originalScope)
1537 QList<QQmlJSScope::ConstPtr> scopes;
1538 for (QQmlJSScope::ConstPtr scope = originalScope; scope;) {
1539 if (scopes.contains(scope)) {
1540 QString inheritenceCycle;
1541 for (
const auto &seen : std::as_const(scopes)) {
1542 inheritenceCycle.append(seen->baseTypeName());
1543 inheritenceCycle.append(QLatin1String(
" -> "));
1545 inheritenceCycle.append(scopes.first()->baseTypeName());
1547 const QString message = QStringLiteral(
"%1 is part of an inheritance cycle: %2")
1548 .arg(scope->internalName(), inheritenceCycle);
1549 m_logger->log(message, qmlInheritanceCycle, scope->sourceLocation());
1550 originalScope->clearBaseType();
1551 originalScope->setBaseTypeError(message);
1555 scopes.append(scope);
1557 const auto newScope = scope->baseType();
1558 if (newScope.isNull()) {
1559 const QString error = scope->baseTypeError();
1560 const QString name = scope->baseTypeName();
1561 if (!error.isEmpty()) {
1562 m_logger->log(error, qmlImport, scope->sourceLocation(),
true,
true);
1563 }
else if (!name.isEmpty() && !m_unresolvedTypes.hasSeen(scope)
1564 && !m_logger->isDisabled()) {
1566 name +
' '_L1 + wasNotFound +
' '_L1 + didYouAddAllImports,
1567 qmlImport, scope->sourceLocation(),
true,
true,
1568 QQmlJSUtils::didYouMean(scope->baseTypeName(),
1569 m_rootScopeImports.types().keys(),
1570 scope->sourceLocation()));
1578void QQmlJSImportVisitor::checkDeprecation(
const QQmlJSScope::ConstPtr &originalScope)
1580 for (QQmlJSScope::ConstPtr scope = originalScope; scope; scope = scope->baseType()) {
1581 for (
const QQmlJSAnnotation &annotation : scope->annotations()) {
1582 if (annotation.isDeprecation()) {
1583 QQQmlJSDeprecation deprecation = annotation.deprecation();
1586 QStringLiteral(
"Type \"%1\" is deprecated").arg(scope->internalName());
1588 if (!deprecation.reason.isEmpty())
1589 message.append(QStringLiteral(
" (Reason: %1)").arg(deprecation.reason));
1591 m_logger->log(message, qmlDeprecated, originalScope->sourceLocation());
1597void QQmlJSImportVisitor::checkGroupedAndAttachedScopes(QQmlJSScope::ConstPtr scope)
1601 if (checkCustomParser(scope))
1604 auto children = scope->childScopes();
1605 while (!children.isEmpty()) {
1606 auto childScope = children.takeFirst();
1607 const auto type = childScope->scopeType();
1609 case QQmlSA::ScopeType::GroupedPropertyScope:
1610 case QQmlSA::ScopeType::AttachedPropertyScope:
1611 if (!childScope->baseType()) {
1612 m_logger->log(QStringLiteral(
"unknown %1 property scope %2.")
1613 .arg(type == QQmlSA::ScopeType::GroupedPropertyScope
1614 ? QStringLiteral(
"grouped")
1615 : QStringLiteral(
"attached"),
1616 childScope->internalName()),
1617 qmlUnqualified, childScope->sourceLocation());
1619 children.append(childScope->childScopes());
1627void QQmlJSImportVisitor::checkForComponentTypeWithProperties(
const QQmlJSScope::ConstPtr &scope)
1629 const QQmlJSScope::ConstPtr base = scope->baseType();
1636 if (base->isComposite())
1639 if (base->internalName() !=
"QQmlComponent"_L1)
1642 const auto ownProperties = scope->ownProperties();
1643 for (
const auto &property : ownProperties) {
1644 m_logger->log(
"Component objects cannot declare new properties."_L1,
1645 qmlSyntax, property.sourceLocation());
1649bool QQmlJSImportVisitor::checkCustomParser(
const QQmlJSScope::ConstPtr &scope)
1651 return scope->isInCustomParserParent();
1654void QQmlJSImportVisitor::flushPendingSignalParameters()
1656 const QQmlJSMetaSignalHandler handler = m_signalHandlers[m_pendingSignalHandler];
1657 for (
const QString ¶meter : handler.signalParameters) {
1658 safeInsertJSIdentifier(m_currentScope, parameter,
1659 { QQmlJSScope::JavaScriptIdentifier::Injected,
1660 m_pendingSignalHandler, std::nullopt,
false });
1662 m_pendingSignalHandler = QQmlJS::SourceLocation();
1666
1667
1668
1669
1670
1671
1672QQmlJSMetaMethod::RelativeFunctionIndex
1673QQmlJSImportVisitor::addFunctionOrExpression(
const QQmlJSScope::ConstPtr &scope,
1674 const QString &name)
1676 auto &array = m_functionsAndExpressions[scope];
1677 array.emplaceBack(name);
1684 for (
const auto &function : std::as_const(m_functionStack))
1685 m_innerFunctions[function]++;
1686 m_functionStack.push({ scope, name });
1688 return QQmlJSMetaMethod::RelativeFunctionIndex {
int(array.size() - 1) };
1692
1693
1694
1695
1696
1697
1698
1699
1700void QQmlJSImportVisitor::forgetFunctionExpression(
const QString &name)
1702 auto nameToVerify = name.isEmpty() ? u"<anon>"_s : name;
1703 Q_UNUSED(nameToVerify);
1704 Q_ASSERT(!m_functionStack.isEmpty());
1705 Q_ASSERT(m_functionStack.top().name == nameToVerify);
1706 m_functionStack.pop();
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721int QQmlJSImportVisitor::synthesizeCompilationUnitRuntimeFunctionIndices(
1722 const QQmlJSScope::Ptr &scope,
int count)
const
1724 const auto suitableScope = [](
const QQmlJSScope::Ptr &scope) {
1725 const auto type = scope->scopeType();
1726 return type == QQmlSA::ScopeType::QMLScope
1727 || type == QQmlSA::ScopeType::GroupedPropertyScope
1728 || type == QQmlSA::ScopeType::AttachedPropertyScope;
1731 if (!suitableScope(scope))
1734 auto it = m_functionsAndExpressions.constFind(scope);
1735 if (it == m_functionsAndExpressions.cend())
1738 const auto &functionsAndExpressions = *it;
1739 for (
const QString &functionOrExpression : functionsAndExpressions) {
1740 scope->addOwnRuntimeFunctionIndex(
1741 static_cast<QQmlJSMetaMethod::AbsoluteFunctionIndex>(count));
1758 count += m_innerFunctions.value({ scope, functionOrExpression }, 0);
1764void QQmlJSImportVisitor::populateRuntimeFunctionIndicesForDocument()
const
1767 const auto synthesize = [&](
const QQmlJSScope::Ptr ¤t) {
1768 count = synthesizeCompilationUnitRuntimeFunctionIndices(current, count);
1770 QQmlJSUtils::traverseFollowingQmlIrObjectStructure(m_exportedRootScope, synthesize);
1773bool QQmlJSImportVisitor::visit(QQmlJS::AST::ExpressionStatement *ast)
1775 if (m_pendingSignalHandler.isValid()) {
1776 enterEnvironment(QQmlSA::ScopeType::SignalHandlerFunctionScope, u"signalhandler"_s,
1777 ast->firstSourceLocation());
1778 flushPendingSignalParameters();
1783void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ExpressionStatement *)
1785 if (m_currentScope->scopeType() == QQmlSA::ScopeType::SignalHandlerFunctionScope) {
1792 const QQmlJS::SourceLocation &srcLocation);
1795 QQmlJSLogger *logger)
1797 QStringView namespaceName{ superType };
1798 namespaceName = namespaceName.first(namespaceName.indexOf(u'.'));
1799 logger->log(u"Namespace '%1' of '%2' must start with an upper case letter."_s.arg(namespaceName)
1801 qmlUncreatableType, location,
true,
true);
1804bool QQmlJSImportVisitor::visit(UiObjectDefinition *definition)
1806 const QString superType = buildName(definition->qualifiedTypeNameId);
1808 const bool isRoot = !rootScopeIsValid();
1809 Q_ASSERT(!superType.isEmpty());
1814 const qsizetype indexOfTypeName = superType.lastIndexOf(u'.');
1815 const bool looksLikeGroupedProperty = superType.front().isLower();
1817 if (indexOfTypeName != -1 && looksLikeGroupedProperty) {
1818 logLowerCaseImport(superType, definition->qualifiedTypeNameId->identifierToken,
1822 if (!looksLikeGroupedProperty) {
1824 enterEnvironment(QQmlSA::ScopeType::QMLScope, superType,
1825 definition->firstSourceLocation());
1827 enterRootScope(QQmlSA::ScopeType::QMLScope, superType,
1828 definition->firstSourceLocation());
1829 m_currentScope->setIsRootFileComponentFlag(
true);
1830 m_currentScope->setIsSingleton(m_rootIsSingleton);
1833 const QTypeRevision revision = m_currentScope->baseTypeRevision();
1834 if (
auto base = m_currentScope->baseType(); base) {
1835 if (isRoot && base->internalName() == u"QQmlComponent") {
1836 m_logger->log(u"Qml top level type cannot be 'Component'."_s, qmlTopLevelComponent,
1837 definition->qualifiedTypeNameId->identifierToken,
true,
true);
1839 if (base->isSingleton() && m_currentScope->isComposite()) {
1840 m_logger->log(u"Singleton Type %1 is not creatable."_s.arg(
1841 m_currentScope->baseTypeName()),
1842 qmlUncreatableType, definition->qualifiedTypeNameId->identifierToken,
1845 }
else if (!base->isCreatable()) {
1847 m_logger->log(u"Type %1 is not creatable."_s.arg(m_currentScope->baseTypeName()),
1848 qmlUncreatableType, definition->qualifiedTypeNameId->identifierToken,
1852 if (m_nextIsInlineComponent) {
1853 Q_ASSERT(std::holds_alternative<InlineComponentNameType>(m_currentRootName));
1854 const QString &name = std::get<InlineComponentNameType>(m_currentRootName);
1855 m_currentScope->setIsInlineComponent(
true);
1856 m_currentScope->setInlineComponentName(name);
1857 m_currentScope->setOwnModuleName(m_exportedRootScope->moduleName());
1858 m_rootScopeImports.setType(name, { m_currentScope, revision });
1859 m_nextIsInlineComponent =
false;
1862 addDefaultProperties();
1863 Q_ASSERT(m_currentScope->scopeType() == QQmlSA::ScopeType::QMLScope);
1864 m_qmlTypes.append(m_currentScope);
1866 m_objectDefinitionScopes << m_currentScope;
1868 enterEnvironmentNonUnique(QQmlSA::ScopeType::GroupedPropertyScope, superType,
1869 definition->firstSourceLocation());
1870 m_bindings.append(createNonUniqueScopeBinding(m_currentScope, superType,
1871 definition->firstSourceLocation()));
1872 QQmlJSScope::resolveTypes(
1873 m_currentScope, m_rootScopeImports.contextualTypes(), &m_usedTypes);
1876 m_currentScope->setAnnotations(parseAnnotations(definition->annotations));
1881void QQmlJSImportVisitor::endVisit(UiObjectDefinition *)
1883 QQmlJSScope::resolveTypes(m_currentScope, m_rootScopeImports.contextualTypes(), &m_usedTypes);
1887bool QQmlJSImportVisitor::visit(UiInlineComponent *component)
1889 if (!std::holds_alternative<RootDocumentNameType>(m_currentRootName)) {
1890 m_logger->log(u"Nested inline components are not supported"_s, qmlSyntax,
1891 component->firstSourceLocation());
1895 const auto it = m_seenInlineComponents.constFind(component->name);
1896 if (it != m_seenInlineComponents.cend()) {
1897 m_logger->log(
"Duplicate inline component '%1'"_L1.arg(it.key()),
1898 qmlDuplicateInlineComponent, component->firstSourceLocation());
1899 m_logger->log(
"Note: previous component named '%1' here"_L1.arg(it.key()),
1900 qmlDuplicateInlineComponent, it.value(),
true,
true, {},
1901 component->firstSourceLocation().startLine);
1903 m_seenInlineComponents[component->name] = component->firstSourceLocation();
1906 m_nextIsInlineComponent =
true;
1907 m_currentRootName = component->name.toString();
1911void QQmlJSImportVisitor::endVisit(UiInlineComponent *component)
1913 m_currentRootName = RootDocumentNameType();
1914 if (m_nextIsInlineComponent) {
1915 m_logger->log(u"Inline component declaration must be followed by a typename"_s,
1916 qmlSyntax, component->firstSourceLocation());
1918 m_nextIsInlineComponent =
false;
1921bool QQmlJSImportVisitor::visit(UiPublicMember *publicMember)
1923 switch (publicMember->type) {
1924 case UiPublicMember::Signal: {
1925 const QString signalName = publicMember->name.toString();
1926 UiParameterList *param = publicMember->parameters;
1927 QQmlJSMetaMethod method;
1928 method.setMethodType(QQmlJSMetaMethodType::Signal);
1929 method.setReturnTypeName(QStringLiteral(
"void"));
1930 method.setMethodName(signalName);
1931 method.setSourceLocation(combine(publicMember->firstSourceLocation(),
1932 publicMember->lastSourceLocation()));
1934 method.addParameter(
1935 QQmlJSMetaParameter(
1936 param->name.toString(),
1937 param->type ? param->type->toString() : QString()
1939 param = param->next;
1941 m_currentScope->addOwnMethod(method);
1944 case UiPublicMember::Property: {
1945 const QString propertyName = publicMember->name.toString();
1946 QString typeName = buildName(publicMember->memberType);
1947 if (typeName.contains(u'.') && typeName.front().isLower()) {
1948 logLowerCaseImport(typeName, publicMember->typeToken, m_logger);
1952 const bool isAlias = (typeName == u"alias"_s);
1954 auto tryParseAlias = [&]() {
1956 if (!publicMember->statement) {
1957 m_logger->log(QStringLiteral(
"Invalid alias expression - an initializer is needed."),
1958 qmlSyntax, publicMember->memberType->firstSourceLocation());
1961 const auto expression = cast<ExpressionStatement *>(publicMember->statement);
1962 auto node = expression ? expression->expression :
nullptr;
1963 auto fex = cast<FieldMemberExpression *>(node);
1966 aliasExpr.prepend(u'.' + fex->name.toString());
1967 fex = cast<FieldMemberExpression *>(node);
1970 if (
const auto idExpression = cast<IdentifierExpression *>(node)) {
1971 aliasExpr.prepend(idExpression->name.toString());
1975 m_logger->log(QStringLiteral(
"Invalid alias expression. Only IDs and field "
1976 "member expressions can be aliased."),
1977 qmlSyntax, publicMember->statement->firstSourceLocation());
1982 if (m_rootScopeImports.hasType(typeName)
1983 && !m_rootScopeImports.type(typeName).scope.isNull()) {
1984 if (m_importTypeLocationMap.contains(typeName))
1985 m_usedTypes.insert(typeName);
1988 QQmlJSMetaProperty prop;
1989 prop.setPropertyName(propertyName);
1990 prop.setIsList(publicMember->typeModifier == QLatin1String(
"list"));
1991 prop.setIsWritable(!publicMember->isReadonly());
1992 prop.setIsFinal(publicMember->isFinal());
1993 prop.setIsVirtual(publicMember->isVirtual());
1994 prop.setIsOverride(publicMember->isOverride());
1995 prop.setAliasExpression(aliasExpr);
1996 prop.setSourceLocation(
1997 combine(publicMember->firstSourceLocation(), publicMember->colonToken));
1999 isAlias ? QQmlJSScope::ConstPtr() : m_rootScopeImports.type(typeName).scope;
2001 prop.setType(prop.isList() ? type->listType() : type);
2002 const QString internalName = type->internalName();
2003 prop.setTypeName(internalName.isEmpty() ? typeName : internalName);
2004 }
else if (!isAlias) {
2005 m_pendingPropertyTypes << PendingPropertyType { m_currentScope, prop.propertyName(),
2006 publicMember->firstSourceLocation() };
2007 prop.setTypeName(typeName);
2009 prop.setAnnotations(parseAnnotations(publicMember->annotations));
2010 if (publicMember->isDefaultMember())
2011 m_currentScope->setOwnDefaultPropertyName(prop.propertyName());
2012 prop.setIndex(m_currentScope->ownProperties().size());
2013 m_currentScope->insertPropertyIdentifier(prop);
2014 if (publicMember->isRequired())
2015 m_currentScope->setPropertyLocallyRequired(prop.propertyName(),
true);
2017 BindingExpressionParseResult parseResult = BindingExpressionParseResult::Invalid;
2021 parseBindingExpression(publicMember->name.toString(), publicMember->statement,
2027 if (parseResult == BindingExpressionParseResult::Script) {
2028 Q_ASSERT(!m_savedBindingOuterScope);
2029 m_savedBindingOuterScope = m_currentScope;
2030 enterEnvironment(QQmlSA::ScopeType::BindingFunctionScope, QStringLiteral(
"binding"),
2031 publicMember->statement->firstSourceLocation());
2041void QQmlJSImportVisitor::endVisit(UiPublicMember *publicMember)
2043 if (m_savedBindingOuterScope) {
2044 m_currentScope = m_savedBindingOuterScope;
2045 m_savedBindingOuterScope = {};
2047 forgetFunctionExpression(publicMember->name.toString());
2051bool QQmlJSImportVisitor::visit(UiRequired *required)
2053 const QString name = required->name.toString();
2055 m_requiredProperties << RequiredProperty { m_currentScope, name,
2056 required->firstSourceLocation() };
2058 m_currentScope->setPropertyLocallyRequired(name,
true);
2062void QQmlJSImportVisitor::visitFunctionExpressionHelper(QQmlJS::AST::FunctionExpression *fexpr)
2064 using namespace QQmlJS::AST;
2065 auto name = fexpr->name.toString();
2066 if (!name.isEmpty()) {
2067 QQmlJSMetaMethod method(name);
2068 method.setMethodType(QQmlJSMetaMethodType::Method);
2069 method.setSourceLocation(combine(fexpr->firstSourceLocation(), fexpr->lastSourceLocation()));
2071 if (!m_pendingMethodAnnotations.isEmpty()) {
2072 method.setAnnotations(m_pendingMethodAnnotations);
2073 m_pendingMethodAnnotations.clear();
2077 const bool parseTypes = m_scopesById.signaturesAreEnforced();
2079 bool formalsFullyTyped = parseTypes;
2080 bool anyFormalTyped =
false;
2081 PendingMethodTypeAnnotations pending{ m_currentScope, name, {} };
2084 for (
auto formals = fexpr->formals; formals; formals = formals->next) {
2085 PatternElement *e = formals->element;
2088 if (e->typeAnnotation && (e->bindingTarget || e->initializer))
2089 m_logger->log(
"Type annotations on default parameters are not supported"_L1,
2091 combine(e->firstSourceLocation(), e->lastSourceLocation()));
2094 if (
const auto *formals = parseTypes ? fexpr->formals :
nullptr) {
2095 const auto parameters = formals->formals();
2096 for (
const auto ¶meter : parameters) {
2097 const QString type = parameter.typeAnnotation
2098 ? parameter.typeAnnotation->type->toString()
2100 if (type.isEmpty()) {
2101 formalsFullyTyped =
false;
2102 method.addParameter(QQmlJSMetaParameter(parameter.id, QStringLiteral(
"var")));
2103 pending.locations.emplace_back();
2105 anyFormalTyped =
true;
2106 method.addParameter(QQmlJSMetaParameter(parameter.id, type));
2107 pending.locations.append(
2108 combine(parameter.typeAnnotation->firstSourceLocation(),
2109 parameter.typeAnnotation->lastSourceLocation()));
2115 method.setIsJavaScriptFunction(!formalsFullyTyped);
2121 if (parseTypes && fexpr->typeAnnotation) {
2122 method.setReturnTypeName(fexpr->typeAnnotation->type->toString());
2123 pending.locations.append(combine(fexpr->typeAnnotation->firstSourceLocation(),
2124 fexpr->typeAnnotation->lastSourceLocation()));
2125 }
else if (anyFormalTyped) {
2126 method.setReturnTypeName(QStringLiteral(
"void"));
2128 method.setReturnTypeName(QStringLiteral(
"var"));
2131 const auto &locs = pending.locations;
2132 if (std::any_of(locs.cbegin(), locs.cend(), [](
const auto &loc) {
return loc.isValid(); }))
2133 m_pendingMethodTypeAnnotations << pending;
2135 method.setJsFunctionIndex(addFunctionOrExpression(m_currentScope, method.methodName()));
2137 if (m_currentScope->scopeType() != QQmlSA::ScopeType::QMLScope) {
2139 const QQmlJS::SourceLocation functionLocation = fexpr->identifierToken.isValid()
2140 ? fexpr->identifierToken
2141 : fexpr->functionToken;
2142 safeInsertJSIdentifier(m_currentScope, name,
2143 { QQmlJSScope::JavaScriptIdentifier::LexicalScoped,
2144 functionLocation, method.returnTypeName(),
2147 m_currentScope->addOwnMethod(method);
2149 enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, name, fexpr->firstSourceLocation());
2151 addFunctionOrExpression(m_currentScope, QStringLiteral(
"<anon>"));
2152 enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, QStringLiteral(
"<anon>"),
2153 fexpr->firstSourceLocation());
2157bool QQmlJSImportVisitor::visit(QQmlJS::AST::FunctionExpression *fexpr)
2159 visitFunctionExpressionHelper(fexpr);
2163void QQmlJSImportVisitor::endVisit(QQmlJS::AST::FunctionExpression *fexpr)
2165 forgetFunctionExpression(fexpr->name.toString());
2169bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiSourceElement *srcElement)
2171 m_pendingMethodAnnotations = parseAnnotations(srcElement->annotations);
2175bool QQmlJSImportVisitor::visit(QQmlJS::AST::FunctionDeclaration *fdecl)
2177 if (!fdecl->name.isEmpty()) {
2178 const QString name = fdecl->name.toString();
2179 if (
auto previousDeclaration = m_currentScope->ownJSIdentifier(name)) {
2180 m_logger->log(
"Identifier '%1' has already been declared"_L1.arg(name), qmlSyntax,
2181 fdecl->identifierToken);
2182 m_logger->log(
"Note: previous declaration of '%1' here"_L1.arg(name), qmlSyntax,
2183 previousDeclaration->location);
2186 visitFunctionExpressionHelper(fdecl);
2190void QQmlJSImportVisitor::endVisit(QQmlJS::AST::FunctionDeclaration *fdecl)
2192 forgetFunctionExpression(fdecl->name.toString());
2196bool QQmlJSImportVisitor::visit(QQmlJS::AST::ClassExpression *ast)
2198 QQmlJSMetaProperty prop;
2199 prop.setPropertyName(ast->name.toString());
2200 m_currentScope->addOwnProperty(prop);
2201 enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, ast->name.toString(),
2202 ast->firstSourceLocation());
2206void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ClassExpression *)
2212 QQmlJS::AST::ArgumentList *args)
2214 QStringView contextString;
2215 QStringView mainString;
2216 QStringView commentString;
2217 auto registerContextString = [&](QStringView string) {
2218 contextString = string;
2221 auto registerMainString = [&](QStringView string) {
2222 mainString = string;
2225 auto registerCommentString = [&](QStringView string) {
2226 commentString = string;
2229 auto finalizeBinding = [&](QV4::CompiledData::Binding::Type type,
2230 QV4::CompiledData::TranslationData data) {
2231 if (type == QV4::CompiledData::Binding::Type_Translation) {
2232 binding.setTranslation(mainString, commentString, contextString, data.number);
2233 }
else if (type == QV4::CompiledData::Binding::Type_TranslationById) {
2234 binding.setTranslationId(mainString, data.number);
2236 binding.setStringLiteral(mainString);
2239 QmlIR::tryGeneratingTranslationBindingBase(
2241 registerMainString, registerCommentString, registerContextString, finalizeBinding);
2244QQmlJSImportVisitor::BindingExpressionParseResult
2245QQmlJSImportVisitor::parseBindingExpression(
2246 const QString &name,
const QQmlJS::AST::Statement *statement,
2247 const UiPublicMember *associatedPropertyDefinition)
2249 if (statement ==
nullptr)
2250 return BindingExpressionParseResult::Invalid;
2252 const auto *exprStatement = cast<
const ExpressionStatement *>(statement);
2254 if (exprStatement ==
nullptr) {
2255 QQmlJS::SourceLocation location = statement->firstSourceLocation();
2257 if (
const auto *block = cast<
const Block *>(statement); block && block->statements) {
2258 location = block->statements->firstSourceLocation();
2261 QQmlJSMetaPropertyBinding binding(location, name);
2262 binding.setScriptBinding(addFunctionOrExpression(m_currentScope, name),
2263 QQmlSA::ScriptBindingKind::PropertyBinding, ScriptValue_Function);
2264 m_bindings.append(UnfinishedBinding {
2266 [binding = std::move(binding)]() {
return binding; }
2268 return BindingExpressionParseResult::Script;
2271 auto expr = exprStatement->expression;
2272 QQmlJSMetaPropertyBinding binding(
2273 combine(expr->firstSourceLocation(), expr->lastSourceLocation()),
2276 ScriptBindingValueType scriptBindingValuetype = ScriptValue_Unknown;
2278 switch (expr->kind) {
2279 case Node::Kind_TrueLiteral:
2280 binding.setBoolLiteral(
true);
2282 case Node::Kind_FalseLiteral:
2283 binding.setBoolLiteral(
false);
2285 case Node::Kind_NullExpression:
2286 binding.setNullLiteral();
2288 case Node::Kind_IdentifierExpression: {
2289 auto idExpr = QQmlJS::AST::cast<QQmlJS::AST::IdentifierExpression *>(expr);
2291 if (idExpr->name == u"undefined")
2292 scriptBindingValuetype = ScriptValue_Undefined;
2295 case Node::Kind_FunctionDeclaration:
2296 case Node::Kind_FunctionExpression:
2297 case Node::Kind_Block: {
2298 scriptBindingValuetype = ScriptValue_Function;
2301 case Node::Kind_NumericLiteral:
2302 binding.setNumberLiteral(cast<NumericLiteral *>(expr)->value);
2304 case Node::Kind_StringLiteral:
2305 binding.setStringLiteral(cast<StringLiteral *>(expr)->value);
2307 case Node::Kind_RegExpLiteral:
2308 binding.setRegexpLiteral(cast<RegExpLiteral *>(expr)->pattern);
2310 case Node::Kind_TemplateLiteral: {
2311 auto templateLit = QQmlJS::AST::cast<QQmlJS::AST::TemplateLiteral *>(expr);
2312 Q_ASSERT(templateLit);
2313 if (templateLit->hasNoSubstitution) {
2314 binding.setStringLiteral(templateLit->value);
2316 binding.setScriptBinding(addFunctionOrExpression(m_currentScope, name),
2317 QQmlSA::ScriptBindingKind::PropertyBinding);
2318 for (QQmlJS::AST::TemplateLiteral *l = templateLit; l; l = l->next) {
2319 if (QQmlJS::AST::ExpressionNode *expression = l->expression)
2320 expression->accept(
this);
2326 if (QQmlJS::AST::UnaryMinusExpression *unaryMinus = QQmlJS::AST::cast<QQmlJS::AST::UnaryMinusExpression *>(expr)) {
2327 if (QQmlJS::AST::NumericLiteral *lit = QQmlJS::AST::cast<QQmlJS::AST::NumericLiteral *>(unaryMinus->expression))
2328 binding.setNumberLiteral(-lit->value);
2329 }
else if (QQmlJS::AST::CallExpression *call = QQmlJS::AST::cast<QQmlJS::AST::CallExpression *>(expr)) {
2330 if (QQmlJS::AST::IdentifierExpression *base = QQmlJS::AST::cast<QQmlJS::AST::IdentifierExpression *>(call->base))
2331 handleTranslationBinding(binding, base->name, call->arguments);
2336 if (!binding.isValid()) {
2338 binding.setScriptBinding(addFunctionOrExpression(m_currentScope, name),
2339 QQmlSA::ScriptBindingKind::PropertyBinding,
2340 scriptBindingValuetype);
2342 m_bindings.append(UnfinishedBinding { m_currentScope, [=]() {
return binding; } });
2345 if (binding.bindingType() == QQmlSA::BindingType::Translation
2346 || binding.bindingType() == QQmlSA::BindingType::TranslationById) {
2347 return BindingExpressionParseResult::Translation;
2349 if (!QQmlJSMetaPropertyBinding::isLiteralBinding(binding.bindingType()))
2350 return BindingExpressionParseResult::Script;
2352 if (associatedPropertyDefinition)
2353 handleLiteralBinding(binding, associatedPropertyDefinition);
2355 return BindingExpressionParseResult::Literal;
2358bool QQmlJSImportVisitor::isImportPrefix(QString prefix)
const
2360 if (prefix.isEmpty() || !prefix.front().isUpper())
2363 return m_rootScopeImports.isNullType(prefix);
2366void QQmlJSImportVisitor::handleIdDeclaration(QQmlJS::AST::UiScriptBinding *scriptBinding)
2368 if (m_currentScope->scopeType() != QQmlJSScope::ScopeType::QMLScope) {
2369 m_logger->log(u"id declarations are only allowed in objects"_s, qmlSyntax,
2370 scriptBinding->statement->firstSourceLocation());
2373 const auto *statement = cast<ExpressionStatement *>(scriptBinding->statement);
2375 m_logger->log(u"id must be followed by an identifier"_s, qmlSyntax,
2376 scriptBinding->statement->firstSourceLocation());
2379 const QString name = [&]() {
2380 if (
const auto *idExpression = cast<IdentifierExpression *>(statement->expression))
2381 return idExpression->name.toString();
2382 else if (
const auto *idString = cast<StringLiteral *>(statement->expression)) {
2383 m_logger->log(u"ids do not need quotation marks"_s, qmlSyntaxIdQuotation,
2384 idString->firstSourceLocation());
2385 return idString->value.toString();
2387 m_logger->log(u"Failed to parse id"_s, qmlSyntax,
2388 statement->expression->firstSourceLocation());
2392 if (!name.isEmpty() && !name.front().isLower() && name.front() != u'_') {
2393 m_logger->log(u"Id must start with a lower case letter or an '_'"_s, qmlSyntax,
2394 statement->expression->firstSourceLocation());
2397 m_currentScope->setIdSourceLocation(combine(scriptBinding->statement->firstSourceLocation(),
2398 scriptBinding->statement->lastSourceLocation()));
2399 if (m_scopesById.existsAnywhereInDocument(name)) {
2402 breakInheritanceCycles(m_currentScope);
2403 m_scopesById.possibleScopes(
2404 name, m_currentScope, Default,
2405 [&](
const QQmlJSScope::ConstPtr &otherScopeWithID,
2406 QQmlJSScopesById::Confidence confidence) {
2408 Q_UNUSED(confidence);
2410 auto otherLocation = otherScopeWithID->sourceLocation();
2414 m_logger->log(u"Found a duplicated id. id %1 was first declared at %2:%3"_s.arg(
2415 name, QString::number(otherLocation.startLine),
2416 QString::number(otherLocation.startColumn)),
2417 qmlSyntaxDuplicateIds,
2418 scriptBinding->firstSourceLocation());
2419 return QQmlJSScopesById::CallbackResult::ContinueSearch;
2422 if (!name.isEmpty())
2423 m_scopesById.insert(name, m_currentScope);
2426void QQmlJSImportVisitor::handleLiteralBinding(
const QQmlJSMetaPropertyBinding &binding,
2427 const UiPublicMember *associatedPropertyDefinition)
2431 Q_UNUSED(associatedPropertyDefinition);
2435
2436
2437
2438
2439
2442 const QQmlJS::SourceLocation &srcLocation)
2444 const auto createBinding = [=]() {
2445 const QQmlJSScope::ScopeType type = scope->scopeType();
2452 const auto propertyBindings = scope->parentScope()->ownPropertyBindings(name);
2453 const bool alreadyHasBinding =
std::any_of(propertyBindings.first, propertyBindings.second,
2454 [&](
const QQmlJSMetaPropertyBinding &binding) {
2455 return binding.bindingType() == bindingType;
2457 if (alreadyHasBinding)
2458 return QQmlJSMetaPropertyBinding(QQmlJS::SourceLocation {});
2461 if (type == QQmlSA::ScopeType::GroupedPropertyScope)
2462 binding.setGroupBinding(
static_cast<QSharedPointer<QQmlJSScope>>(scope));
2464 binding.setAttachedBinding(
static_cast<QSharedPointer<QQmlJSScope>>(scope));
2467 return { scope->parentScope(), createBinding };
2470bool QQmlJSImportVisitor::visit(UiScriptBinding *scriptBinding)
2472 Q_ASSERT(!m_savedBindingOuterScope);
2473 Q_ASSERT(!m_thisScriptBindingIsJavaScript);
2474 m_savedBindingOuterScope = m_currentScope;
2475 const auto id = scriptBinding->qualifiedId;
2476 if (!id->next && id->name == QLatin1String(
"id")) {
2477 handleIdDeclaration(scriptBinding);
2484 for (; group->next; group = group->next) {
2485 const QString name = group->name.toString();
2489 if (group == id && isImportPrefix(name)) {
2490 prefix = name + u'.';
2494 const bool isAttachedProperty = name.front().isUpper();
2495 if (isAttachedProperty) {
2497 enterEnvironmentNonUnique(QQmlSA::ScopeType::AttachedPropertyScope, prefix + name,
2498 group->firstSourceLocation());
2501 enterEnvironmentNonUnique(QQmlSA::ScopeType::GroupedPropertyScope, prefix + name,
2502 group->firstSourceLocation());
2504 m_bindings.append(createNonUniqueScopeBinding(m_currentScope, prefix + name,
2505 group->firstSourceLocation()));
2510 const auto name = group->name.toString();
2514 const auto signal = QQmlSignalNames::handlerNameToSignalName(name);
2516 if (!signal.has_value() || m_currentScope->hasProperty(name)) {
2517 m_propertyBindings[m_currentScope].append(
2518 { m_savedBindingOuterScope, group->firstSourceLocation(), name });
2520 auto result = parseBindingExpression(name, scriptBinding->statement);
2521 m_thisScriptBindingIsJavaScript = (result == BindingExpressionParseResult::Script);
2523 const auto statement = scriptBinding->statement;
2524 QStringList signalParameters;
2526 if (ExpressionStatement *expr = cast<ExpressionStatement *>(statement)) {
2527 if (FunctionExpression *func = expr->expression->asFunctionDefinition()) {
2528 for (FormalParameterList *formal = func->formals; formal; formal = formal->next)
2529 signalParameters << formal->element->bindingIdentifier.toString();
2533 QQmlJSMetaMethod scopeSignal;
2534 const auto methods = m_currentScope->methods(*signal, QQmlJSMetaMethodType::Signal);
2535 if (!methods.isEmpty())
2536 scopeSignal = methods[0];
2538 const auto firstSourceLocation = statement->firstSourceLocation();
2539 bool hasMultilineStatementBody =
2540 statement->lastSourceLocation().startLine > firstSourceLocation.startLine;
2541 m_pendingSignalHandler = firstSourceLocation;
2542 m_signalHandlers.insert(firstSourceLocation,
2543 { scopeSignal.parameterNames(), hasMultilineStatementBody });
2547 const auto index = addFunctionOrExpression(m_currentScope, name);
2548 const auto createBinding = [
2550 scope = m_currentScope,
2551 signalName = *signal,
2554 firstSourceLocation,
2555 groupLocation = group->firstSourceLocation(),
2556 signalParameters]() {
2558 Q_ASSERT(scope->isFullyResolved());
2559 QQmlSA::ScriptBindingKind kind = QQmlSA::ScriptBindingKind::Invalid;
2560 const auto methods = scope->methods(signalName, QQmlJSMetaMethodType::Signal);
2561 if (!methods.isEmpty()) {
2562 kind = QQmlSA::ScriptBindingKind::SignalHandler;
2563 checkSignal(scope, groupLocation, name, signalParameters);
2564 }
else if (QQmlJSUtils::propertyFromChangedHandler(scope, name).has_value()) {
2565 kind = QQmlSA::ScriptBindingKind::ChangeHandler;
2566 checkSignal(scope, groupLocation, name, signalParameters);
2567 }
else if (scope->hasProperty(name)) {
2570 kind = QQmlSA::ScriptBindingKind::PropertyBinding;
2571 m_signalHandlers.remove(firstSourceLocation);
2574 checkSignal(scope, groupLocation, name, signalParameters);
2577 QQmlJSMetaPropertyBinding binding(firstSourceLocation, name);
2578 binding.setScriptBinding(index, kind, ScriptValue_Function);
2581 m_bindings.append(UnfinishedBinding { m_currentScope, createBinding });
2582 m_thisScriptBindingIsJavaScript =
true;
2588 while (m_currentScope->scopeType() == QQmlSA::ScopeType::GroupedPropertyScope
2589 || m_currentScope->scopeType() == QQmlSA::ScopeType::AttachedPropertyScope) {
2594 enterEnvironment(QQmlSA::ScopeType::SignalHandlerFunctionScope,
2596 scriptBinding->statement->firstSourceLocation());
2598 enterEnvironment(QQmlSA::ScopeType::BindingFunctionScope,
2600 scriptBinding->statement->firstSourceLocation());
2606void QQmlJSImportVisitor::endVisit(UiScriptBinding *)
2608 if (m_savedBindingOuterScope) {
2609 m_currentScope = m_savedBindingOuterScope;
2610 m_savedBindingOuterScope = {};
2616 if (m_thisScriptBindingIsJavaScript) {
2617 m_thisScriptBindingIsJavaScript =
false;
2618 Q_ASSERT(!m_functionStack.isEmpty());
2619 m_functionStack.pop();
2623bool QQmlJSImportVisitor::visit(UiArrayBinding *arrayBinding)
2625 enterEnvironment(QQmlSA::ScopeType::QMLScope, buildName(arrayBinding->qualifiedId),
2626 arrayBinding->firstSourceLocation());
2627 m_currentScope->setIsArrayScope(
true);
2634void QQmlJSImportVisitor::endVisit(UiArrayBinding *arrayBinding)
2641 const auto children = m_currentScope->childScopes();
2642 const auto propertyName = QQmlJSUtils::getScopeName(m_currentScope, QQmlSA::ScopeType::QMLScope);
2645 if (checkCustomParser(m_currentScope)) {
2652 for (
auto element = arrayBinding->members; element; element = element->next, ++i) {
2653 const auto &type = children[i];
2654 if ((type->scopeType() != QQmlSA::ScopeType::QMLScope)) {
2655 m_logger->log(u"Declaring an object which is not a Qml object"
2656 " as a list member."_s, qmlSyntax, element->firstSourceLocation());
2659 m_pendingPropertyObjectBindings
2660 << PendingPropertyObjectBinding { m_currentScope, type, propertyName,
2661 element->firstSourceLocation(),
false };
2662 QQmlJSMetaPropertyBinding binding(element->firstSourceLocation(), propertyName);
2663 binding.setObject(QQmlJSUtils::getScopeName(type, QQmlSA::ScopeType::QMLScope),
2664 QQmlJSScope::ConstPtr(type));
2665 m_bindings.append(UnfinishedBinding {
2667 [binding = std::move(binding)]() {
return binding; },
2668 QQmlJSScope::ListPropertyTarget
2673bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiEnumDeclaration *uied)
2675 QQmlJSMetaEnum qmlEnum(uied->name.toString());
2676 qmlEnum.setIsQml(
true);
2677 qmlEnum.setLineNumber(uied->enumToken.startLine);
2678 for (
const auto *member = uied->members; member; member = member->next) {
2679 qmlEnum.addKey(member->member.toString());
2680 qmlEnum.addValue(
int(member->value));
2682 m_currentScope->addOwnEnumeration(qmlEnum);
2686void QQmlJSImportVisitor::addImportWithLocation(
2687 const QString &name,
const QQmlJS::SourceLocation &loc,
bool hadWarnings)
2689 if (m_importTypeLocationMap.contains(name)
2690 && m_importTypeLocationMap.values(name).contains(loc)) {
2694 m_importTypeLocationMap.insert(name, loc);
2699 if (!hadWarnings && loc.isValid())
2700 m_importLocations.insert(loc);
2703QList<QQmlJS::DiagnosticMessage> QQmlJSImportVisitor::importFromHost(
2704 const QString &path,
const QString &prefix,
const QQmlJS::SourceLocation &location)
2706 QFileInfo fileInfo(path);
2707 if (!fileInfo.exists()) {
2708 m_logger->log(
"File or directory you are trying to import does not exist: %1."_L1.arg(path),
2709 qmlImport, location);
2713 if (fileInfo.isFile()) {
2714 const auto scope = m_importer->importFile(path);
2715 const QString actualPrefix = prefix.isEmpty() ? scope->internalName() : prefix;
2716 m_rootScopeImports.setType(actualPrefix, { scope, QTypeRevision() });
2717 addImportWithLocation(actualPrefix, location,
false);
2721 if (fileInfo.isDir()) {
2722 auto scopes = m_importer->importDirectory(path, prefix);
2723 const auto types = scopes.types();
2724 const auto warnings = scopes.warnings();
2725 m_rootScopeImports.add(std::move(scopes));
2726 for (
auto it = types.keyBegin(), end = types.keyEnd(); it != end; it++)
2727 addImportWithLocation(*it, location, !warnings.isEmpty());
2732 "%1 is neither a file nor a directory. Are sure the import path is correct?"_L1.arg(
2734 qmlImport, location);
2738QList<QQmlJS::DiagnosticMessage> QQmlJSImportVisitor::importFromQrc(
2739 const QString &path,
const QString &prefix,
const QQmlJS::SourceLocation &location)
2741 Q_ASSERT(path.startsWith(u':'));
2742 const QQmlJSResourceFileMapper *mapper = m_importer->resourceFileMapper();
2746 const auto pathNoColon = QStringView(path).mid(1);
2747 if (mapper->isFile(pathNoColon)) {
2748 const auto entry = m_importer->resourceFileMapper()->entry(
2749 QQmlJSResourceFileMapper::resourceFileFilter(pathNoColon.toString()));
2750 const auto scope = m_importer->importFile(entry.filePath);
2751 const QString actualPrefix =
2752 prefix.isEmpty() ? QFileInfo(entry.resourcePath).baseName() : prefix;
2753 m_rootScopeImports.setType(actualPrefix, { scope, QTypeRevision() });
2754 addImportWithLocation(actualPrefix, location,
false);
2758 auto scopes = m_importer->importDirectory(path, prefix);
2759 const auto types = scopes.types();
2760 const auto warnings = scopes.warnings();
2761 m_rootScopeImports.add(std::move(scopes));
2762 for (
auto it = types.keyBegin(), end = types.keyEnd(); it != end; it++)
2763 addImportWithLocation(*it, location, !warnings.isEmpty());
2767bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiImport *import)
2770 QString prefix = QLatin1String(
"");
2771 if (import->asToken.isValid()) {
2772 prefix += import->importId;
2773 if (!import->importId.isEmpty() && !import->importId.front().isUpper()) {
2774 m_logger->log(u"Import qualifier '%1' must start with a capital letter."_s.arg(
2776 qmlImport, import->importIdToken,
true,
true);
2778 m_seenModuleQualifiers.append(prefix);
2781 const QString filename = import->fileName.toString();
2782 if (!filename.isEmpty()) {
2783 const QUrl url(filename);
2784 const QString scheme = url.scheme();
2785 const QQmlJS::SourceLocation importLocation = import->firstSourceLocation();
2786 if (scheme ==
""_L1) {
2787 QFileInfo fileInfo(url.path());
2788 QString absolute = fileInfo.isRelative()
2789 ? QDir::cleanPath(QDir(m_implicitImportDirectory).filePath(filename))
2791 auto warnings = absolute.startsWith(u':')
2792 ? importFromQrc(absolute, prefix, importLocation)
2793 : importFromHost(absolute, prefix, importLocation);
2794 processImportWarnings(
"path \"%1\""_L1.arg(url.path()), warnings, importLocation);
2796 }
else if (scheme ==
"file"_L1) {
2797 auto warnings = importFromHost(url.path(), prefix, importLocation);
2798 processImportWarnings(
"URL \"%1\""_L1.arg(url.path()), warnings, importLocation);
2800 }
else if (scheme ==
"qrc"_L1) {
2801 auto warnings = importFromQrc(
":"_L1 + url.path(), prefix, importLocation);
2802 processImportWarnings(
"URL \"%1\""_L1.arg(url.path()), warnings, importLocation);
2805 m_logger->log(
"Unknown import syntax. Imports can be paths, qrc urls or file urls"_L1,
2806 qmlImport, import->firstSourceLocation());
2810 const QString path = buildName(import->importUri);
2812 QStringList staticModulesProvided;
2814 auto imported = m_importer->importModule(
2815 path, prefix, import->version ? import->version->version : QTypeRevision(),
2816 &staticModulesProvided);
2817 const auto types = imported.types();
2818 const auto warnings = imported.warnings();
2819 m_rootScopeImports.add(std::move(imported));
2820 for (
auto it = types.keyBegin(), end = types.keyEnd(); it != end; it++)
2821 addImportWithLocation(*it, import->firstSourceLocation(), !warnings.isEmpty());
2823 if (prefix.isEmpty()) {
2824 for (
const QString &staticModule : std::as_const(staticModulesProvided)) {
2826 if (path != staticModule && m_importStaticModuleLocationMap.contains(staticModule))
2829 m_importStaticModuleLocationMap[staticModule] = import->firstSourceLocation();
2833 processImportWarnings(
2834 QStringLiteral(
"module \"%1\"").arg(path), warnings, import->firstSourceLocation());
2838#if QT_VERSION >= QT_VERSION_CHECK(6
, 6
, 0
)
2840void handlePragmaValues(QQmlJS::AST::UiPragma *pragma, F &&assign)
2842 for (
const QQmlJS::AST::UiPragmaValueList *v = pragma->values; v; v = v->next)
2847void handlePragmaValues(QQmlJS::AST::UiPragma *pragma, F &&assign)
2849 assign(pragma->value);
2853bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiPragma *pragma)
2855 if (pragma->name == u"Strict"_s) {
2860 if (!m_logger->wasCategoryChanged(qmlCompiler))
2861 m_logger->setCategorySeverity(qmlCompiler, QQmlJS::WarningSeverity::Warning);
2862 }
else if (pragma->name == u"Singleton") {
2863 m_rootIsSingleton =
true;
2864 }
else if (pragma->name == u"ComponentBehavior") {
2865 handlePragmaValues(pragma, [
this, pragma](QStringView value) {
2866 if (value == u"Bound") {
2867 m_scopesById.setComponentsAreBound(
true);
2868 }
else if (value == u"Unbound") {
2869 m_scopesById.setComponentsAreBound(
false);
2871 m_logger->log(u"Unknown argument \"%1\" to pragma ComponentBehavior"_s.arg(value),
2872 qmlSyntax, pragma->firstSourceLocation());
2875 }
else if (pragma->name == u"FunctionSignatureBehavior") {
2876 handlePragmaValues(pragma, [
this, pragma](QStringView value) {
2877 if (value == u"Enforced") {
2878 m_scopesById.setSignaturesAreEnforced(
true);
2879 }
else if (value == u"Ignored") {
2880 m_scopesById.setSignaturesAreEnforced(
false);
2883 u"Unknown argument \"%1\" to pragma FunctionSignatureBehavior"_s.arg(value),
2884 qmlSyntax, pragma->firstSourceLocation());
2887 }
else if (pragma->name == u"ValueTypeBehavior") {
2888 handlePragmaValues(pragma, [
this, pragma](QStringView value) {
2889 if (value == u"Copy") {
2891 }
else if (value == u"Reference") {
2893 }
else if (value == u"Addressable") {
2894 m_scopesById.setValueTypesAreAddressable(
true);
2895 }
else if (value == u"Inaddressable") {
2896 m_scopesById.setValueTypesAreAddressable(
false);
2898 m_logger->log(u"Unknown argument \"%1\" to pragma ValueTypeBehavior"_s.arg(value),
2899 qmlSyntax, pragma->firstSourceLocation());
2907void QQmlJSImportVisitor::throwRecursionDepthError()
2909 m_logger->log(QStringLiteral(
"Maximum statement or expression depth exceeded"),
2910 qmlRecursionDepthErrors, QQmlJS::SourceLocation());
2913bool QQmlJSImportVisitor::visit(QQmlJS::AST::ClassDeclaration *ast)
2915 enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, ast->name.toString(),
2916 ast->firstSourceLocation());
2920void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ClassDeclaration *)
2925bool QQmlJSImportVisitor::visit(QQmlJS::AST::ForStatement *ast)
2927 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"forloop"),
2928 ast->firstSourceLocation());
2932void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ForStatement *)
2937bool QQmlJSImportVisitor::visit(QQmlJS::AST::ForEachStatement *ast)
2939 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"foreachloop"),
2940 ast->firstSourceLocation());
2944void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ForEachStatement *)
2949bool QQmlJSImportVisitor::visit(QQmlJS::AST::Block *ast)
2951 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"block"),
2952 ast->firstSourceLocation());
2954 if (m_pendingSignalHandler.isValid())
2955 flushPendingSignalParameters();
2960void QQmlJSImportVisitor::endVisit(QQmlJS::AST::Block *)
2965bool QQmlJSImportVisitor::visit(QQmlJS::AST::CaseBlock *ast)
2967 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"case"),
2968 ast->firstSourceLocation());
2972void QQmlJSImportVisitor::endVisit(QQmlJS::AST::CaseBlock *)
2977bool QQmlJSImportVisitor::visit(QQmlJS::AST::Catch *catchStatement)
2979 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"catch"),
2980 catchStatement->firstSourceLocation());
2984void QQmlJSImportVisitor::endVisit(QQmlJS::AST::Catch *)
2989bool QQmlJSImportVisitor::visit(QQmlJS::AST::WithStatement *ast)
2991 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"with"),
2992 ast->firstSourceLocation());
2994 m_logger->log(QStringLiteral(
"with statements are strongly discouraged in QML "
2995 "and might cause false positives when analysing unqualified "
2997 qmlWith, ast->firstSourceLocation());
3002void QQmlJSImportVisitor::endVisit(QQmlJS::AST::WithStatement *)
3007bool QQmlJSImportVisitor::visit(QQmlJS::AST::FormalParameterList *fpl)
3009 const auto &boundedNames = fpl->boundNames();
3010 for (
auto const &boundName : boundedNames) {
3012 std::optional<QString> typeName;
3013 if (TypeAnnotation *annotation = boundName.typeAnnotation.data())
3014 if (Type *type = annotation->type)
3015 typeName = type->toString();
3016 safeInsertJSIdentifier(m_currentScope, boundName.id,
3017 { QQmlJSScope::JavaScriptIdentifier::Parameter,
3018 boundName.location, typeName,
false });
3023bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiObjectBinding *uiob)
3027 Q_ASSERT(uiob->qualifiedTypeNameId);
3029 bool needsResolution =
false;
3030 int scopesEnteredCounter = 0;
3032 const QString typeName = buildName(uiob->qualifiedTypeNameId);
3033 if (typeName.front().isLower() && typeName.contains(u'.')) {
3034 logLowerCaseImport(typeName, uiob->qualifiedTypeNameId->identifierToken, m_logger);
3038 for (
auto group = uiob->qualifiedId; group->next; group = group->next) {
3039 const QString idName = group->name.toString();
3041 if (idName.isEmpty())
3044 if (group == uiob->qualifiedId && isImportPrefix(idName)) {
3045 prefix = idName + u'.';
3049 const auto scopeKind = idName.front().isUpper() ? QQmlSA::ScopeType::AttachedPropertyScope
3050 : QQmlSA::ScopeType::GroupedPropertyScope;
3053 enterEnvironmentNonUnique(scopeKind, prefix + idName, group->firstSourceLocation());
3055 m_bindings.append(createNonUniqueScopeBinding(m_currentScope, prefix + idName,
3056 group->firstSourceLocation()));
3058 ++scopesEnteredCounter;
3059 needsResolution = needsResolution || !exists;
3064 for (
int i=0; i < scopesEnteredCounter; ++i) {
3069 if (needsResolution) {
3070 QQmlJSScope::resolveTypes(
3071 m_currentScope, m_rootScopeImports.contextualTypes(), &m_usedTypes);
3074 enterEnvironment(QQmlSA::ScopeType::QMLScope, typeName,
3075 uiob->qualifiedTypeNameId->identifierToken);
3077 m_qmlTypes.append(m_currentScope);
3078 m_objectBindingScopes << m_currentScope;
3082void QQmlJSImportVisitor::endVisit(QQmlJS::AST::UiObjectBinding *uiob)
3084 QQmlJSScope::resolveTypes(m_currentScope, m_rootScopeImports.contextualTypes(), &m_usedTypes);
3086 const QQmlJSScope::Ptr childScope = m_currentScope;
3089 auto group = uiob->qualifiedId;
3090 int scopesEnteredCounter = 0;
3093 for (; group->next; group = group->next) {
3094 const QString idName = group->name.toString();
3096 if (idName.isEmpty())
3099 if (group == uiob->qualifiedId && isImportPrefix(idName)) {
3100 prefix = idName + u'.';
3104 const auto scopeKind = idName.front().isUpper() ? QQmlSA::ScopeType::AttachedPropertyScope
3105 : QQmlSA::ScopeType::GroupedPropertyScope;
3107 [[maybe_unused]]
bool exists =
3108 enterEnvironmentNonUnique(scopeKind, prefix + idName, group->firstSourceLocation());
3110 scopesEnteredCounter++;
3118 const QString propertyName = group->name.toString();
3120 if (m_currentScope->isNameDeferred(propertyName)) {
3121 bool foundIds =
false;
3122 QList<QQmlJSScope::ConstPtr> childScopes { childScope };
3124 while (!childScopes.isEmpty()) {
3125 const QQmlJSScope::ConstPtr scope = childScopes.takeFirst();
3126 m_scopesById.possibleIds(
3127 scope, scope, Default,
3128 [&](
const QString &id, QQmlJSScopesById::Confidence confidence) {
3131 Q_UNUSED(confidence);
3133 return QQmlJSScopesById::CallbackResult::StopSearch;
3136 childScopes << scope->childScopes();
3141 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
3143 qmlDeferredPropertyId, uiob->firstSourceLocation());
3147 if (checkCustomParser(m_currentScope)) {
3151 m_pendingPropertyObjectBindings
3152 << PendingPropertyObjectBinding { m_currentScope, childScope, propertyName,
3153 uiob->firstSourceLocation(), uiob->hasOnToken };
3155 QQmlJSMetaPropertyBinding binding(uiob->firstSourceLocation(), propertyName);
3156 if (uiob->hasOnToken) {
3157 if (childScope->hasInterface(u"QQmlPropertyValueInterceptor"_s)) {
3158 binding.setInterceptor(QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope),
3159 QQmlJSScope::ConstPtr(childScope));
3161 binding.setValueSource(QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope),
3162 QQmlJSScope::ConstPtr(childScope));
3165 binding.setObject(QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope),
3166 QQmlJSScope::ConstPtr(childScope));
3168 m_bindings.append(UnfinishedBinding { m_currentScope, [=]() {
return binding; } });
3171 for (
int i = 0; i < scopesEnteredCounter; ++i)
3175bool QQmlJSImportVisitor::visit(ExportDeclaration *)
3177 Q_ASSERT(rootScopeIsValid());
3178 Q_ASSERT(m_exportedRootScope != m_globalScope);
3179 Q_ASSERT(m_currentScope == m_globalScope);
3180 m_currentScope = m_exportedRootScope;
3184void QQmlJSImportVisitor::endVisit(ExportDeclaration *)
3186 Q_ASSERT(rootScopeIsValid());
3187 m_currentScope = m_exportedRootScope->parentScope();
3188 Q_ASSERT(m_currentScope == m_globalScope);
3191bool QQmlJSImportVisitor::visit(ESModule *module)
3193 Q_ASSERT(!rootScopeIsValid());
3194 enterRootScope(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"module"),
3195 module->firstSourceLocation());
3196 m_currentScope->setIsScript(
true);
3197 importBaseModules();
3202void QQmlJSImportVisitor::endVisit(ESModule *)
3204 QQmlJSScope::resolveTypes(
3205 m_exportedRootScope, m_rootScopeImports.contextualTypes(), &m_usedTypes);
3208bool QQmlJSImportVisitor::visit(Program *program)
3210 Q_ASSERT(m_globalScope == m_currentScope);
3211 Q_ASSERT(!rootScopeIsValid());
3212 enterRootScope(QQmlSA::ScopeType::JSFunctionScope, u"script"_s, program->firstSourceLocation());
3213 m_exportedRootScope->setIsScript(
true);
3214 importBaseModules();
3218void QQmlJSImportVisitor::endVisit(Program *)
3220 QQmlJSScope::resolveTypes(
3221 m_exportedRootScope, m_rootScopeImports.contextualTypes(), &m_usedTypes);
3224void QQmlJSImportVisitor::endVisit(QQmlJS::AST::FieldMemberExpression *fieldMember)
3228 const QString name = fieldMember->name.toString();
3229 if (m_importTypeLocationMap.contains(name)) {
3230 const QQmlJSImportedScope type = m_rootScopeImports.type(name);
3231 if (type.scope.isNull()) {
3232 if (m_rootScopeImports.hasType(name))
3233 m_usedTypes.insert(name);
3234 }
else if (!type.scope->ownAttachedTypeName().isEmpty()) {
3235 m_usedTypes.insert(name);
3240bool QQmlJSImportVisitor::visit(QQmlJS::AST::IdentifierExpression *idexp)
3242 const QString name = idexp->name.toString();
3243 if (m_importTypeLocationMap.contains(name)) {
3244 m_usedTypes.insert(name);
3250bool QQmlJSImportVisitor::visit(QQmlJS::AST::PatternElement *element)
3253 if (element->isVariableDeclaration()) {
3254 QQmlJS::AST::BoundNames names;
3255 element->boundNames(&names);
3256 for (
const auto &name : std::as_const(names)) {
3257 std::optional<QString> typeName;
3258 if (TypeAnnotation *annotation = name.typeAnnotation.data())
3259 if (Type *type = annotation->type)
3260 typeName = type->toString();
3261 using Kind = QQmlJSScope::JavaScriptIdentifier::Kind;
3262 const Kind kind = (element->scope == QQmlJS::AST::VariableScope::Var)
3263 ? Kind::FunctionScoped
3264 : Kind::LexicalScoped;
3265 const QString variableName = name.id;
3266 if (kind == Kind::LexicalScoped) {
3267 const QQmlJS::SourceLocation location = element->firstSourceLocation();
3268 if (
auto previousDeclaration = m_currentScope->ownJSIdentifier(variableName)) {
3269 m_logger->log(
"Identifier '%1' has already been declared"_L1.arg(variableName), qmlSyntax,
3271 m_logger->log(
"Note: previous declaration of '%1' here"_L1.arg(variableName), qmlSyntax,
3272 previousDeclaration->location);
3275 const bool isConstVariable = element->scope == QQmlJS::AST::VariableScope::Const;
3276 const bool couldInsert = safeInsertJSIdentifier(m_currentScope,
3278 { (element->scope == QQmlJS::AST::VariableScope::Var)
3279 ? QQmlJSScope::JavaScriptIdentifier::FunctionScoped
3280 : QQmlJSScope::JavaScriptIdentifier::LexicalScoped,
3281 name.location, typeName,
3291bool QQmlJSImportVisitor::visit(IfStatement *statement)
3293 if (BinaryExpression *binary = cast<BinaryExpression *>(statement->expression)) {
3294 if (binary->op == QSOperator::Assign) {
3296 "Assignment in condition: did you mean to use \"===\" or \"==\" instead of \"=\"?"_L1,
3297 qmlAssignmentInCondition, binary->operatorToken);