148QQmlJSImportVisitor::QQmlJSImportVisitor(QQmlJSImporter *importer, QQmlJSLogger *logger,
149 const QString &implicitImportDirectory,
150 const QStringList &qmldirFiles)
151 : m_implicitImportDirectory(implicitImportDirectory),
152 m_qmldirFiles(qmldirFiles),
153 m_exportedRootScope(QQmlJSScope::resetForReparse(importer->importFile(logger->filePath()))),
154 m_importer(importer),
156 m_rootScopeImports(QQmlJS::ContextualTypes(
157 QQmlJS::ContextualTypes::QML, { }, { },
158 importer->builtinInternalNames().contextualTypes().arrayType()),
164 m_exportedRootScope->setScopeType(QQmlSA::ScopeType::QMLScope);
165 m_exportedRootScope->setBaseTypeName(QQmlJSImporter::s_inProcessMarker);
166 m_exportedRootScope->setFilePath(m_logger->filePath());
167 m_exportedRootScope->setIsComposite(
true);
170
171
172
173
174
175 auto globalScope = QQmlJSScope::create();
176 globalScope->setInternalName(u"global"_s);
177 globalScope->setScopeType(QQmlSA::ScopeType::JSFunctionScope);
179 QQmlJSScope::JavaScriptIdentifier globalJavaScript = {
180 QQmlJSScope::JavaScriptIdentifier::LexicalScoped, QQmlJS::SourceLocation(), std::nullopt,
184 QV4::Compiler::Codegen::forEachGlobalName([&](QLatin1StringView globalName) {
185 globalScope->insertJSIdentifier(globalName, globalJavaScript);
188 m_globalScope = globalScope;
189 m_currentScope = globalScope;
192QQmlJSImportVisitor::~QQmlJSImportVisitor() =
default;
194void QQmlJSImportVisitor::populateCurrentScope(
195 QQmlJSScope::ScopeType type,
const QString &name,
const QQmlJS::SourceLocation &location)
197 m_currentScope->setScopeType(type);
198 m_currentScope->setIsComposite(
true);
199 m_currentScope->setFilePath(m_logger->filePath());
200 m_currentScope->setSourceLocation(location);
201 setScopeName(m_currentScope, type, name);
202 m_scopesByIrLocation.insert({ location.startLine, location.startColumn }, m_currentScope);
205void QQmlJSImportVisitor::enterRootScope(QQmlJSScope::ScopeType type,
const QString &name,
const QQmlJS::SourceLocation &location)
207 Q_ASSERT(m_currentScope == m_globalScope);
208 QQmlJSScope::reparent(m_currentScope, m_exportedRootScope);
209 m_currentScope = m_exportedRootScope;
210 populateCurrentScope(type, name, location);
213void QQmlJSImportVisitor::enterEnvironment(QQmlJSScope::ScopeType type,
const QString &name,
214 const QQmlJS::SourceLocation &location)
216 QQmlJSScope::Ptr newScope = QQmlJSScope::create();
217 QQmlJSScope::reparent(m_currentScope, newScope);
218 m_currentScope = std::move(newScope);
219 populateCurrentScope(type, name, location);
222bool QQmlJSImportVisitor::enterEnvironmentNonUnique(QQmlJSScope::ScopeType type,
224 const QQmlJS::SourceLocation &location)
226 Q_ASSERT(type == QQmlSA::ScopeType::GroupedPropertyScope
227 || type == QQmlSA::ScopeType::AttachedPropertyScope);
229 const auto pred = [&](
const QQmlJSScope::ConstPtr &s) {
232 return s->internalName() == name;
234 const auto scopes = m_currentScope->childScopes();
237 auto it = std::find_if(scopes.begin(), scopes.end(), pred);
238 if (it == scopes.end()) {
240 enterEnvironment(type, name, location);
244 m_scopesByIrLocation.insert({ location.startLine, location.startColumn }, *it);
245 m_currentScope = *it;
249void QQmlJSImportVisitor::leaveEnvironment()
251 m_currentScope = m_currentScope->parentScope();
254void QQmlJSImportVisitor::warnUnresolvedType(
const QQmlJSScope::ConstPtr &type)
const
256 m_logger->log(QStringLiteral(
"Type %1 is used but it is not resolved")
257 .arg(QQmlJSUtils::getScopeName(type, type->scopeType())),
258 qmlUnresolvedType, type->sourceLocation());
261void QQmlJSImportVisitor::warnMissingPropertyForBinding(
262 const QString &property,
const QQmlJS::SourceLocation &location,
263 const std::optional<QQmlJSFixSuggestion> &fixSuggestion)
265 m_logger->log(QStringLiteral(
"Could not find property \"%1\".").arg(property),
266 qmlMissingProperty, location,
true,
true, fixSuggestion);
274QQmlJSImportVisitor::AliasPropertyResolution
275QQmlJSImportVisitor::resolveAliasProperty(
const QQmlJSScope::Ptr &object,
276 const QQmlJSMetaProperty &property)
278 AliasPropertyResolution result = Resolved;
279 QStringList components = property.aliasExpression().split(u'.');
280 QQmlJSMetaProperty targetProperty;
282 bool foundProperty =
false;
283 bool hasWarnedAlready =
false;
286 QQmlJSScope::ConstPtr type = m_scopesById.scope(components.takeFirst(), object);
287 QQmlJSScope::ConstPtr typeScope;
288 if (!type.isNull()) {
289 foundProperty =
true;
296 while (type && !components.isEmpty()) {
297 const QString name = components.takeFirst();
299 if (!checkTypeResolved(type)) {
300 hasWarnedAlready =
true;
305 if (!type->hasProperty(name)) {
306 foundProperty =
false;
311 const auto target = type->property(name);
312 if (!target.type()) {
313 if (target.isAlias()) {
314 result = NeedsRequeue;
318 hasWarnedAlready = QQmlJSScope::ownerOfProperty(type, name).scope->filePath()
319 == m_exportedRootScope->filePath();
323 type = target.type();
324 targetProperty = target;
329 if (result == NeedsRequeue)
331 if (!hasWarnedAlready) {
333 m_logger->log(QStringLiteral(
"Cannot deduce type of alias \"%1\"")
334 .arg(property.propertyName()),
335 qmlMissingType, property.sourceLocation());
338 QStringLiteral(
"Cannot resolve alias \"%1\"").arg(property.propertyName()),
339 qmlUnresolvedAlias, property.sourceLocation());
343 Q_ASSERT(property.index() >= 0);
344 object->addOwnProperty(property);
347 QQmlJSMetaProperty newProperty = property;
348 newProperty.setType(type);
350 newProperty.setIsList(targetProperty.isList());
351 newProperty.setIsWritable(targetProperty.isWritable());
352 newProperty.setIsFinal(targetProperty.isFinal());
353 newProperty.setIsPointer(targetProperty.isPointer());
355 const bool onlyId = !property.aliasExpression().contains(u'.');
357 newProperty.setAliasTargetScope(type);
358 newProperty.setAliasTargetName(QStringLiteral(
"id-only-alias"));
360 const auto &ownerScope =
361 QQmlJSScope::ownerOfProperty(typeScope, targetProperty.propertyName()).scope;
362 newProperty.setAliasTargetScope(ownerScope);
363 newProperty.setAliasTargetName(targetProperty.propertyName());
366 if (
const QString internalName = type->internalName(); !internalName.isEmpty())
367 newProperty.setTypeName(internalName);
369 Q_ASSERT(newProperty.index() >= 0);
370 object->addOwnProperty(newProperty);
371 m_aliasDefinitions.append({ object, property.propertyName() });
376void QQmlJSImportVisitor::resolveAliases()
378 QQueue<QQmlJSScope::Ptr> objects;
379 objects.enqueue(m_exportedRootScope);
381 qsizetype lastRequeueLength = std::numeric_limits<qsizetype>::max();
382 QQueue<QQmlJSScope::Ptr> requeue;
383 QDuplicateTracker<std::pair<QQmlJSScope::Ptr, QQmlJSMetaProperty>> alreadyResolvedAliases;
385 bool processingRequeue =
false;
387 while (!objects.isEmpty()) {
388 const QQmlJSScope::Ptr object = objects.dequeue();
389 const auto properties = object->ownProperties();
391 bool doRequeue =
false;
392 for (
const auto &property : properties) {
393 if (!property.isAlias() || !property.type().isNull()
394 || alreadyResolvedAliases.contains({ object, property })) {
397 if (resolveAliasProperty(object, property) == NeedsRequeue) {
400 Q_UNUSED(alreadyResolvedAliases.hasSeen({ object, property }));
404 if (!processingRequeue) {
405 const auto childScopes = object->childScopes();
406 for (
const auto &childScope : childScopes)
407 objects.enqueue(childScope);
411 requeue.enqueue(object);
413 if (objects.isEmpty() && requeue.size() < lastRequeueLength) {
414 processingRequeue =
true;
415 lastRequeueLength = requeue.size();
416 objects.swap(requeue);
421void QQmlJSImportVisitor::resolveGroupedProperties()
423 QQueue<QQmlJSScope::Ptr> objects;
424 objects.enqueue(m_exportedRootScope);
426 while (!objects.isEmpty()) {
427 const QQmlJSScope::Ptr object = objects.dequeue();
428 const auto childScopes = object->childScopes();
429 for (
const auto &childScope : childScopes) {
430 if (mayBeUnresolvedGroupedProperty(childScope)) {
431 const QString name = childScope->internalName();
432 if (object->isNameDeferred(name)) {
433 const QQmlJSScope::ConstPtr deferred = m_scopesById.scope(name, childScope);
434 if (!deferred.isNull()) {
435 QQmlJSScope::resolveGroup(childScope, deferred,
436 m_rootScopeImports.contextualTypes(),
439 }
else if (
const QQmlJSScope::ConstPtr propType = object->property(name).type()) {
440 QQmlJSScope::resolveGroup(childScope, propType,
441 m_rootScopeImports.contextualTypes(), usedTypes());
444 objects.enqueue(childScope);
449QString QQmlJSImportVisitor::implicitImportDirectory(
const QString &localFile,
450 const 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 =
477 std::partition(importWarnings.begin(), importWarnings.end(),
478 [](
const QQmlJS::DiagnosticMessage &message) {
479 return message.msgType() != QtMsgType::QtInfoMsg;
481 if (fileSelectorWarningsIt != importWarnings.end()) {
482 m_logger->log(QStringLiteral(
"Warnings occurred while importing %1:").arg(what), qmlImportFileSelector,
484 m_logger->processMessages(QSpan(fileSelectorWarningsIt, importWarnings.end()),
485 qmlImportFileSelector, srcLocation);
488 if (fileSelectorWarningsIt == importWarnings.begin())
491 m_logger->log(QStringLiteral(
"Warnings occurred while importing %1:").arg(what), qmlImport,
493 m_logger->processMessages(QSpan(importWarnings.begin(), fileSelectorWarningsIt), qmlImport,
497void QQmlJSImportVisitor::importBaseModules()
499 Q_ASSERT(m_rootScopeImports.isEmpty());
500 m_rootScopeImports = m_importer->importHardCodedBuiltins();
502
503
504
505
506
507 m_rootScopeImports.setCurrentFileSelector(
508 QQmlJSUtils::fileSelectorFor(m_exportedRootScope));
510 const QQmlJS::SourceLocation invalidLoc;
511 const auto types = m_rootScopeImports.types();
512 for (
auto it = types.keyBegin(), end = types.keyEnd(); it != end; it++)
513 addImportWithLocation(*it, invalidLoc,
false);
515 if (!m_qmldirFiles.isEmpty())
516 m_rootScopeImports.addWarnings(m_importer->importQmldirs(m_qmldirFiles));
520 if (!m_logger->filePath().endsWith(u".qmltypes"_s)) {
521 auto precedence = quint8(QQmlJS::PrecedenceValues::ImplicitImport);
522 auto implicitImport = m_importer->importDirectory(m_implicitImportDirectory, precedence);
523 m_importer->registerVersionedImports(implicitImport);
524 m_rootScopeImports.add(std::move(implicitImport));
529 if (
const QQmlJSResourceFileMapper *mapper = m_importer->resourceFileMapper()) {
530 const QStringList resourcePaths = mapper->resourcePaths(QQmlJSResourceFileMapper::Filter {
531 m_logger->filePath(), QStringList(), QQmlJSResourceFileMapper::Resource });
532 for (
const QString &path : resourcePaths) {
533 const qsizetype lastSlash = path.lastIndexOf(QLatin1Char(
'/'));
536 auto precedence = quint8(QQmlJS::PrecedenceValues::ImplicitImport);
537 auto resourceImport =
538 m_importer->importDirectory(path.first(lastSlash), precedence);
539 m_importer->registerVersionedImports(resourceImport);
540 m_rootScopeImports.add(std::move(resourceImport));
545 processImportWarnings(QStringLiteral(
"base modules"), m_rootScopeImports.warnings());
548bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiProgram *)
552 if (
auto elementName = QFileInfo(m_logger->filePath()).baseName();
553 !elementName.isEmpty() && elementName[0].isUpper()) {
554 auto precedence = quint8(QQmlJS::PrecedenceValues::ImplicitImport);
555 m_rootScopeImports.setType(elementName,
556 { m_exportedRootScope, QTypeRevision{ }, precedence });
562void QQmlJSImportVisitor::endVisit(UiProgram *)
564 for (
const auto &scope : std::as_const(m_objectBindingScopes)) {
565 breakInheritanceCycles(scope);
566 checkDeprecation(scope);
567 checkForComponentTypeWithProperties(scope);
570 for (
const auto &scope : std::as_const(m_objectDefinitionScopes)) {
571 if (m_pendingDefaultProperties.contains(scope))
573 breakInheritanceCycles(scope);
574 checkDeprecation(scope);
575 checkForComponentTypeWithProperties(scope);
578 const auto &keys = m_pendingDefaultProperties.keys();
579 for (
const auto &scope : keys) {
580 breakInheritanceCycles(scope);
581 checkDeprecation(scope);
582 checkForComponentTypeWithProperties(scope);
586 resolveGroupedProperties();
588 checkGroupedAndAttachedScopes();
591 processDefaultProperties();
592 processPropertyTypes();
593 processMethodTypes();
594 processPropertyBindings();
595 processPropertyBindingObjects();
596 checkRequiredProperties();
598 populateRuntimeFunctionIndicesForDocument();
603 ExpressionStatement *expr = cast<ExpressionStatement *>(statement);
605 if (!statement || !expr->expression)
608 switch (expr->expression->kind) {
609 case Node::Kind_StringLiteral:
610 return cast<StringLiteral *>(expr->expression)->value.toString();
611 case Node::Kind_NumericLiteral:
612 return cast<NumericLiteral *>(expr->expression)->value;
618QList<QQmlJSAnnotation> QQmlJSImportVisitor::parseAnnotations(QQmlJS::AST::UiAnnotationList *list)
621 QList<QQmlJSAnnotation> annotationList;
623 for (UiAnnotationList *item = list; item !=
nullptr; item = item->next) {
624 UiAnnotation *annotation = item->annotation;
626 QQmlJSAnnotation qqmljsAnnotation;
627 qqmljsAnnotation.name = buildName(annotation->qualifiedTypeNameId);
629 for (UiObjectMemberList *memberItem = annotation->initializer->members; memberItem !=
nullptr; memberItem = memberItem->next) {
630 switch (memberItem->member->kind) {
631 case Node::Kind_UiScriptBinding: {
632 auto *scriptBinding = QQmlJS::AST::cast<UiScriptBinding*>(memberItem->member);
633 qqmljsAnnotation.bindings[buildName(scriptBinding->qualifiedId)]
634 = bindingToVariant(scriptBinding->statement);
643 annotationList.append(qqmljsAnnotation);
646 return annotationList;
650 const QQmlJS::SourceLocation &first,
const QQmlJS::SourceLocation &second,
651 const QList<QQmlJS::SourceLocation> &groupedObjectDefinitions)
653 const auto innermostDefinitionOffset =
654 [groupedObjectDefinitions](
const QQmlJS::SourceLocation &location) {
655 quint32 innermostOffset = 0;
656 for (
const QQmlJS::SourceLocation &definition : groupedObjectDefinitions) {
657 const bool contains = definition.offset <= location.offset
658 && location.offset < definition.offset + definition.length;
659 if (contains && definition.offset > innermostOffset)
660 innermostOffset = definition.offset;
662 return innermostOffset;
664 return innermostDefinitionOffset(first) == innermostDefinitionOffset(second);
667void QQmlJSImportVisitor::setAllBindings()
669 using Key = std::pair<QQmlJSScope::ConstPtr, QString>;
670 QHash<Key, QQmlJS::SourceLocation> foundBindings;
672 for (
auto it = m_bindings.cbegin(); it != m_bindings.cend(); ++it) {
674 const QQmlJSScope::Ptr type = it->owner;
675 if (!checkTypeResolved(type))
684 if (!type->isFullyResolved())
686 auto binding = it->create();
687 if (!binding.isValid())
689 type->addOwnPropertyBinding(binding, it->specifier);
692 if (binding.hasInterceptor() || binding.hasValueSource())
694 const QString propertyName = binding.propertyName();
695 QQmlJSMetaProperty property = type->property(propertyName);
698
699
700
701
702
703 if (!property.isValid())
707 if (property.isList())
710 const Key key = std::make_pair(type, propertyName);
711 auto sourceLocationIt = foundBindings.constFind(key);
712 if (sourceLocationIt == foundBindings.constEnd()) {
713 foundBindings.insert(key, binding.sourceLocation());
717 const QQmlJS::SourceLocation location = binding.sourceLocation();
724 const bool irBuilderAlreadyWarned = groupedPropertiesInSameGroupedObjectDefinition(
725 *sourceLocationIt, location, m_groupedObjectDefinitions);
726 if (!irBuilderAlreadyWarned) {
727 m_logger->log(
"Duplicate binding on property '%1'"_L1.arg(propertyName),
728 qmlDuplicatePropertyBinding, location);
730 m_logger->log(
"Note: previous binding on '%1' here"_L1.arg(propertyName),
731 qmlDuplicatePropertyBinding, *sourceLocationIt,
true,
true, {},
736void QQmlJSImportVisitor::processDefaultProperties()
738 for (
auto it = m_pendingDefaultProperties.constBegin();
739 it != m_pendingDefaultProperties.constEnd(); ++it) {
740 QQmlJSScope::ConstPtr parentScope = it.key();
743 if (checkCustomParser(parentScope))
746 if (!checkTypeResolved(parentScope))
750
751
752
753
754
755
756
757
758
760 parentScope = parentScope->baseType();
762 const QString defaultPropertyName =
763 parentScope ? parentScope->defaultPropertyName() : QString();
765 if (defaultPropertyName.isEmpty()) {
768 bool isComponent =
false;
769 for (QQmlJSScope::ConstPtr s = parentScope; s; s = s->baseType()) {
770 if (s->internalName() == QStringLiteral(
"QQmlComponent")) {
776 if (!isComponent && checkTypeResolved(parentScope)) {
777 m_logger->log(QStringLiteral(
"Cannot assign to non-existent default property"),
778 qmlMissingProperty, it.value().constFirst()->sourceLocation());
784 const QQmlJSMetaProperty defaultProp = parentScope->property(defaultPropertyName);
785 auto propType = defaultProp.type();
786 const auto handleUnresolvedDefaultProperty = [&](
const QQmlJSScope::ConstPtr &) {
788 m_logger->log(QStringLiteral(
"Property \"%1\" has incomplete type \"%2\". You may be "
789 "missing an import.")
790 .arg(defaultPropertyName, defaultProp.typeName()),
791 qmlUnresolvedType, it.value().constFirst()->sourceLocation());
794 const auto assignToUnknownProperty = [&]() {
797 for (
const QQmlJSScope::Ptr &scope : std::as_const(*it))
798 scope->setAssignedToUnknownProperty(
true);
801 if (propType.isNull()) {
802 if (checkTypeResolved(parentScope)
803 && QQmlJSScope::ownerOfProperty(parentScope, defaultPropertyName).scope->filePath()
804 != m_exportedRootScope->filePath()) {
805 handleUnresolvedDefaultProperty(propType);
807 assignToUnknownProperty();
811 if (it.value().size() > 1
812 && !defaultProp.isList()
813 && !propType->isListProperty()) {
815 QStringLiteral(
"Cannot assign multiple objects to a default non-list property"),
816 qmlNonListProperty, it.value().constFirst()->sourceLocation());
819 if (!checkTypeResolved(propType, handleUnresolvedDefaultProperty)) {
820 assignToUnknownProperty();
824 for (
const QQmlJSScope::Ptr &scope : std::as_const(*it)) {
825 if (!checkTypeResolved(scope))
830 if (propType->canAssign(scope)) {
831 scope->setIsWrappedInImplicitComponent(
832 causesImplicitComponentWrapping(defaultProp, scope));
836 m_logger->log(QStringLiteral(
"Cannot assign to default property of incompatible type"),
837 qmlIncompatibleType, scope->sourceLocation());
842void QQmlJSImportVisitor::processPropertyTypes()
844 for (
const PendingPropertyType &type : std::as_const(m_pendingPropertyTypes)) {
845 Q_ASSERT(type.scope->hasOwnProperty(type.name));
847 auto property = type.scope->ownProperty(type.name);
849 if (
const auto propertyType = QQmlJSScope::findType(
850 property.typeName(), m_rootScopeImports.contextualTypes()).scope) {
851 property.setType(property.isList() ? propertyType->listType() : propertyType);
852 type.scope->addOwnProperty(property);
854 QString msg = property.typeName() +
' '_L1 + wasNotFound;
855 if (property.typeName() ==
"list"_L1)
856 msg +=
" list is not a type. It requires an element type argument (eg. list<int>)"_L1;
857 m_logger->log(msg, qmlImport, type.location);
862void QQmlJSImportVisitor::processMethodTypes()
864 const auto isEnumUsedAsType = [&](QStringView typeName,
const QQmlJS::SourceLocation &loc) {
865 if (typeName ==
"enum"_L1) {
869 const auto split = typeName.tokenize(u'.').toContainer<QVarLengthArray<QStringView, 4>>();
870 if (split.size() != 2)
873 const QStringView scopeName = split[0];
874 const QStringView enumName = split[1];
876 if (
auto scope = QQmlJSScope::findType(scopeName.toString(),
877 m_rootScopeImports.contextualTypes()).scope) {
878 if (scope->enumeration(enumName.toString()).isValid()) {
880 "QML enumerations are not types. Use int, or use double if the enum's underlying type does not fit into int."_L1,
881 qmlEnumsAreNotTypes, loc);
888 for (
const auto &method : std::as_const(m_pendingMethodTypeAnnotations)) {
889 for (
auto [it, end] = method.scope->mutableOwnMethodsRange(method.methodName); it != end; ++it) {
890 const auto [parameterBegin, parameterEnd] = it->mutableParametersRange();
891 for (
auto parameter = parameterBegin; parameter != parameterEnd; ++parameter) {
892 const int parameterIndex = parameter - parameterBegin;
893 if (isEnumUsedAsType(parameter->typeName(), method.locations[parameterIndex]))
895 if (
const auto parameterType = QQmlJSScope::findType(
896 parameter->typeName(), m_rootScopeImports.contextualTypes()).scope) {
897 parameter->setType({ parameterType });
900 u"\"%1\" was not found for the type of parameter \"%2\" in method \"%3\"."_s
901 .arg(parameter->typeName(), parameter->name(), it->methodName()),
902 qmlUnresolvedType, method.locations[parameter - parameterBegin]);
906 if (isEnumUsedAsType(it->returnTypeName(), method.locations.last()))
908 if (
const auto returnType = QQmlJSScope::findType(
909 it->returnTypeName(), m_rootScopeImports.contextualTypes()).scope) {
910 it->setReturnType({ returnType });
912 m_logger->log(u"\"%1\" was not found for the return type of method \"%2\"."_s.arg(
913 it->returnTypeName(), it->methodName()),
914 qmlUnresolvedType, method.locations.last());
922
923
924
925
926
927
928
932 for (QStringView propertyName: possiblyGroupedProperty.tokenize(u".")) {
933 property = scope->property(propertyName.toString());
934 if (property.isValid())
935 scope = property.type();
942void QQmlJSImportVisitor::processPropertyBindingObjects()
944 QSet<std::pair<QQmlJSScope::Ptr, QString>> foundLiterals;
952 QSet<std::pair<QQmlJSScope::Ptr, QString>> visited;
953 for (
const PendingPropertyObjectBinding &objectBinding :
954 std::as_const(m_pendingPropertyObjectBindings)) {
956 const auto uniqueBindingId = std::make_pair(objectBinding.scope, objectBinding.name);
957 if (visited.contains(uniqueBindingId))
959 visited.insert(uniqueBindingId);
961 auto [existingBindingsBegin, existingBindingsEnd] =
962 uniqueBindingId.first->ownPropertyBindings(uniqueBindingId.second);
963 const bool hasLiteralBindings =
964 std::any_of(existingBindingsBegin, existingBindingsEnd,
965 [](
const QQmlJSMetaPropertyBinding &x) {
return x.hasLiteral(); });
966 if (hasLiteralBindings)
967 foundLiterals.insert(uniqueBindingId);
971 QSet<std::pair<QQmlJSScope::Ptr, QString>> foundObjects;
972 QSet<std::pair<QQmlJSScope::Ptr, QString>> foundInterceptors;
973 QSet<std::pair<QQmlJSScope::Ptr, QString>> foundValueSources;
975 for (
const PendingPropertyObjectBinding &objectBinding :
976 std::as_const(m_pendingPropertyObjectBindings)) {
977 const QString propertyName = objectBinding.name;
978 QQmlJSScope::Ptr childScope = objectBinding.childScope;
980 const auto assignToUnknownProperty = [&]() {
983 childScope->setAssignedToUnknownProperty(
true);
987 if (!checkTypeResolved(objectBinding.scope)) {
988 assignToUnknownProperty();
992 QQmlJSMetaProperty property = resolveProperty(propertyName, objectBinding.scope);
994 if (!property.isValid()) {
995 warnMissingPropertyForBinding(propertyName, objectBinding.location);
998 const auto handleUnresolvedProperty = [&](
const QQmlJSScope::ConstPtr &) {
1000 m_logger->log(QStringLiteral(
"Property \"%1\" has incomplete type \"%2\". You may be "
1001 "missing an import.")
1002 .arg(propertyName, property.typeName()),
1003 qmlUnresolvedType, objectBinding.location);
1006 if (property.type().isNull()) {
1007 assignToUnknownProperty();
1008 if (checkTypeResolved(objectBinding.scope)
1009 && QQmlJSScope::ownerOfProperty(objectBinding.scope, propertyName).scope->filePath()
1010 != m_exportedRootScope->filePath()) {
1013 handleUnresolvedProperty(property.type());
1019 if (!checkTypeResolved(property.type(), handleUnresolvedProperty)) {
1020 assignToUnknownProperty();
1022 }
else if (!checkTypeResolved(childScope)) {
1026 if (!objectBinding.onToken && !property.type()->canAssign(childScope)) {
1027 m_logger->log(QStringLiteral(
"Cannot assign object of type %1 to %2")
1028 .arg(QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope),
1029 property.typeName()),
1030 qmlIncompatibleType, childScope->sourceLocation());
1034 childScope->setIsWrappedInImplicitComponent(
1035 causesImplicitComponentWrapping(property, childScope));
1038 const auto uniqueBindingId = std::make_pair(objectBinding.scope, objectBinding.name);
1039 const QString typeName = QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope);
1041 auto isConditionalBinding = [&]() ->
bool {
1043
1044
1045
1046
1047 return childScope->hasOwnPropertyBindings(u"enabled"_s)
1048 || childScope->hasOwnPropertyBindings(u"when"_s)
1049 || childScope->hasOwnPropertyBindings(u"running"_s);
1052 if (objectBinding.onToken) {
1053 if (childScope->hasInterface(QStringLiteral(
"QQmlPropertyValueInterceptor"))) {
1054 if (foundInterceptors.contains(uniqueBindingId)) {
1055 if (!isConditionalBinding()) {
1056 m_logger->log(QStringLiteral(
"Duplicate interceptor on property \"%1\"")
1058 qmlDuplicatePropertyBinding, objectBinding.location);
1061 foundInterceptors.insert(uniqueBindingId);
1063 }
else if (childScope->hasInterface(QStringLiteral(
"QQmlPropertyValueSource"))) {
1064 if (foundValueSources.contains(uniqueBindingId)) {
1065 if (!isConditionalBinding()) {
1066 m_logger->log(QStringLiteral(
"Duplicate value source on property \"%1\"")
1068 qmlDuplicatePropertyBinding, objectBinding.location);
1070 }
else if (foundObjects.contains(uniqueBindingId)
1071 || foundLiterals.contains(uniqueBindingId)) {
1072 if (!isConditionalBinding()) {
1073 m_logger->log(QStringLiteral(
"Cannot combine value source and binding on "
1076 qmlDuplicatePropertyBinding, objectBinding.location);
1079 foundValueSources.insert(uniqueBindingId);
1082 m_logger->log(QStringLiteral(
"On-binding for property \"%1\" has wrong type \"%2\"")
1083 .arg(propertyName, typeName),
1084 qmlIncompatibleType, objectBinding.location);
1087 if (foundValueSources.contains(uniqueBindingId)) {
1088 if (!isConditionalBinding()) {
1090 QStringLiteral(
"Cannot combine value source and binding on property \"%1\"")
1092 qmlDuplicatePropertyBinding, objectBinding.location);
1095 foundObjects.insert(uniqueBindingId);
1103 QList<QQmlJSScope::ConstPtr> descendants;
1104 std::vector<QQmlJSScope::ConstPtr> toVisit;
1106 toVisit.push_back(scope);
1107 while (!toVisit.empty()) {
1108 const QQmlJSScope::ConstPtr s = toVisit.back();
1114 toVisit.insert(toVisit.end(), s->childScopesBegin(), s->childScopesEnd());
1121void QQmlJSImportVisitor::populatePropertyAliases()
1123 for (
const auto &alias : std::as_const(m_aliasDefinitions)) {
1124 const auto &[aliasScope, aliasName] = alias;
1125 if (aliasScope.isNull())
1128 auto property = aliasScope->ownProperty(aliasName);
1129 if (!property.isValid() || !property.aliasTargetScope())
1132 Property target(property.aliasTargetScope(), property.aliasTargetName());
1135 m_propertyAliases[target].append(alias);
1136 property = target.scope->property(target.name);
1137 target = Property(property.aliasTargetScope(), property.aliasTargetName());
1138 }
while (property.isAlias() && target.scope);
1142void QQmlJSImportVisitor::checkRequiredProperties()
1144 for (
const auto &required : std::as_const(m_requiredProperties)) {
1145 if (!required.scope->hasProperty(required.name)) {
1147 QStringLiteral(
"Property \"%1\" was marked as required but does not exist.")
1148 .arg(required.name),
1149 qmlRequired, required.location);
1153 const auto compType = m_rootScopeImports.type(u"Component"_s).scope;
1154 const auto isComponentRoot = [&](
const QQmlJSScope::ConstPtr &requiredScope) {
1155 if (requiredScope->isWrappedInImplicitComponent())
1157 if (
const auto s = requiredScope->parentScope(); s && s->baseType() == compType)
1162 const auto scopeRequiresProperty = [&](
const QQmlJSScope::ConstPtr &requiredScope,
1163 const QString &propName,
1164 const QQmlJSScope::ConstPtr &descendant) {
1165 if (!requiredScope->isPropertyLocallyRequired(propName))
1169 return QQmlJSScope::ownerOfProperty(requiredScope, propName).scope
1170 == QQmlJSScope::ownerOfProperty(descendant, propName).scope;
1173 const auto requiredHasBinding = [](
const QList<QQmlJSScope::ConstPtr> &scopesToSearch,
1174 const QQmlJSScope::ConstPtr &owner,
1175 const QString &propName) {
1176 for (
const auto &scope : scopesToSearch) {
1177 if (scope->property(propName).isAlias())
1179 const auto &[begin, end] = scope->ownPropertyBindings(propName);
1180 for (
auto it = begin; it != end; ++it) {
1182 const bool isRelevantBinding = QQmlSA::isRegularBindingType(it->bindingType())
1183 || it->bindingType() == QQmlSA::BindingType::Interceptor
1184 || it->bindingType() == QQmlSA::BindingType::ValueSource;
1185 if (!isRelevantBinding)
1187 if (QQmlJSScope::ownerOfProperty(scope, propName).scope == owner)
1195 const auto requiredUsedInRootAlias = [&](
const QQmlJSScope::ConstPtr &requiredScope,
1196 const QString &propName) {
1197 const Property target(requiredScope, propName);
1200 const auto allAliasesToTargetIt = m_propertyAliases.constFind(target);
1201 if (allAliasesToTargetIt == m_propertyAliases.constEnd())
1208 allAliasesToTargetIt->constBegin(), allAliasesToTargetIt->constEnd(),
1209 [](
const Property &property) {
return property.scope->isFileRootComponent(); });
1212 const auto requiredSetThroughAlias = [&](
const QList<QQmlJSScope::ConstPtr> &scopesToSearch,
1213 const QQmlJSScope::ConstPtr &requiredScope,
1214 const QString &propName) {
1215 const auto &propertyDefScope = QQmlJSScope::ownerOfProperty(requiredScope, propName);
1216 const auto &propertyAliases = m_propertyAliases[{ propertyDefScope.scope, propName }];
1217 for (
const auto &alias : propertyAliases) {
1218 for (
const auto &s : scopesToSearch) {
1219 if (s->hasOwnPropertyBindings(alias.name))
1226 const auto warn = [
this](
const QQmlJSScope::ConstPtr &prevRequiredScope,
1227 const QString &propName,
const QQmlJSScope::ConstPtr &defScope,
1228 const QQmlJSScope::ConstPtr &requiredScope,
1229 const QQmlJSScope::ConstPtr &descendant) {
1230 const auto &propertyScope = QQmlJSScope::ownerOfProperty(requiredScope, propName).scope;
1231 const QString propertyScopeName = !propertyScope.isNull()
1232 ? QQmlJSUtils::getScopeName(propertyScope, QQmlSA::ScopeType::QMLScope)
1235 std::optional<QQmlJSFixSuggestion> suggestion;
1237 QString message = QStringLiteral(
"Component is missing required property %1 from %2")
1238 .arg(propName, propertyScopeName);
1239 if (requiredScope != descendant) {
1240 const QString requiredScopeName = prevRequiredScope
1241 ? QQmlJSUtils::getScopeName(prevRequiredScope, QQmlSA::ScopeType::QMLScope)
1244 if (!prevRequiredScope.isNull()) {
1245 if (
auto sourceScope = prevRequiredScope->baseType()) {
1246 suggestion = QQmlJSFixSuggestion{
1247 "%1:%2:%3: Property marked as required in %4."_L1
1248 .arg(sourceScope->filePath(),
1249 QString::number(sourceScope->sourceLocation().startLine),
1250 QString::number(sourceScope->sourceLocation().startColumn),
1252 sourceScope->sourceLocation()
1256 if (sourceScope->isComposite())
1257 suggestion->setFilename(sourceScope->filePath());
1260 message +=
" (marked as required by %1)"_L1.arg(requiredScopeName);
1264 m_logger->log(message, qmlRequired, defScope->sourceLocation(),
true,
true, suggestion);
1267 populatePropertyAliases();
1269 for (
const auto &[_, defScope] : m_scopesByIrLocation.asKeyValueRange()) {
1270 if (defScope->isFileRootComponent() || defScope->isInlineComponent()
1271 || defScope->componentRootStatus() != QQmlJSScope::IsComponentRoot::No
1272 || defScope->scopeType() != QQmlSA::ScopeType::QMLScope) {
1276 QList<QQmlJSScope::ConstPtr> scopesToSearch;
1277 for (QQmlJSScope::ConstPtr scope = defScope; scope; scope = scope->baseType()) {
1278 const auto descendants = QList<QQmlJSScope::ConstPtr>()
1279 << scope << qmlScopeDescendants(scope);
1280 for (
const QQmlJSScope::ConstPtr &descendant : std::as_const(descendants)) {
1283 if (descendant != scope && descendant->isInlineComponent())
1285 scopesToSearch << descendant;
1286 const auto ownProperties = descendant->ownProperties();
1287 for (
auto propertyIt = ownProperties.constBegin();
1288 propertyIt != ownProperties.constEnd(); ++propertyIt) {
1289 const QString propName = propertyIt.key();
1290 if (descendant->hasOwnPropertyBindings(propName))
1293 QQmlJSScope::ConstPtr prevRequiredScope;
1294 for (
const QQmlJSScope::ConstPtr &requiredScope : std::as_const(scopesToSearch)) {
1297 if (isComponentRoot(requiredScope))
1300 if (!scopeRequiresProperty(requiredScope, propName, descendant)) {
1301 prevRequiredScope = requiredScope;
1305 if (requiredHasBinding(scopesToSearch, descendant, propName))
1308 if (requiredUsedInRootAlias(requiredScope, propName))
1311 if (requiredSetThroughAlias(scopesToSearch, requiredScope, propName))
1314 warn(prevRequiredScope, propName, defScope, requiredScope, descendant);
1315 prevRequiredScope = requiredScope;
1323void QQmlJSImportVisitor::processPropertyBindings()
1325 for (
auto it = m_propertyBindings.constBegin(); it != m_propertyBindings.constEnd(); ++it) {
1326 QQmlJSScope::Ptr scope = it.key();
1327 for (
auto &[visibilityScope, location, name] : it.value()) {
1328 if (!scope->hasProperty(name) && !m_logger->isDisabled()) {
1332 if (checkCustomParser(scope))
1336 std::optional<QQmlJSFixSuggestion> fixSuggestion;
1338 for (QQmlJSScope::ConstPtr baseScope = scope; !baseScope.isNull();
1339 baseScope = baseScope->baseType()) {
1340 if (
auto suggestion = QQmlJSUtils::didYouMean(
1341 name, baseScope->ownProperties().keys(), m_logger->filePath(), location);
1342 suggestion.has_value()) {
1343 fixSuggestion = suggestion;
1348 if (checkTypeResolved(scope))
1349 warnMissingPropertyForBinding(name, location, fixSuggestion);
1353 const auto property = scope->property(name);
1354 if (!property.type()) {
1355 m_logger->log(QStringLiteral(
"No type found for property \"%1\". This may be due "
1356 "to a missing import statement or incomplete "
1359 qmlMissingType, location);
1362 const auto &annotations = property.annotations();
1364 const auto deprecationAnn =
1365 std::find_if(annotations.cbegin(), annotations.cend(),
1366 [](
const QQmlJSAnnotation &ann) {
return ann.isDeprecation(); });
1368 if (deprecationAnn != annotations.cend()) {
1369 const auto deprecation = deprecationAnn->deprecation();
1371 QString message = QStringLiteral(
"Binding on deprecated property \"%1\"")
1372 .arg(property.propertyName());
1374 if (!deprecation.reason.isEmpty())
1375 message.append(QStringLiteral(
" (Reason: %1)").arg(deprecation.reason));
1377 m_logger->log(message, qmlDeprecated, location);
1383void QQmlJSImportVisitor::checkSignal(
1384 const QQmlJSScope::ConstPtr &signalScope,
const QQmlJS::SourceLocation &location,
1385 const QString &handlerName,
const QStringList &handlerParameters)
1387 const auto signal = QQmlSignalNames::handlerNameToSignalName(handlerName);
1389 std::optional<QQmlJSMetaMethod> signalMethod;
1390 const auto setSignalMethod = [&](
const QQmlJSScope::ConstPtr &scope,
const QString &name) {
1391 const auto methods = scope->methods(name, QQmlJSMetaMethodType::Signal);
1392 if (!methods.isEmpty())
1393 signalMethod = methods[0];
1396 if (signal.has_value()) {
1397 if (signalScope->hasMethod(*signal)) {
1398 setSignalMethod(signalScope, *signal);
1399 }
else if (
auto p = QQmlJSUtils::propertyFromChangedHandler(signalScope, handlerName)) {
1404 if (
auto notify = p->notify(); !notify.isEmpty()) {
1405 setSignalMethod(signalScope, notify);
1407 Q_ASSERT(!p->bindable().isEmpty());
1408 signalMethod = QQmlJSMetaMethod {};
1413 if (!signalMethod.has_value()) {
1418 if (signalScope->baseTypeName() == QStringLiteral(
"Connections")) {
1420 u"Implicitly defining \"%1\" as signal handler in Connections is deprecated. "
1421 u"Create a function instead: \"function %2(%3) { ... }\"."_s.arg(
1422 handlerName, handlerName, handlerParameters.join(u", ")),
1423 qmlUnqualified, location,
true,
true);
1427 auto baseType = QQmlJSScope::nonCompositeBaseType(signalScope);
1428 if (baseType && baseType->hasCustomParser())
1432 QStringLiteral(
"no matching signal found for handler \"%1\"").arg(handlerName),
1433 qmlUnqualified, location,
true,
true);
1437 const auto signalParameters = signalMethod->parameters();
1438 QHash<QString, qsizetype> parameterNameIndexes;
1440 for (
int i = 0, end = signalParameters.size(); i < end; i++) {
1441 auto &p = signalParameters[i];
1442 parameterNameIndexes[p.name()] = i;
1444 auto signalName = [&]() {
1446 return u" called %1"_s.arg(*signal);
1449 auto type = p.type();
1452 "Type %1 of parameter %2 in signal%3 was not found, but is required to compile "
1453 "%4."_L1.arg(p.typeName(), p.name(), signalName(), handlerName),
1454 qmlSignalParameters, location);
1458 if (type->isComposite())
1466 auto parameterName = [&]() {
1467 if (p.name().isEmpty())
1469 return u" called %1"_s.arg(p.name());
1471 switch (type->accessSemantics()) {
1472 case QQmlJSScope::AccessSemantics::Reference:
1474 m_logger->log(QStringLiteral(
"Type %1 of parameter%2 in signal%3 should be "
1475 "passed by pointer to be able to compile %4. ")
1476 .arg(p.typeName(), parameterName(), signalName(),
1478 qmlSignalParameters, location);
1480 case QQmlJSScope::AccessSemantics::Value:
1481 case QQmlJSScope::AccessSemantics::Sequence:
1485 "Type %1 of parameter%2 in signal%3 should be passed by "
1486 "value or const reference to be able to compile %4. ")
1487 .arg(p.typeName(), parameterName(), signalName(),
1489 qmlSignalParameters, location);
1491 case QQmlJSScope::AccessSemantics::None:
1493 QStringLiteral(
"Type %1 of parameter%2 in signal%3 required by the "
1494 "compilation of %4 cannot be used. ")
1495 .arg(p.typeName(), parameterName(), signalName(), handlerName),
1496 qmlSignalParameters, location);
1501 if (handlerParameters.size() > signalParameters.size()) {
1502 m_logger->log(QStringLiteral(
"Signal handler for \"%2\" has more formal"
1503 " parameters than the signal it handles.")
1505 qmlSignalParameters, location);
1509 for (qsizetype i = 0, end = handlerParameters.size(); i < end; i++) {
1510 const QStringView handlerParameter = handlerParameters.at(i);
1511 auto it = parameterNameIndexes.constFind(handlerParameter.toString());
1512 if (it == parameterNameIndexes.constEnd())
1514 const qsizetype j = *it;
1519 m_logger->log(QStringLiteral(
"Parameter %1 to signal handler for \"%2\""
1520 " is called \"%3\". The signal has a parameter"
1521 " of the same name in position %4.")
1522 .arg(QString::number(i + 1), handlerName, handlerParameter,
1523 QString::number(j + 1)),
1524 qmlSignalParameters, location);
1528void QQmlJSImportVisitor::addDefaultProperties()
1530 QQmlJSScope::ConstPtr parentScope = m_currentScope->parentScope();
1531 if (m_currentScope == m_exportedRootScope || parentScope->isArrayScope()
1532 || m_currentScope->isInlineComponent())
1535 m_pendingDefaultProperties[m_currentScope->parentScope()] << m_currentScope;
1537 if (checkCustomParser(parentScope))
1541
1542
1543
1544
1545
1546
1547
1548
1549
1551 parentScope = parentScope->baseType();
1553 const QString defaultPropertyName =
1554 parentScope ? parentScope->defaultPropertyName() : QString();
1556 if (defaultPropertyName.isEmpty())
1561 QQmlJSMetaPropertyBinding binding(m_currentScope->sourceLocation(), defaultPropertyName);
1562 binding.setObject(QQmlJSUtils::getScopeName(m_currentScope, QQmlSA::ScopeType::QMLScope),
1563 QQmlJSScope::ConstPtr(m_currentScope));
1564 m_bindings.append(UnfinishedBinding { m_currentScope->parentScope(), [=]() {
return binding; },
1565 QQmlJSScope::UnnamedPropertyTarget });
1568void QQmlJSImportVisitor::breakInheritanceCycles(
const QQmlJSScope::Ptr &originalScope)
1570 QList<QQmlJSScope::ConstPtr> scopes;
1571 for (QQmlJSScope::ConstPtr scope = originalScope; scope;) {
1572 if (scopes.contains(scope)) {
1573 QString inheritenceCycle;
1574 for (
const auto &seen : std::as_const(scopes)) {
1575 inheritenceCycle.append(seen->baseTypeName());
1576 inheritenceCycle.append(QLatin1String(
" -> "));
1578 inheritenceCycle.append(scopes.first()->baseTypeName());
1580 const QString message = QStringLiteral(
"%1 is part of an inheritance cycle: %2")
1581 .arg(originalScope->baseTypeName(), inheritenceCycle);
1582 m_logger->log(message, qmlInheritanceCycle, scope->sourceLocation());
1583 originalScope->clearBaseType();
1584 originalScope->setBaseTypeError(message);
1588 scopes.append(scope);
1590 const auto newScope = scope->baseType();
1591 if (newScope.isNull()) {
1592 const QString error = scope->baseTypeError();
1593 const QString name = scope->baseTypeName();
1594 if (!error.isEmpty()) {
1595 m_logger->log(error, qmlImport, scope->sourceLocation(),
true,
true);
1596 }
else if (!name.isEmpty() && !m_unresolvedTypes.hasSeen(scope)
1597 && !m_logger->isDisabled()) {
1598 m_logger->log(name +
' '_L1 + wasNotFound +
' '_L1, qmlImport,
1599 scope->sourceLocation(),
true,
true,
1600 QQmlJSUtils::didYouMean(
1601 scope->baseTypeName(), m_rootScopeImports.types().keys(),
1602 m_logger->filePath(), scope->sourceLocation()));
1610void QQmlJSImportVisitor::checkDeprecation(
const QQmlJSScope::ConstPtr &originalScope)
1612 for (QQmlJSScope::ConstPtr scope = originalScope; scope; scope = scope->baseType()) {
1613 for (
const QQmlJSAnnotation &annotation : scope->annotations()) {
1614 if (annotation.isDeprecation()) {
1615 QQQmlJSDeprecation deprecation = annotation.deprecation();
1618 QStringLiteral(
"Type \"%1\" is deprecated").arg(scope->internalName());
1620 if (!deprecation.reason.isEmpty())
1621 message.append(QStringLiteral(
" (Reason: %1)").arg(deprecation.reason));
1623 m_logger->log(message, qmlDeprecated, originalScope->sourceLocation());
1629void QQmlJSImportVisitor::checkForComponentTypeWithProperties(
const QQmlJSScope::ConstPtr &scope)
1631 const QQmlJSScope::ConstPtr base = scope->baseType();
1638 if (base->isComposite())
1641 if (base->internalName() !=
"QQmlComponent"_L1)
1644 const auto ownProperties = scope->ownProperties();
1645 for (
const auto &property : ownProperties) {
1646 m_logger->log(
"Component objects cannot declare new properties."_L1,
1647 qmlSyntax, property.sourceLocation());
1651bool QQmlJSImportVisitor::checkCustomParser(
const QQmlJSScope::ConstPtr &scope)
1653 return scope->isInCustomParserParent();
1656void QQmlJSImportVisitor::flushPendingSignalParameters()
1658 const QQmlJSMetaSignalHandler handler = m_signalHandlers[m_pendingSignalHandler];
1659 for (
const QString ¶meter : handler.signalParameters) {
1660 safeInsertJSIdentifier(m_currentScope, parameter,
1661 { QQmlJSScope::JavaScriptIdentifier::Injected,
1662 m_pendingSignalHandler, std::nullopt,
false });
1664 m_pendingSignalHandler = QQmlJS::SourceLocation();
1668
1669
1670
1671
1672
1673
1674QQmlJSMetaMethod::RelativeFunctionIndex
1675QQmlJSImportVisitor::addFunctionOrExpression(
const QQmlJSScope::ConstPtr &scope,
1676 const QString &name)
1678 auto &array = m_functionsAndExpressions[scope];
1679 array.emplaceBack(name);
1686 for (
const auto &function : std::as_const(m_functionStack))
1687 m_innerFunctions[function]++;
1688 m_functionStack.push({ scope, name });
1690 return QQmlJSMetaMethod::RelativeFunctionIndex {
int(array.size() - 1) };
1694
1695
1696
1697
1698
1699
1700
1701
1702void QQmlJSImportVisitor::forgetFunctionExpression(
const QString &name)
1704 auto nameToVerify = name.isEmpty() ? u"<anon>"_s : name;
1705 Q_UNUSED(nameToVerify);
1706 Q_ASSERT(!m_functionStack.isEmpty());
1707 Q_ASSERT(m_functionStack.top().name == nameToVerify);
1708 m_functionStack.pop();
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723int QQmlJSImportVisitor::synthesizeCompilationUnitRuntimeFunctionIndices(
1724 const QQmlJSScope::Ptr &scope,
int count)
const
1726 const auto suitableScope = [](
const QQmlJSScope::Ptr &scope) {
1727 const auto type = scope->scopeType();
1728 return type == QQmlSA::ScopeType::QMLScope
1729 || type == QQmlSA::ScopeType::GroupedPropertyScope
1730 || type == QQmlSA::ScopeType::AttachedPropertyScope;
1733 if (!suitableScope(scope))
1736 auto it = m_functionsAndExpressions.constFind(scope);
1737 if (it == m_functionsAndExpressions.cend())
1740 const auto &functionsAndExpressions = *it;
1741 for (
const QString &functionOrExpression : functionsAndExpressions) {
1742 scope->addOwnRuntimeFunctionIndex(
1743 static_cast<QQmlJSMetaMethod::AbsoluteFunctionIndex>(count));
1760 count += m_innerFunctions.value({ scope, functionOrExpression }, 0);
1766void QQmlJSImportVisitor::populateRuntimeFunctionIndicesForDocument()
const
1769 const auto synthesize = [&](
const QQmlJSScope::Ptr ¤t) {
1770 count = synthesizeCompilationUnitRuntimeFunctionIndices(current, count);
1772 QQmlJSUtils::traverseFollowingQmlIrObjectStructure(m_exportedRootScope, synthesize);
1775bool QQmlJSImportVisitor::visit(QQmlJS::AST::ExpressionStatement *ast)
1777 if (m_pendingSignalHandler.isValid()) {
1778 enterEnvironment(QQmlSA::ScopeType::SignalHandlerFunctionScope, u"signalhandler"_s,
1779 ast->firstSourceLocation());
1780 flushPendingSignalParameters();
1785void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ExpressionStatement *)
1787 if (m_currentScope->scopeType() == QQmlSA::ScopeType::SignalHandlerFunctionScope) {
1794 const QQmlJS::SourceLocation &srcLocation);
1797 QQmlJSLogger *logger)
1799 QStringView namespaceName{ superType };
1800 namespaceName = namespaceName.first(namespaceName.indexOf(u'.'));
1801 logger->log(u"Namespace '%1' of '%2' must start with an upper case letter."_s
1802 .arg(namespaceName, superType),
1803 qmlUncreatableType, location,
true,
true);
1806bool QQmlJSImportVisitor::visit(UiObjectDefinition *definition)
1808 const QString superType = buildName(definition->qualifiedTypeNameId);
1810 const bool isRoot = !rootScopeIsValid();
1811 Q_ASSERT(!superType.isEmpty());
1818 const qsizetype indexOfTypeName = superType.lastIndexOf(u'.');
1819 const bool looksLikeGroupedProperty = !superType.front().isUpper();
1821 if (indexOfTypeName != -1 && looksLikeGroupedProperty) {
1822 logLowerCaseImport(superType, definition->qualifiedTypeNameId->identifierToken,
1826 if (!looksLikeGroupedProperty) {
1828 enterEnvironment(QQmlSA::ScopeType::QMLScope, superType,
1829 definition->firstSourceLocation());
1831 enterRootScope(QQmlSA::ScopeType::QMLScope, superType,
1832 definition->firstSourceLocation());
1833 m_currentScope->setIsRootFileComponentFlag(
true);
1836 const QTypeRevision revision = m_currentScope->baseTypeRevision();
1837 if (
auto base = m_currentScope->baseType(); base) {
1838 if (isRoot && base->internalName() == u"QQmlComponent") {
1839 m_logger->log(u"Qml top level type cannot be 'Component'."_s, qmlTopLevelComponent,
1840 definition->qualifiedTypeNameId->identifierToken,
true,
true);
1842 if (base->isSingleton() && m_currentScope->isComposite()) {
1843 m_logger->log(u"Singleton Type %1 is not creatable."_s.arg(
1844 m_currentScope->baseTypeName()),
1845 qmlUncreatableType, definition->qualifiedTypeNameId->identifierToken,
1848 }
else if (!base->isCreatable()) {
1850 m_logger->log(u"Type %1 is not creatable."_s.arg(m_currentScope->baseTypeName()),
1851 qmlUncreatableType, definition->qualifiedTypeNameId->identifierToken,
1855 if (m_nextIsInlineComponent) {
1856 Q_ASSERT(std::holds_alternative<InlineComponentNameType>(m_currentRootName));
1857 const QString &name = std::get<InlineComponentNameType>(m_currentRootName);
1858 m_currentScope->setIsInlineComponent(
true);
1859 m_currentScope->setInlineComponentName(name);
1860 m_currentScope->setOwnModuleName(m_exportedRootScope->moduleName());
1861 auto precedence = quint8(QQmlJS::PrecedenceValues::InlineComponent);
1862 m_rootScopeImports.setType(name, { m_currentScope, revision, precedence });
1863 m_nextIsInlineComponent =
false;
1866 addDefaultProperties();
1867 Q_ASSERT(m_currentScope->scopeType() == QQmlSA::ScopeType::QMLScope);
1868 m_qmlTypes.append(m_currentScope);
1870 m_objectDefinitionScopes << m_currentScope;
1872 m_groupedObjectDefinitions.append(
1873 combine(definition->firstSourceLocation(), definition->lastSourceLocation()));
1874 enterEnvironmentNonUnique(QQmlSA::ScopeType::GroupedPropertyScope, superType,
1875 definition->firstSourceLocation());
1876 m_bindings.append(createNonUniqueScopeBinding(m_currentScope, superType,
1877 definition->firstSourceLocation()));
1878 QQmlJSScope::resolveTypes(m_currentScope, m_rootScopeImports.contextualTypes(),
1882 m_currentScope->setAnnotations(parseAnnotations(definition->annotations));
1887void QQmlJSImportVisitor::endVisit(UiObjectDefinition *)
1889 QQmlJSScope::resolveTypes(m_currentScope, m_rootScopeImports.contextualTypes(), usedTypes());
1893bool QQmlJSImportVisitor::visit(UiInlineComponent *component)
1895 if (!std::holds_alternative<RootDocumentNameType>(m_currentRootName)) {
1900 const auto it = m_seenInlineComponents.constFind(component->name);
1901 if (it != m_seenInlineComponents.cend()) {
1902 m_logger->log(
"Note: previous component named '%1' here"_L1.arg(it.key()),
1903 qmlDuplicateInlineComponent, it.value(),
true,
true, {},
1904 component->firstSourceLocation().startLine);
1906 m_seenInlineComponents[component->name] = component->firstSourceLocation();
1909 m_nextIsInlineComponent =
true;
1910 m_currentRootName = component->name.toString();
1914void QQmlJSImportVisitor::endVisit(UiInlineComponent *component)
1916 m_currentRootName = RootDocumentNameType();
1917 if (m_nextIsInlineComponent) {
1918 m_logger->log(u"Inline component declaration must be followed by a typename"_s,
1919 qmlSyntax, component->firstSourceLocation());
1921 m_nextIsInlineComponent =
false;
1924bool QQmlJSImportVisitor::visit(UiPublicMember *publicMember)
1926 switch (publicMember->type) {
1927 case UiPublicMember::Signal: {
1928 const QString signalName = publicMember->name.toString();
1929 UiParameterList *param = publicMember->parameters;
1930 QQmlJSMetaMethod method;
1931 method.setMethodType(QQmlJSMetaMethodType::Signal);
1932 method.setReturnTypeName(QStringLiteral(
"void"));
1933 method.setMethodName(signalName);
1934 method.setSourceLocation(combine(publicMember->firstSourceLocation(),
1935 publicMember->lastSourceLocation()));
1936 method.setMethodIndex(
1937 QQmlJSMetaMethod::RelativeFunctionIndex(m_currentScope->ownMethods().size()));
1939 method.addParameter(
1940 QQmlJSMetaParameter(
1941 param->name.toString(),
1942 param->type ? param->type->toString() : QString()
1944 param = param->next;
1946 m_currentScope->addOwnMethod(method);
1949 case UiPublicMember::Property: {
1950 const QString propertyName = publicMember->name.toString();
1951 QString typeName = buildName(publicMember->memberType);
1952 if (typeName.contains(u'.') && typeName.front().isLower()) {
1953 logLowerCaseImport(typeName, publicMember->typeToken, m_logger);
1957 const bool isAlias = (typeName == u"alias"_s);
1959 auto tryParseAlias = [&]() {
1961 if (!publicMember->statement) {
1962 m_logger->log(QStringLiteral(
"Invalid alias expression - an initializer is needed."),
1963 qmlSyntax, publicMember->memberType->firstSourceLocation());
1966 const auto expression = cast<ExpressionStatement *>(publicMember->statement);
1967 auto node = expression ? expression->expression :
nullptr;
1968 auto fex = cast<FieldMemberExpression *>(node);
1971 aliasExpr.prepend(u'.' + fex->name.toString());
1972 fex = cast<FieldMemberExpression *>(node);
1975 if (
const auto idExpression = cast<IdentifierExpression *>(node)) {
1976 aliasExpr.prepend(idExpression->name.toString());
1981 QQmlJSMetaProperty prop;
1982 prop.setPropertyName(propertyName);
1983 prop.setIsList(publicMember->typeModifier == QLatin1String(
"list"));
1984 prop.setIsWritable(!publicMember->isReadonly());
1985 prop.setIsFinal(publicMember->isFinal());
1986 prop.setIsVirtual(publicMember->isVirtual());
1987 prop.setIsOverride(publicMember->isOverride());
1988 prop.setAliasExpression(aliasExpr);
1989 prop.setSourceLocation(
1990 combine(publicMember->firstSourceLocation(), publicMember->colonToken));
1992 isAlias ? QQmlJSScope::ConstPtr() : m_rootScopeImports.type(typeName).scope;
1994 const auto factory = type.factory();
1995 prop.setType(prop.isList() ? (factory ? QQmlJSScope::Ptr{ } : type->listType()) : type);
1996 const bool isListOfLazyType = prop.isList() && factory;
1997 if (isListOfLazyType) {
1998 m_pendingPropertyTypes << PendingPropertyType {
1999 m_currentScope, prop.propertyName(), publicMember->firstSourceLocation()
2001 prop.setTypeName(typeName);
2003 const QString internalName =
2004 factory ? factory->internalName() : type->internalName();
2005 prop.setTypeName(internalName.isEmpty() ? typeName : internalName);
2012 Q_ASSERT(type.factory() == factory);
2013 }
else if (!isAlias) {
2014 m_pendingPropertyTypes << PendingPropertyType { m_currentScope, prop.propertyName(),
2015 publicMember->firstSourceLocation() };
2016 prop.setTypeName(typeName);
2018 prop.setAnnotations(parseAnnotations(publicMember->annotations));
2019 if (publicMember->isDefaultMember())
2020 m_currentScope->setOwnDefaultPropertyName(propertyName);
2021 prop.setIndex(m_currentScope->ownProperties().size());
2022 m_currentScope->addOwnProperty(prop);
2024 QQmlJSMetaMethod method(
2025 QQmlSignalNames::propertyNameToChangedSignalName(propertyName), u"void"_s);
2026 method.setMethodType(QQmlJSMetaMethodType::Signal);
2027 method.setIsImplicitQmlPropertyChangeSignal(
true);
2028 method.setMethodIndex(
2029 QQmlJSMetaMethod::RelativeFunctionIndex(m_currentScope->ownMethods().size()));
2030 m_currentScope->addOwnMethod(method);
2032 if (publicMember->isRequired())
2033 m_currentScope->setPropertyLocallyRequired(prop.propertyName(),
true);
2035 BindingExpressionParseResult parseResult = BindingExpressionParseResult::Invalid;
2039 parseBindingExpression(publicMember->name.toString(), publicMember->statement,
2045 if (parseResult == BindingExpressionParseResult::Script) {
2046 Q_ASSERT(!m_savedBindingOuterScope);
2047 m_savedBindingOuterScope = m_currentScope;
2048 enterEnvironment(QQmlSA::ScopeType::BindingFunctionScope, QStringLiteral(
"binding"),
2049 publicMember->statement->firstSourceLocation());
2059void QQmlJSImportVisitor::endVisit(UiPublicMember *publicMember)
2061 if (m_savedBindingOuterScope) {
2062 m_currentScope = m_savedBindingOuterScope;
2063 m_savedBindingOuterScope = {};
2065 forgetFunctionExpression(publicMember->name.toString());
2069bool QQmlJSImportVisitor::visit(UiRequired *required)
2071 const QString name = required->name.toString();
2073 m_requiredProperties << RequiredProperty { m_currentScope, name,
2074 required->firstSourceLocation() };
2076 m_currentScope->setPropertyLocallyRequired(name,
true);
2080void QQmlJSImportVisitor::visitFunctionExpressionHelper(QQmlJS::AST::FunctionExpression *fexpr)
2082 using namespace QQmlJS::AST;
2083 auto name = fexpr->name.toString();
2084 if (!name.isEmpty()) {
2085 QQmlJSMetaMethod method(name);
2086 method.setMethodType(QQmlJSMetaMethodType::Method);
2087 method.setSourceLocation(combine(fexpr->firstSourceLocation(), fexpr->lastSourceLocation()));
2089 if (!m_pendingMethodAnnotations.isEmpty()) {
2090 method.setAnnotations(m_pendingMethodAnnotations);
2091 m_pendingMethodAnnotations.clear();
2095 const bool parseTypes = m_scopesById.signaturesAreEnforced();
2097 bool formalsFullyTyped = parseTypes;
2098 bool anyFormalTyped =
false;
2099 PendingMethodTypeAnnotations pending{ m_currentScope, name, {} };
2102 for (
auto formals = fexpr->formals; formals; formals = formals->next) {
2103 PatternElement *e = formals->element;
2106 if (e->typeAnnotation && (e->bindingTarget || e->initializer))
2107 m_logger->log(
"Type annotations on default parameters are not supported"_L1,
2109 combine(e->firstSourceLocation(), e->lastSourceLocation()));
2112 if (
const auto *formals = parseTypes ? fexpr->formals :
nullptr) {
2113 const auto parameters = formals->formals();
2114 for (
const auto ¶meter : parameters) {
2115 const QString type = parameter.typeAnnotation
2116 ? parameter.typeAnnotation->type->toString()
2118 if (type.isEmpty()) {
2119 formalsFullyTyped =
false;
2120 method.addParameter(QQmlJSMetaParameter(parameter.id, QStringLiteral(
"var")));
2121 pending.locations.emplace_back();
2123 anyFormalTyped =
true;
2124 method.addParameter(QQmlJSMetaParameter(parameter.id, type));
2125 pending.locations.append(
2126 combine(parameter.typeAnnotation->firstSourceLocation(),
2127 parameter.typeAnnotation->lastSourceLocation()));
2133 method.setIsJavaScriptFunction(!formalsFullyTyped);
2139 if (parseTypes && fexpr->typeAnnotation) {
2140 method.setReturnTypeName(fexpr->typeAnnotation->type->toString());
2141 pending.locations.append(combine(fexpr->typeAnnotation->firstSourceLocation(),
2142 fexpr->typeAnnotation->lastSourceLocation()));
2143 }
else if (anyFormalTyped) {
2144 method.setReturnTypeName(QStringLiteral(
"void"));
2146 method.setReturnTypeName(QStringLiteral(
"var"));
2149 const auto &locs = pending.locations;
2150 if (std::any_of(locs.cbegin(), locs.cend(), [](
const auto &loc) {
return loc.isValid(); }))
2151 m_pendingMethodTypeAnnotations << pending;
2153 method.setCompiledFunctionIndex(addFunctionOrExpression(m_currentScope, method.methodName()));
2154 method.setMethodIndex(
2155 QQmlJSMetaMethod::RelativeFunctionIndex(m_currentScope->ownMethods().size()));
2157 if (m_currentScope->scopeType() != QQmlSA::ScopeType::QMLScope) {
2159 const QQmlJS::SourceLocation functionLocation = fexpr->identifierToken.isValid()
2160 ? fexpr->identifierToken
2161 : fexpr->functionToken;
2162 safeInsertJSIdentifier(m_currentScope, name,
2163 { QQmlJSScope::JavaScriptIdentifier::LexicalScoped,
2164 functionLocation, method.returnTypeName(),
2167 m_currentScope->addOwnMethod(method);
2169 enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, name, fexpr->firstSourceLocation());
2171 addFunctionOrExpression(m_currentScope, QStringLiteral(
"<anon>"));
2172 enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, QStringLiteral(
"<anon>"),
2173 fexpr->firstSourceLocation());
2177bool QQmlJSImportVisitor::visit(QQmlJS::AST::FunctionExpression *fexpr)
2179 visitFunctionExpressionHelper(fexpr);
2183void QQmlJSImportVisitor::endVisit(QQmlJS::AST::FunctionExpression *fexpr)
2185 forgetFunctionExpression(fexpr->name.toString());
2189bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiSourceElement *srcElement)
2191 m_pendingMethodAnnotations = parseAnnotations(srcElement->annotations);
2195bool QQmlJSImportVisitor::visit(QQmlJS::AST::FunctionDeclaration *fdecl)
2197 if (!fdecl->name.isEmpty()) {
2198 const QString name = fdecl->name.toString();
2199 if (
auto previousDeclaration = m_currentScope->ownJSIdentifier(name)) {
2200 m_logger->log(
"Identifier '%1' has already been declared"_L1.arg(name), qmlSyntax,
2201 fdecl->identifierToken);
2202 m_logger->log(
"Note: previous declaration of '%1' here"_L1.arg(name), qmlSyntax,
2203 previousDeclaration->location);
2206 visitFunctionExpressionHelper(fdecl);
2210void QQmlJSImportVisitor::endVisit(QQmlJS::AST::FunctionDeclaration *fdecl)
2212 forgetFunctionExpression(fdecl->name.toString());
2216bool QQmlJSImportVisitor::visit(QQmlJS::AST::ClassExpression *ast)
2218 QQmlJSMetaProperty prop;
2219 prop.setPropertyName(ast->name.toString());
2220 m_currentScope->addOwnProperty(prop);
2221 enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, ast->name.toString(),
2222 ast->firstSourceLocation());
2226void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ClassExpression *)
2232 QQmlJS::AST::ArgumentList *args)
2234 QStringView contextString;
2235 QStringView mainString;
2236 QStringView commentString;
2237 auto registerContextString = [&](QStringView string) {
2238 contextString = string;
2241 auto registerMainString = [&](QStringView string) {
2242 mainString = string;
2245 auto registerCommentString = [&](QStringView string) {
2246 commentString = string;
2249 auto finalizeBinding = [&](QV4::CompiledData::Binding::Type type,
2250 QV4::CompiledData::TranslationData data) {
2251 if (type == QV4::CompiledData::Binding::Type_Translation) {
2252 binding.setTranslation(mainString, commentString, contextString, data.number);
2253 }
else if (type == QV4::CompiledData::Binding::Type_TranslationById) {
2254 binding.setTranslationId(mainString, data.number);
2256 binding.setStringLiteral(mainString);
2259 QmlIR::tryGeneratingTranslationBindingBase(
2261 registerMainString, registerCommentString, registerContextString, finalizeBinding);
2264QQmlJSImportVisitor::BindingExpressionParseResult
2265QQmlJSImportVisitor::parseBindingExpression(
2266 const QString &name,
const QQmlJS::AST::Statement *statement,
2267 const UiPublicMember *associatedPropertyDefinition)
2269 if (statement ==
nullptr)
2270 return BindingExpressionParseResult::Invalid;
2272 const auto *exprStatement = cast<
const ExpressionStatement *>(statement);
2274 if (exprStatement ==
nullptr) {
2275 QQmlJS::SourceLocation location = statement->firstSourceLocation();
2277 if (
const auto *block = cast<
const Block *>(statement); block && block->statements) {
2278 location = block->statements->firstSourceLocation();
2281 QQmlJSMetaPropertyBinding binding(location, name);
2282 binding.setScriptBinding(addFunctionOrExpression(m_currentScope, name),
2283 QQmlSA::ScriptBindingKind::PropertyBinding, ScriptValue_Function);
2284 m_bindings.append(UnfinishedBinding {
2286 [binding = std::move(binding)]() {
return binding; }
2288 return BindingExpressionParseResult::Script;
2291 auto expr = exprStatement->expression;
2292 QQmlJSMetaPropertyBinding binding(
2293 combine(expr->firstSourceLocation(), expr->lastSourceLocation()),
2296 ScriptBindingValueType scriptBindingValuetype = ScriptValue_Unknown;
2298 switch (expr->kind) {
2299 case Node::Kind_TrueLiteral:
2300 binding.setBoolLiteral(
true);
2302 case Node::Kind_FalseLiteral:
2303 binding.setBoolLiteral(
false);
2305 case Node::Kind_NullExpression:
2306 binding.setNullLiteral();
2308 case Node::Kind_IdentifierExpression: {
2309 auto idExpr = QQmlJS::AST::cast<QQmlJS::AST::IdentifierExpression *>(expr);
2311 if (idExpr->name == u"undefined")
2312 scriptBindingValuetype = ScriptValue_Undefined;
2315 case Node::Kind_FunctionDeclaration:
2316 case Node::Kind_FunctionExpression:
2317 case Node::Kind_Block: {
2318 scriptBindingValuetype = ScriptValue_Function;
2321 case Node::Kind_NumericLiteral:
2322 binding.setNumberLiteral(cast<NumericLiteral *>(expr)->value);
2324 case Node::Kind_StringLiteral:
2325 binding.setStringLiteral(cast<StringLiteral *>(expr)->value);
2327 case Node::Kind_RegExpLiteral:
2328 binding.setRegexpLiteral(cast<RegExpLiteral *>(expr)->pattern);
2330 case Node::Kind_TemplateLiteral: {
2331 auto templateLit = QQmlJS::AST::cast<QQmlJS::AST::TemplateLiteral *>(expr);
2332 Q_ASSERT(templateLit);
2333 if (templateLit->hasNoSubstitution) {
2334 binding.setStringLiteral(templateLit->value);
2336 binding.setScriptBinding(addFunctionOrExpression(m_currentScope, name),
2337 QQmlSA::ScriptBindingKind::PropertyBinding);
2342 if (QQmlJS::AST::UnaryMinusExpression *unaryMinus = QQmlJS::AST::cast<QQmlJS::AST::UnaryMinusExpression *>(expr)) {
2343 if (QQmlJS::AST::NumericLiteral *lit = QQmlJS::AST::cast<QQmlJS::AST::NumericLiteral *>(unaryMinus->expression))
2344 binding.setNumberLiteral(-lit->value);
2345 }
else if (QQmlJS::AST::CallExpression *call = QQmlJS::AST::cast<QQmlJS::AST::CallExpression *>(expr)) {
2346 if (QQmlJS::AST::IdentifierExpression *base = QQmlJS::AST::cast<QQmlJS::AST::IdentifierExpression *>(call->base))
2347 handleTranslationBinding(binding, base->name, call->arguments);
2352 if (!binding.isValid()) {
2354 binding.setScriptBinding(addFunctionOrExpression(m_currentScope, name),
2355 QQmlSA::ScriptBindingKind::PropertyBinding,
2356 scriptBindingValuetype);
2358 m_bindings.append(UnfinishedBinding { m_currentScope, [=]() {
return binding; } });
2361 if (binding.bindingType() == QQmlSA::BindingType::Translation
2362 || binding.bindingType() == QQmlSA::BindingType::TranslationById) {
2363 return BindingExpressionParseResult::Translation;
2365 if (!QQmlJSMetaPropertyBinding::isLiteralBinding(binding.bindingType()))
2366 return BindingExpressionParseResult::Script;
2368 if (associatedPropertyDefinition)
2369 handleLiteralBinding(binding, associatedPropertyDefinition);
2371 return BindingExpressionParseResult::Literal;
2374bool QQmlJSImportVisitor::isImportPrefix(QString prefix)
const
2376 if (prefix.isEmpty() || !prefix.front().isUpper())
2379 return m_rootScopeImports.isNullType(prefix);
2382void QQmlJSImportVisitor::handleIdDeclaration(QQmlJS::AST::UiScriptBinding *scriptBinding)
2384 if (m_currentScope->scopeType() != QQmlJSScope::ScopeType::QMLScope) {
2385 m_logger->log(u"id declarations are only allowed in objects"_s, qmlSyntax,
2386 scriptBinding->statement->firstSourceLocation());
2389 const auto *statement = cast<ExpressionStatement *>(scriptBinding->statement);
2394 const QString name = [&]() {
2395 if (
const auto *idExpression = cast<IdentifierExpression *>(statement->expression))
2396 return idExpression->name.toString();
2397 else if (
const auto *idString = cast<StringLiteral *>(statement->expression)) {
2398 m_logger->log(u"ids do not need quotation marks"_s, qmlSyntaxIdQuotation,
2399 idString->firstSourceLocation());
2400 return idString->value.toString();
2406 m_currentScope->setIdSourceLocation(combine(scriptBinding->statement->firstSourceLocation(),
2407 scriptBinding->statement->lastSourceLocation()));
2408 if (m_scopesById.existsAnywhereInDocument(name)) {
2411 breakInheritanceCycles(m_currentScope);
2412 m_scopesById.possibleScopes(
2413 name, m_currentScope, QQmlJSScopesByIdOption::Default,
2414 [&](
const QQmlJSScope::ConstPtr &otherScopeWithID,
2415 QQmlJSScopesById::Confidence confidence) {
2417 Q_UNUSED(confidence);
2419 auto otherLocation = otherScopeWithID->sourceLocation();
2423 m_logger->log(u"Found a duplicated id. id %1 was first declared at %2:%3"_s.arg(
2424 name, QString::number(otherLocation.startLine),
2425 QString::number(otherLocation.startColumn)),
2426 qmlSyntaxDuplicateIds,
2427 scriptBinding->firstSourceLocation());
2428 return QQmlJSScopesById::CallbackResult::ContinueSearch;
2431 if (!name.isEmpty())
2432 m_scopesById.insert(name, m_currentScope);
2435void QQmlJSImportVisitor::handleLiteralBinding(
const QQmlJSMetaPropertyBinding &binding,
2436 const UiPublicMember *associatedPropertyDefinition)
2440 Q_UNUSED(associatedPropertyDefinition);
2444
2445
2446
2447
2448
2451 const QQmlJS::SourceLocation &srcLocation)
2453 const auto createBinding = [=]() {
2454 const QQmlJSScope::ScopeType type = scope->scopeType();
2461 const auto propertyBindings = scope->parentScope()->ownPropertyBindings(name);
2462 const bool alreadyHasBinding =
std::any_of(propertyBindings.first, propertyBindings.second,
2463 [&](
const QQmlJSMetaPropertyBinding &binding) {
2464 return binding.bindingType() == bindingType;
2466 if (alreadyHasBinding)
2467 return QQmlJSMetaPropertyBinding(QQmlJS::SourceLocation {});
2470 if (type == QQmlSA::ScopeType::GroupedPropertyScope)
2471 binding.setGroupBinding(
static_cast<QSharedPointer<QQmlJSScope>>(scope));
2473 binding.setAttachedBinding(
static_cast<QSharedPointer<QQmlJSScope>>(scope));
2476 return { scope->parentScope(), createBinding };
2479bool QQmlJSImportVisitor::visit(UiScriptBinding *scriptBinding)
2481 Q_ASSERT(!m_savedBindingOuterScope);
2482 Q_ASSERT(!m_thisScriptBindingIsJavaScript);
2483 m_savedBindingOuterScope = m_currentScope;
2484 const auto id = scriptBinding->qualifiedId;
2485 if (!id->next && id->name == QLatin1String(
"id")) {
2486 handleIdDeclaration(scriptBinding);
2493 for (; group->next; group = group->next) {
2494 const QString name = group->name.toString();
2498 if (group == id && isImportPrefix(name)) {
2499 prefix = name + u'.';
2503 const bool isAttachedProperty = name.front().isUpper();
2504 if (isAttachedProperty) {
2506 enterEnvironmentNonUnique(QQmlSA::ScopeType::AttachedPropertyScope, prefix + name,
2507 group->firstSourceLocation());
2510 enterEnvironmentNonUnique(QQmlSA::ScopeType::GroupedPropertyScope, prefix + name,
2511 group->firstSourceLocation());
2513 m_bindings.append(createNonUniqueScopeBinding(m_currentScope, prefix + name,
2514 group->firstSourceLocation()));
2519 const auto name = group->name.toString();
2523 const auto signal = QQmlSignalNames::handlerNameToSignalName(name);
2525 if (!signal.has_value() || m_currentScope->hasProperty(name)) {
2526 m_propertyBindings[m_currentScope].append(
2527 { m_savedBindingOuterScope, group->firstSourceLocation(), name });
2529 auto result = parseBindingExpression(name, scriptBinding->statement);
2530 m_thisScriptBindingIsJavaScript = (result == BindingExpressionParseResult::Script);
2532 const auto statement = scriptBinding->statement;
2533 QStringList signalParameters;
2535 if (ExpressionStatement *expr = cast<ExpressionStatement *>(statement)) {
2536 if (FunctionExpression *func = expr->expression->asFunctionDefinition()) {
2537 for (FormalParameterList *formal = func->formals; formal; formal = formal->next)
2538 signalParameters << formal->element->bindingIdentifier.toString();
2542 QQmlJSMetaMethod scopeSignal;
2543 const auto methods = m_currentScope->methods(*signal, QQmlJSMetaMethodType::Signal);
2544 if (!methods.isEmpty())
2545 scopeSignal = methods[0];
2547 const auto firstSourceLocation = statement->firstSourceLocation();
2548 bool hasMultilineStatementBody =
2549 statement->lastSourceLocation().startLine > firstSourceLocation.startLine;
2550 m_pendingSignalHandler = firstSourceLocation;
2551 m_signalHandlers.insert(firstSourceLocation,
2552 { scopeSignal.parameterNames(), hasMultilineStatementBody });
2556 const auto index = addFunctionOrExpression(m_currentScope, name);
2557 const auto createBinding = [
2559 scope = m_currentScope,
2560 signalName = *signal,
2563 firstSourceLocation,
2564 groupLocation = group->firstSourceLocation(),
2565 signalParameters]() {
2567 Q_ASSERT(scope->isFullyResolved());
2568 QQmlSA::ScriptBindingKind kind = QQmlSA::ScriptBindingKind::Invalid;
2569 const auto methods = scope->methods(signalName, QQmlJSMetaMethodType::Signal);
2570 if (!methods.isEmpty()) {
2571 kind = QQmlSA::ScriptBindingKind::SignalHandler;
2572 checkSignal(scope, groupLocation, name, signalParameters);
2573 }
else if (QQmlJSUtils::propertyFromChangedHandler(scope, name).has_value()) {
2574 kind = QQmlSA::ScriptBindingKind::ChangeHandler;
2575 checkSignal(scope, groupLocation, name, signalParameters);
2576 }
else if (scope->hasProperty(name)) {
2579 kind = QQmlSA::ScriptBindingKind::PropertyBinding;
2580 m_signalHandlers.remove(firstSourceLocation);
2583 checkSignal(scope, groupLocation, name, signalParameters);
2586 QQmlJSMetaPropertyBinding binding(firstSourceLocation, name);
2587 binding.setScriptBinding(index, kind, ScriptValue_Function);
2590 m_bindings.append(UnfinishedBinding { m_currentScope, createBinding });
2591 m_thisScriptBindingIsJavaScript =
true;
2597 while (m_currentScope->scopeType() == QQmlSA::ScopeType::GroupedPropertyScope
2598 || m_currentScope->scopeType() == QQmlSA::ScopeType::AttachedPropertyScope) {
2603 enterEnvironment(QQmlSA::ScopeType::SignalHandlerFunctionScope,
2605 scriptBinding->statement->firstSourceLocation());
2607 enterEnvironment(QQmlSA::ScopeType::BindingFunctionScope,
2609 scriptBinding->statement->firstSourceLocation());
2615void QQmlJSImportVisitor::endVisit(UiScriptBinding *)
2617 if (m_savedBindingOuterScope) {
2618 m_currentScope = m_savedBindingOuterScope;
2619 m_savedBindingOuterScope = {};
2625 if (m_thisScriptBindingIsJavaScript) {
2626 m_thisScriptBindingIsJavaScript =
false;
2627 Q_ASSERT(!m_functionStack.isEmpty());
2628 m_functionStack.pop();
2632bool QQmlJSImportVisitor::visit(UiArrayBinding *arrayBinding)
2634 createAttachedAndGroupedScopes(arrayBinding->qualifiedId);
2635 enterEnvironment(QQmlSA::ScopeType::QMLScope, buildName(arrayBinding->qualifiedId),
2636 arrayBinding->firstSourceLocation());
2637 m_currentScope->setIsArrayScope(
true);
2641void QQmlJSImportVisitor::endVisit(UiArrayBinding *arrayBinding)
2648 const auto children = m_currentScope->childScopes();
2651 const int scopesEnteredCounter = openAttachedAndGroupedScopes(arrayBinding->qualifiedId);
2652 auto guard = qScopeGuard([
this, scopesEnteredCounter]() {
2653 for (
int i = 0; i < scopesEnteredCounter; ++i)
2657 if (checkCustomParser(m_currentScope)) {
2663 auto group = arrayBinding->qualifiedId;
2664 for (; group->next; group = group->next) { }
2665 const QString propertyName = group->name.toString();
2668 for (
auto element = arrayBinding->members; element; element = element->next, ++i) {
2669 const auto &type = children[i];
2670 if ((type->scopeType() != QQmlSA::ScopeType::QMLScope)) {
2671 m_logger->log(u"Declaring an object which is not a Qml object"
2672 " as a list member."_s, qmlSyntax, element->firstSourceLocation());
2675 m_pendingPropertyObjectBindings
2676 << PendingPropertyObjectBinding { m_currentScope, type, propertyName,
2677 element->firstSourceLocation(),
false };
2678 QQmlJSMetaPropertyBinding binding(element->firstSourceLocation(), propertyName);
2679 binding.setObject(QQmlJSUtils::getScopeName(type, QQmlSA::ScopeType::QMLScope),
2680 QQmlJSScope::ConstPtr(type));
2681 m_bindings.append(UnfinishedBinding {
2683 [binding = std::move(binding)]() {
return binding; },
2684 QQmlJSScope::ListPropertyTarget
2689bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiEnumDeclaration *uied)
2691 QQmlJSMetaEnum qmlEnum(uied->name.toString());
2692 qmlEnum.setIsQml(
true);
2693 qmlEnum.setLineNumber(uied->enumToken.startLine);
2694 for (
const auto *member = uied->members; member; member = member->next) {
2695 qmlEnum.addKey(member->member.toString());
2696 qmlEnum.addValue(
int(member->value));
2698 m_currentScope->addOwnEnumeration(qmlEnum);
2702QList<QQmlJS::DiagnosticMessage> QQmlJSImportVisitor::importFromHost(
2703 const QString &path,
const QString &prefix,
const QQmlJS::SourceLocation &location)
2705 QFileInfo fileInfo(path);
2706 if (!fileInfo.exists()) {
2707 m_logger->log(
"File or directory you are trying to import does not exist: %1."_L1.arg(path),
2708 qmlImport, location);
2712 if (fileInfo.isFile()) {
2713 const auto scope = m_importer->importFile(path);
2714 const QString actualPrefix = prefix.isEmpty() ? scope->internalName() : prefix;
2715 auto precedence = quint8(QQmlJS::PrecedenceValues::Default);
2716 m_rootScopeImports.setType(actualPrefix, { scope, QTypeRevision(), precedence });
2717 addImportWithLocation(actualPrefix, location,
false);
2721 if (fileInfo.isDir()) {
2722 auto precedence = quint8(QQmlJS::PrecedenceValues::Default);
2723 auto scopes = m_importer->importDirectory(path, precedence, prefix);
2724 m_importer->registerVersionedImports(scopes);
2725 const auto types = scopes.types();
2726 const auto warnings = scopes.warnings();
2727 m_rootScopeImports.add(std::move(scopes));
2728 for (
auto it = types.keyBegin(), end = types.keyEnd(); it != end; it++)
2729 addImportWithLocation(*it, location, !warnings.isEmpty());
2734 "%1 is neither a file nor a directory. Are sure the import path is correct?"_L1.arg(
2736 qmlImport, location);
2740QList<QQmlJS::DiagnosticMessage> QQmlJSImportVisitor::importFromQrc(
2741 const QString &path,
const QString &prefix,
const QQmlJS::SourceLocation &location)
2743 Q_ASSERT(path.startsWith(u':'));
2744 const QQmlJSResourceFileMapper *mapper = m_importer->resourceFileMapper();
2748 const auto pathNoColon = QStringView(path).mid(1);
2749 if (mapper->isFile(pathNoColon)) {
2750 const auto entry = m_importer->resourceFileMapper()->entry(
2751 QQmlJSResourceFileMapper::resourceFileFilter(pathNoColon.toString()));
2752 const auto scope = m_importer->importFile(entry.filePath);
2753 const QString actualPrefix =
2754 prefix.isEmpty() ? QFileInfo(entry.resourcePath).baseName() : prefix;
2755 auto precedence = quint8(QQmlJS::PrecedenceValues::Default);
2756 m_rootScopeImports.setType(actualPrefix, { scope, QTypeRevision(), precedence });
2757 addImportWithLocation(actualPrefix, location,
false);
2761 auto scopes = m_importer->importDirectory(path, quint8(QQmlJS::PrecedenceValues::Default), prefix);
2762 m_importer->registerVersionedImports(scopes);
2763 const auto types = scopes.types();
2764 const auto warnings = scopes.warnings();
2765 m_rootScopeImports.add(std::move(scopes));
2766 for (
auto it = types.keyBegin(), end = types.keyEnd(); it != end; it++)
2767 addImportWithLocation(*it, location, !warnings.isEmpty());
2771bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiImport *import)
2774 QString prefix = QLatin1String(
"");
2775 if (import->asToken.isValid()) {
2776 prefix += import->importId;
2777 m_seenModuleQualifiers.append(prefix);
2780 const QString filename = import->fileName.toString();
2781 if (!filename.isEmpty()) {
2782 const QUrl url(filename);
2783 const QString scheme = url.scheme();
2784 const QQmlJS::SourceLocation importLocation = import->firstSourceLocation();
2785 if (scheme ==
""_L1) {
2786 QFileInfo fileInfo(url.path());
2787 QString absolute = fileInfo.isRelative()
2788 ? QDir::cleanPath(QDir(m_implicitImportDirectory).filePath(filename))
2790 auto warnings = absolute.startsWith(u':')
2791 ? importFromQrc(absolute, prefix, importLocation)
2792 : importFromHost(absolute, prefix, importLocation);
2793 processImportWarnings(
"path \"%1\""_L1.arg(url.path()), warnings, importLocation);
2795 }
else if (scheme ==
"file"_L1) {
2796 auto warnings = importFromHost(url.path(), prefix, importLocation);
2797 processImportWarnings(
"URL \"%1\""_L1.arg(url.path()), warnings, importLocation);
2799 }
else if (scheme ==
"qrc"_L1) {
2800 auto warnings = importFromQrc(
":"_L1 + url.path(), prefix, importLocation);
2801 processImportWarnings(
"URL \"%1\""_L1.arg(url.path()), warnings, importLocation);
2804 m_logger->log(
"Unknown import syntax. Imports can be paths, qrc urls or file urls"_L1,
2805 qmlImport, import->firstSourceLocation());
2809 const QString path = buildName(import->importUri);
2811 QStringList staticModulesProvided;
2813 auto imported = m_importer->importModule(
2814 path, quint8(QQmlJS::PrecedenceValues::Default), prefix,
2815 import->version ? import->version->version : QTypeRevision(), &staticModulesProvided);
2816 m_importer->registerVersionedImports(imported);
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))
2825 addStaticImportWithLocation(path, import->firstSourceLocation(), path != staticModule);
2828 processImportWarnings(
2829 QStringLiteral(
"module \"%1\"").arg(path), warnings, import->firstSourceLocation());
2833#if QT_VERSION >= QT_VERSION_CHECK(6
, 6
, 0
)
2835void handlePragmaValues(QQmlJS::AST::UiPragma *pragma, F &&assign)
2837 for (
const QQmlJS::AST::UiPragmaValueList *v = pragma->values; v; v = v->next)
2842void handlePragmaValues(QQmlJS::AST::UiPragma *pragma, F &&assign)
2844 assign(pragma->value);
2848bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiPragma *pragma)
2850 if (pragma->name == u"Strict"_s) {
2855 if (!m_logger->wasCategoryChanged(qmlCompiler))
2856 m_logger->setCategorySeverity(qmlCompiler, QQmlJS::WarningSeverity::Warning);
2857 }
else if (pragma->name == u"ComponentBehavior") {
2858 handlePragmaValues(pragma, [
this, pragma](QStringView value) {
2859 if (value == u"Bound") {
2860 m_scopesById.setComponentsAreBound(
true);
2861 }
else if (value == u"Unbound") {
2862 m_scopesById.setComponentsAreBound(
false);
2864 m_logger->log(u"Unknown argument \"%1\" to pragma ComponentBehavior"_s.arg(value),
2865 qmlSyntax, pragma->firstSourceLocation());
2868 }
else if (pragma->name == u"FunctionSignatureBehavior") {
2869 handlePragmaValues(pragma, [
this, pragma](QStringView value) {
2870 if (value == u"Enforced") {
2871 m_scopesById.setSignaturesAreEnforced(
true);
2872 }
else if (value == u"Ignored") {
2873 m_scopesById.setSignaturesAreEnforced(
false);
2876 u"Unknown argument \"%1\" to pragma FunctionSignatureBehavior"_s.arg(value),
2877 qmlSyntax, pragma->firstSourceLocation());
2880 }
else if (pragma->name == u"ValueTypeBehavior") {
2881 handlePragmaValues(pragma, [
this, pragma](QStringView value) {
2882 if (value == u"Copy") {
2884 }
else if (value == u"Reference") {
2886 }
else if (value == u"Addressable") {
2887 m_scopesById.setValueTypesAreAddressable(
true);
2888 }
else if (value == u"Inaddressable") {
2889 m_scopesById.setValueTypesAreAddressable(
false);
2890 }
else if (value == u"Assertable") {
2891 m_scopesById.setValueTypesAreAssertable(
true);
2892 }
else if (value == u"Inassertable") {
2893 m_scopesById.setValueTypesAreAssertable(
false);
2895 m_logger->log(u"Unknown argument \"%1\" to pragma ValueTypeBehavior"_s.arg(value),
2896 qmlSyntax, pragma->firstSourceLocation());
2904void QQmlJSImportVisitor::throwRecursionDepthError()
2906 m_logger->log(QStringLiteral(
"Maximum statement or expression depth exceeded"),
2907 qmlRecursionDepthErrors, QQmlJS::SourceLocation());
2910bool QQmlJSImportVisitor::visit(QQmlJS::AST::ClassDeclaration *ast)
2912 enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, ast->name.toString(),
2913 ast->firstSourceLocation());
2917void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ClassDeclaration *)
2922bool QQmlJSImportVisitor::visit(QQmlJS::AST::ForStatement *ast)
2924 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"forloop"),
2925 ast->firstSourceLocation());
2929void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ForStatement *)
2934bool QQmlJSImportVisitor::visit(QQmlJS::AST::ForEachStatement *ast)
2936 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"foreachloop"),
2937 ast->firstSourceLocation());
2941void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ForEachStatement *)
2946bool QQmlJSImportVisitor::visit(QQmlJS::AST::Block *ast)
2948 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"block"),
2949 ast->firstSourceLocation());
2951 if (m_pendingSignalHandler.isValid())
2952 flushPendingSignalParameters();
2957void QQmlJSImportVisitor::endVisit(QQmlJS::AST::Block *)
2962bool QQmlJSImportVisitor::visit(QQmlJS::AST::CaseBlock *ast)
2964 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"case"),
2965 ast->firstSourceLocation());
2969void QQmlJSImportVisitor::endVisit(QQmlJS::AST::CaseBlock *)
2974bool QQmlJSImportVisitor::visit(QQmlJS::AST::Catch *catchStatement)
2976 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"catch"),
2977 catchStatement->firstSourceLocation());
2981void QQmlJSImportVisitor::endVisit(QQmlJS::AST::Catch *)
2986bool QQmlJSImportVisitor::visit(QQmlJS::AST::WithStatement *ast)
2988 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"with"),
2989 ast->firstSourceLocation());
2991 m_logger->log(QStringLiteral(
"with statements are strongly discouraged in QML "
2992 "and might cause false positives when analysing unqualified "
2994 qmlWith, ast->firstSourceLocation());
2999void QQmlJSImportVisitor::endVisit(QQmlJS::AST::WithStatement *)
3004bool QQmlJSImportVisitor::visit(QQmlJS::AST::FormalParameterList *fpl)
3006 const auto &boundedNames = fpl->boundNames();
3007 for (
auto const &boundName : boundedNames) {
3009 std::optional<QString> typeName;
3010 if (TypeAnnotation *annotation = boundName.typeAnnotation.data())
3011 if (Type *type = annotation->type)
3012 typeName = type->toString();
3013 safeInsertJSIdentifier(m_currentScope, boundName.id,
3014 { QQmlJSScope::JavaScriptIdentifier::Parameter,
3015 boundName.location, typeName,
false });
3020void QQmlJSImportVisitor::createAttachedAndGroupedScopes(UiQualifiedId *propertyName)
3022 bool needsResolution =
false;
3023 int scopesEnteredCounter = 0;
3025 for (
auto group = propertyName; group->next; group = group->next) {
3026 const QString idName = group->name.toString();
3028 if (idName.isEmpty())
3031 if (group == propertyName && isImportPrefix(idName)) {
3032 prefix = idName + u'.';
3036 const auto scopeKind = idName.front().isUpper() ? QQmlSA::ScopeType::AttachedPropertyScope
3037 : QQmlSA::ScopeType::GroupedPropertyScope;
3040 enterEnvironmentNonUnique(scopeKind, prefix + idName, group->firstSourceLocation());
3042 m_bindings.append(createNonUniqueScopeBinding(m_currentScope, prefix + idName,
3043 group->firstSourceLocation()));
3045 ++scopesEnteredCounter;
3046 needsResolution = needsResolution || !exists;
3051 for (
int i=0; i < scopesEnteredCounter; ++i) {
3056 if (needsResolution) {
3057 QQmlJSScope::resolveTypes(m_currentScope, m_rootScopeImports.contextualTypes(),
3062bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiObjectBinding *uiob)
3066 Q_ASSERT(uiob->qualifiedTypeNameId);
3068 const QString typeName = buildName(uiob->qualifiedTypeNameId);
3069 if (typeName.front().isLower() && typeName.contains(u'.')) {
3070 logLowerCaseImport(typeName, uiob->qualifiedTypeNameId->identifierToken, m_logger);
3073 createAttachedAndGroupedScopes(uiob->qualifiedId);
3075 enterEnvironment(QQmlSA::ScopeType::QMLScope, typeName,
3076 uiob->qualifiedTypeNameId->identifierToken);
3078 m_qmlTypes.append(m_currentScope);
3079 m_objectBindingScopes << m_currentScope;
3083int QQmlJSImportVisitor::openAttachedAndGroupedScopes(UiQualifiedId *propertyName)
3086 int scopesEnteredCounter = 0;
3087 auto group = propertyName;
3088 for (; group->next; group = group->next) {
3089 const QString idName = group->name.toString();
3091 if (idName.isEmpty())
3094 if (group == propertyName && isImportPrefix(idName)) {
3095 prefix = idName + u'.';
3099 const auto scopeKind = idName.front().isUpper() ? QQmlSA::ScopeType::AttachedPropertyScope
3100 : QQmlSA::ScopeType::GroupedPropertyScope;
3102 [[maybe_unused]]
bool exists =
3103 enterEnvironmentNonUnique(scopeKind, prefix + idName, group->firstSourceLocation());
3105 scopesEnteredCounter++;
3109 return scopesEnteredCounter;
3112void QQmlJSImportVisitor::endVisit(QQmlJS::AST::UiObjectBinding *uiob)
3114 QQmlJSScope::resolveTypes(m_currentScope, m_rootScopeImports.contextualTypes(), usedTypes());
3116 const QQmlJSScope::Ptr childScope = m_currentScope;
3119 const int scopesEnteredCounter = openAttachedAndGroupedScopes(uiob->qualifiedId);
3124 auto group = uiob->qualifiedId;
3125 for (; group->next; group = group->next) { }
3126 const QString propertyName = group->name.toString();
3128 if (m_currentScope->isNameDeferred(propertyName)) {
3129 bool foundIds =
false;
3130 QList<QQmlJSScope::ConstPtr> childScopes { childScope };
3132 while (!childScopes.isEmpty()) {
3133 const QQmlJSScope::ConstPtr scope = childScopes.takeFirst();
3134 m_scopesById.possibleIds(
3135 scope, scope, QQmlJSScopesByIdOption::Default,
3136 [&](
const QString &id, QQmlJSScopesById::Confidence confidence) {
3139 Q_UNUSED(confidence);
3141 return QQmlJSScopesById::CallbackResult::StopSearch;
3144 childScopes << scope->childScopes();
3149 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
3151 qmlDeferredPropertyId, uiob->firstSourceLocation());
3155 if (checkCustomParser(m_currentScope)) {
3159 m_pendingPropertyObjectBindings
3160 << PendingPropertyObjectBinding { m_currentScope, childScope, propertyName,
3161 uiob->firstSourceLocation(), uiob->hasOnToken };
3163 QQmlJSMetaPropertyBinding binding(uiob->firstSourceLocation(), propertyName);
3164 if (uiob->hasOnToken) {
3165 if (childScope->hasInterface(u"QQmlPropertyValueInterceptor"_s)) {
3166 binding.setInterceptor(QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope),
3167 QQmlJSScope::ConstPtr(childScope));
3169 binding.setValueSource(QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope),
3170 QQmlJSScope::ConstPtr(childScope));
3173 binding.setObject(QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope),
3174 QQmlJSScope::ConstPtr(childScope));
3176 m_bindings.append(UnfinishedBinding { m_currentScope, [=]() {
return binding; } });
3179 for (
int i = 0; i < scopesEnteredCounter; ++i)
3183bool QQmlJSImportVisitor::visit(ExportDeclaration *)
3185 Q_ASSERT(rootScopeIsValid());
3186 Q_ASSERT(m_exportedRootScope != m_globalScope);
3187 Q_ASSERT(m_currentScope == m_globalScope);
3188 m_currentScope = m_exportedRootScope;
3192void QQmlJSImportVisitor::endVisit(ExportDeclaration *)
3194 Q_ASSERT(rootScopeIsValid());
3195 m_currentScope = m_exportedRootScope->parentScope();
3196 Q_ASSERT(m_currentScope == m_globalScope);
3199bool QQmlJSImportVisitor::visit(ESModule *module)
3201 Q_ASSERT(!rootScopeIsValid());
3202 enterRootScope(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral(
"module"),
3203 module->firstSourceLocation());
3204 m_currentScope->setIsScript(
true);
3205 importBaseModules();
3210void QQmlJSImportVisitor::endVisit(ESModule *)
3212 QQmlJSScope::resolveTypes(m_exportedRootScope, m_rootScopeImports.contextualTypes(),
3216bool QQmlJSImportVisitor::visit(Program *program)
3218 Q_ASSERT(m_globalScope == m_currentScope);
3219 Q_ASSERT(!rootScopeIsValid());
3220 enterRootScope(QQmlSA::ScopeType::JSFunctionScope, u"script"_s, program->firstSourceLocation());
3221 m_exportedRootScope->setIsScript(
true);
3222 importBaseModules();
3226void QQmlJSImportVisitor::endVisit(Program *)
3228 QQmlJSScope::resolveTypes(m_exportedRootScope, m_rootScopeImports.contextualTypes(),
3232bool QQmlJSImportVisitor::visit(QQmlJS::AST::PatternElement *element)
3235 if (element->isVariableDeclaration()) {
3236 QQmlJS::AST::BoundNames names;
3237 element->boundNames(&names);
3238 for (
const auto &name : std::as_const(names)) {
3239 std::optional<QString> typeName;
3240 if (TypeAnnotation *annotation = name.typeAnnotation.data())
3241 if (Type *type = annotation->type)
3242 typeName = type->toString();
3243 using Kind = QQmlJSScope::JavaScriptIdentifier::Kind;
3244 const Kind kind = (element->scope == QQmlJS::AST::VariableScope::Var)
3245 ? Kind::FunctionScoped
3246 : Kind::LexicalScoped;
3247 const QString variableName = name.id;
3248 if (kind == Kind::LexicalScoped) {
3249 const QQmlJS::SourceLocation location = element->firstSourceLocation();
3250 if (
auto previousDeclaration = m_currentScope->ownJSIdentifier(variableName)) {
3251 m_logger->log(
"Identifier '%1' has already been declared"_L1.arg(variableName), qmlSyntax,
3253 m_logger->log(
"Note: previous declaration of '%1' here"_L1.arg(variableName), qmlSyntax,
3254 previousDeclaration->location);
3257 const bool isConstVariable = element->scope == QQmlJS::AST::VariableScope::Const;
3258 const bool couldInsert = safeInsertJSIdentifier(m_currentScope,
3260 { (element->scope == QQmlJS::AST::VariableScope::Var)
3261 ? QQmlJSScope::JavaScriptIdentifier::FunctionScoped
3262 : QQmlJSScope::JavaScriptIdentifier::LexicalScoped,
3263 name.location, typeName,