Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qqmljsimportvisitor.cpp
Go to the documentation of this file.
1// Copyright (C) 2019 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
3// Qt-Security score:significant
4
9
10#include <QtCore/qdir.h>
11#include <QtCore/qqueue.h>
12#include <QtCore/qscopedvaluerollback.h>
13#include <QtCore/qpoint.h>
14#include <QtCore/qrect.h>
15#include <QtCore/qsize.h>
16
17#include <QtQml/private/qqmlsignalnames_p.h>
18#include <QtQml/private/qv4codegen_p.h>
19#include <QtQml/private/qqmlstringconverters_p.h>
20#include <QtQml/private/qqmlirbuilder_p.h>
21#include "qqmljsscope_p.h"
22#include "qqmljsutils_p.h"
25
26#include <QtCore/qtyperevision.h>
27
28#include <algorithm>
29#include <limits>
30#include <optional>
31#include <variant>
32
33QT_BEGIN_NAMESPACE
34
35using namespace Qt::StringLiterals;
36
37using namespace QQmlJS::AST;
38
40 = "was not found."_L1;
41
42/*!
43 \internal
44 Returns if assigning \a assignedType to \a property would require an
45 implicit component wrapping.
46 */
48 const QQmlJSScope::ConstPtr &assignedType)
49{
50 // See QQmlComponentAndAliasResolver::findAndRegisterImplicitComponents()
51 // for the logic in qqmltypecompiler
52
53 // Note: unlike findAndRegisterImplicitComponents() we do not check whether
54 // the property type is *derived* from QQmlComponent at some point because
55 // this is actually meaningless (and in the case of QQmlComponent::create()
56 // gets rejected in QQmlPropertyValidator): if the type is not a
57 // QQmlComponent, we have a type mismatch because of assigning a Component
58 // object to a non-Component property
59 const bool propertyVerdict = property.type()->internalName() == u"QQmlComponent";
60
61 const bool assignedTypeVerdict = [&assignedType]() {
62 // Note: nonCompositeBaseType covers the case when assignedType itself
63 // is non-composite
64 auto cppBase = QQmlJSScope::nonCompositeBaseType(assignedType);
65 Q_ASSERT(cppBase); // any QML type has (or must have) a C++ base type
66
67 // See isUsableComponent() in qqmltypecompiler.cpp: along with checking
68 // whether a type has a QQmlComponent static meta object (which we
69 // substitute here with checking the first non-composite base for being
70 // a QQmlComponent), it also excludes QQmlAbstractDelegateComponent
71 // subclasses from implicit wrapping
72 if (cppBase->internalName() == u"QQmlComponent")
73 return false;
74 for (; cppBase; cppBase = cppBase->baseType()) {
75 if (cppBase->internalName() == u"QQmlAbstractDelegateComponent")
76 return false;
77 }
78 return true;
79 }();
80
81 return propertyVerdict && assignedTypeVerdict;
82}
83
84/*!
85 \internal
86 A guarded version of insertJSIdentifier. If the scope is a QML scope,
87 it will log a syntax error instead.
88 Returns true if insertion was successful, otherwise false
89 */
90bool QQmlJSImportVisitor::safeInsertJSIdentifier(QQmlJSScope::Ptr &scope, const QString &name,
91 const QQmlJSScope::JavaScriptIdentifier &identifier)
93 /* The grammar currently allows putting a variable declaration into a UiObjectMember
94 and we only complain about it in the IRBbuilder. It is unclear whether we should change
95 the grammar, as the linter would need to handle invalid programs anyway, so we'd need
96 to add some recovery rule to the grammar in any case.
97 We use this method instead to avoid an assertion in insertJSIdentifier
98 */
99 if (scope->scopeType() == QQmlSA::ScopeType::QMLScope)
100 return false;
101 scope->insertJSIdentifier(name, identifier);
102 return true;
105/*!
106 \internal
107 Sets the name of \a scope to \a name based on \a type.
108*/
109void QQmlJSImportVisitor::setScopeName(QQmlJSScope::Ptr &scope, QQmlJSScope::ScopeType type,
110 const QString &name)
111{
112 Q_ASSERT(scope);
113 switch (type) {
114 case QQmlSA::ScopeType::GroupedPropertyScope:
115 scope->setInternalName(name);
116 return;
117 case QQmlSA::ScopeType::AttachedPropertyScope:
118 scope->setInternalName(name);
119 scope->setBaseTypeName(name);
120 QQmlJSScope::resolveTypes(scope, m_rootScopeImports.contextualTypes(), usedTypes());
121 return;
122 case QQmlSA::ScopeType::QMLScope:
123 scope->setBaseTypeName(name);
124 QQmlJSScope::resolveTypes(scope, m_rootScopeImports.contextualTypes(), usedTypes());
125 return;
126 case QQmlSA::ScopeType::JSFunctionScope:
127 case QQmlSA::ScopeType::BindingFunctionScope:
128 case QQmlSA::ScopeType::SignalHandlerFunctionScope:
129 case QQmlSA::ScopeType::JSLexicalScope:
130 case QQmlSA::ScopeType::EnumScope:
131 scope->setBaseTypeName(name);
132 return;
133 };
136template<typename Node>
137QString buildName(const Node *node)
139 QString result;
140 for (const Node *segment = node; segment; segment = segment->next) {
141 if (!result.isEmpty())
142 result += u'.';
143 result += segment->name;
145 return result;
147
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),
155 m_logger(logger),
156 m_rootScopeImports(QQmlJS::ContextualTypes(
157 QQmlJS::ContextualTypes::QML, { }, { },
158 importer->builtinInternalNames().contextualTypes().arrayType()),
159 { })
160{
161 Q_ASSERT(logger); // must be valid
162 Q_ASSERT(importer); // must be valid
163
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);
168
169 /* FIXME:
170 we create a "local global object" – this prevents any modification of the actual global object;
171 That's necessary because scopes track child scopes, and we don't want to do any shared modifications.
172 However, if we were to allow that the global object doesn't track the child scopes, we could move
173 the global object scope into the type resolver instead.
174 */
175 auto globalScope = QQmlJSScope::create();
176 globalScope->setInternalName(u"global"_s);
177 globalScope->setScopeType(QQmlSA::ScopeType::JSFunctionScope);
178
179 QQmlJSScope::JavaScriptIdentifier globalJavaScript = {
180 QQmlJSScope::JavaScriptIdentifier::LexicalScoped, QQmlJS::SourceLocation(), std::nullopt,
181 true
182 };
183
184 QV4::Compiler::Codegen::forEachGlobalName([&](QLatin1StringView globalName) {
185 globalScope->insertJSIdentifier(globalName, globalJavaScript);
186 });
187
188 m_globalScope = globalScope;
189 m_currentScope = globalScope;
190}
191
192QQmlJSImportVisitor::~QQmlJSImportVisitor() = default;
193
194void QQmlJSImportVisitor::populateCurrentScope(
195 QQmlJSScope::ScopeType type, const QString &name, const QQmlJS::SourceLocation &location)
196{
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);
203}
204
205void QQmlJSImportVisitor::enterRootScope(QQmlJSScope::ScopeType type, const QString &name, const QQmlJS::SourceLocation &location)
206{
207 Q_ASSERT(m_currentScope == m_globalScope);
208 QQmlJSScope::reparent(m_currentScope, m_exportedRootScope);
209 m_currentScope = m_exportedRootScope;
210 populateCurrentScope(type, name, location);
211}
212
213void QQmlJSImportVisitor::enterEnvironment(QQmlJSScope::ScopeType type, const QString &name,
214 const QQmlJS::SourceLocation &location)
215{
216 QQmlJSScope::Ptr newScope = QQmlJSScope::create();
217 QQmlJSScope::reparent(m_currentScope, newScope);
218 m_currentScope = std::move(newScope);
219 populateCurrentScope(type, name, location);
220}
221
222bool QQmlJSImportVisitor::enterEnvironmentNonUnique(QQmlJSScope::ScopeType type,
223 const QString &name,
224 const QQmlJS::SourceLocation &location)
225{
226 Q_ASSERT(type == QQmlSA::ScopeType::GroupedPropertyScope
227 || type == QQmlSA::ScopeType::AttachedPropertyScope);
228
229 const auto pred = [&](const QQmlJSScope::ConstPtr &s) {
230 // it's either attached or grouped property, so use internalName()
231 // directly. see setScopeName() for details
232 return s->internalName() == name;
233 };
234 const auto scopes = m_currentScope->childScopes();
235 // TODO: linear search. might want to make childScopes() a set/hash-set and
236 // use faster algorithm here
237 auto it = std::find_if(scopes.begin(), scopes.end(), pred);
238 if (it == scopes.end()) {
239 // create and enter new scope
240 enterEnvironment(type, name, location);
241 return false;
242 }
243 // enter found scope
244 m_scopesByIrLocation.insert({ location.startLine, location.startColumn }, *it);
245 m_currentScope = *it;
246 return true;
247}
248
249void QQmlJSImportVisitor::leaveEnvironment()
250{
251 m_currentScope = m_currentScope->parentScope();
252}
253
254void QQmlJSImportVisitor::warnUnresolvedType(const QQmlJSScope::ConstPtr &type) const
255{
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());
259}
260
261void QQmlJSImportVisitor::warnMissingPropertyForBinding(
262 const QString &property, const QQmlJS::SourceLocation &location,
263 const std::optional<QQmlJSFixSuggestion> &fixSuggestion)
264{
265 m_logger->log(QStringLiteral("Could not find property \"%1\".").arg(property),
266 qmlMissingProperty, location, true, true, fixSuggestion);
267}
268
269static bool mayBeUnresolvedGroupedProperty(const QQmlJSScope::ConstPtr &scope)
270{
271 return scope->scopeType() == QQmlSA::ScopeType::GroupedPropertyScope && !scope->baseType();
272}
273
274QQmlJSImportVisitor::AliasPropertyResolution
275QQmlJSImportVisitor::resolveAliasProperty(const QQmlJSScope::Ptr &object,
276 const QQmlJSMetaProperty &property)
277{
278 AliasPropertyResolution result = Resolved;
279 QStringList components = property.aliasExpression().split(u'.');
280 QQmlJSMetaProperty targetProperty;
281
282 bool foundProperty = false;
283 bool hasWarnedAlready = false;
284
285 // The first component has to be an ID. Find the object it refers to.
286 QQmlJSScope::ConstPtr type = m_scopesById.scope(components.takeFirst(), object);
287 QQmlJSScope::ConstPtr typeScope;
288 if (!type.isNull()) {
289 foundProperty = true;
290
291 // Any further components are nested properties of that object.
292 // Technically we can only resolve a limited depth in the engine, but the rules
293 // on that are fuzzy and subject to change. Let's ignore it for now.
294 // If the target is itself an alias and has not been resolved, re-queue the object
295 // and try again later.
296 while (type && !components.isEmpty()) {
297 const QString name = components.takeFirst();
298
299 if (!checkTypeResolved(type)) {
300 hasWarnedAlready = true;
301 type = { };
302 break;
303 }
304
305 if (!type->hasProperty(name)) {
306 foundProperty = false;
307 type = { };
308 break;
309 }
310
311 const auto target = type->property(name);
312 if (!target.type()) {
313 if (target.isAlias()) {
314 result = NeedsRequeue;
315 } else {
316 // We already warned about the missing type in the property definition if
317 // the type is defined in this QML file.
318 hasWarnedAlready = QQmlJSScope::ownerOfProperty(type, name).scope->filePath()
319 == m_exportedRootScope->filePath();
320 }
321 }
322 typeScope = type;
323 type = target.type();
324 targetProperty = target;
325 }
326 }
327
328 if (type.isNull()) {
329 if (result == NeedsRequeue)
330 return result;
331 if (!hasWarnedAlready) {
332 if (foundProperty) {
333 m_logger->log(QStringLiteral("Cannot deduce type of alias \"%1\"")
334 .arg(property.propertyName()),
335 qmlMissingType, property.sourceLocation());
336 } else {
337 m_logger->log(
338 QStringLiteral("Cannot resolve alias \"%1\"").arg(property.propertyName()),
339 qmlUnresolvedAlias, property.sourceLocation());
340 }
341 }
342
343 Q_ASSERT(property.index() >= 0); // this property is already in object
344 object->addOwnProperty(property);
345
346 } else {
347 QQmlJSMetaProperty newProperty = property;
348 newProperty.setType(type);
349 // Copy additional property information from target
350 newProperty.setIsList(targetProperty.isList());
351 newProperty.setIsWritable(targetProperty.isWritable());
352 newProperty.setIsFinal(targetProperty.isFinal());
353 newProperty.setIsPointer(targetProperty.isPointer());
354
355 const bool onlyId = !property.aliasExpression().contains(u'.');
356 if (onlyId) {
357 newProperty.setAliasTargetScope(type);
358 newProperty.setAliasTargetName(QStringLiteral("id-only-alias"));
359 } else {
360 const auto &ownerScope =
361 QQmlJSScope::ownerOfProperty(typeScope, targetProperty.propertyName()).scope;
362 newProperty.setAliasTargetScope(ownerScope);
363 newProperty.setAliasTargetName(targetProperty.propertyName());
364 }
365
366 if (const QString internalName = type->internalName(); !internalName.isEmpty())
367 newProperty.setTypeName(internalName);
368
369 Q_ASSERT(newProperty.index() >= 0); // this property is already in object
370 object->addOwnProperty(newProperty);
371 m_aliasDefinitions.append({ object, property.propertyName() });
372 }
373 return result;
374}
375
376void QQmlJSImportVisitor::resolveAliases()
377{
378 QQueue<QQmlJSScope::Ptr> objects;
379 objects.enqueue(m_exportedRootScope);
380
381 qsizetype lastRequeueLength = std::numeric_limits<qsizetype>::max();
382 QQueue<QQmlJSScope::Ptr> requeue;
383 QDuplicateTracker<std::pair<QQmlJSScope::Ptr, QQmlJSMetaProperty>> alreadyResolvedAliases;
384
385 bool processingRequeue = false;
386
387 while (!objects.isEmpty()) {
388 const QQmlJSScope::Ptr object = objects.dequeue();
389 const auto properties = object->ownProperties();
390
391 bool doRequeue = false;
392 for (const auto &property : properties) {
393 if (!property.isAlias() || !property.type().isNull()
394 || alreadyResolvedAliases.contains({ object, property })) {
395 continue;
396 }
397 if (resolveAliasProperty(object, property) == NeedsRequeue) {
398 doRequeue = true;
399 } else {
400 Q_UNUSED(alreadyResolvedAliases.hasSeen({ object, property }));
401 }
402 }
403
404 if (!processingRequeue) {
405 const auto childScopes = object->childScopes();
406 for (const auto &childScope : childScopes)
407 objects.enqueue(childScope);
408 }
409
410 if (doRequeue)
411 requeue.enqueue(object);
412
413 if (objects.isEmpty() && requeue.size() < lastRequeueLength) {
414 processingRequeue = true;
415 lastRequeueLength = requeue.size();
416 objects.swap(requeue);
417 }
418 }
419}
420
421void QQmlJSImportVisitor::resolveGroupedProperties()
422{
423 QQueue<QQmlJSScope::Ptr> objects;
424 objects.enqueue(m_exportedRootScope);
425
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(),
437 usedTypes());
438 }
439 } else if (const QQmlJSScope::ConstPtr propType = object->property(name).type()) {
440 QQmlJSScope::resolveGroup(childScope, propType,
441 m_rootScopeImports.contextualTypes(), usedTypes());
442 }
443 }
444 objects.enqueue(childScope);
445 }
446 }
447}
448
449QString QQmlJSImportVisitor::implicitImportDirectory(const QString &localFile,
450 const QQmlJSResourceFileMapper *mapper)
451{
452 if (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(":/");
460 }
461 }
462
463 return QFileInfo(localFile).canonicalPath() + u'/';
464}
465
466void QQmlJSImportVisitor::processImportWarnings(
467 const QString &what, const QList<QQmlJS::DiagnosticMessage> &warnings,
468 const QQmlJS::SourceLocation &srcLocation)
469{
470 if (warnings.isEmpty())
471 return;
472
473 QList<QQmlJS::DiagnosticMessage> importWarnings = warnings;
474
475 // if we have file selector warnings, they are marked by a lower priority
476 auto fileSelectorWarningsIt =
477 std::partition(importWarnings.begin(), importWarnings.end(),
478 [](const QQmlJS::DiagnosticMessage &message) {
479 return message.msgType() != QtMsgType::QtInfoMsg;
480 });
481 if (fileSelectorWarningsIt != importWarnings.end()) {
482 m_logger->log(QStringLiteral("Warnings occurred while importing %1:").arg(what), qmlImportFileSelector,
483 srcLocation);
484 m_logger->processMessages(QSpan(fileSelectorWarningsIt, importWarnings.end()),
485 qmlImportFileSelector, srcLocation);
486 }
487
488 if (fileSelectorWarningsIt == importWarnings.begin())
489 return;
490
491 m_logger->log(QStringLiteral("Warnings occurred while importing %1:").arg(what), qmlImport,
492 srcLocation);
493 m_logger->processMessages(QSpan(importWarnings.begin(), fileSelectorWarningsIt), qmlImport,
494 srcLocation);
495}
496
497void QQmlJSImportVisitor::importBaseModules()
498{
499 Q_ASSERT(m_rootScopeImports.isEmpty());
500 m_rootScopeImports = m_importer->importHardCodedBuiltins();
501 /* Pass the file's selector along so we have a consistent view on selectors:
502 - If there is a file selector, we only consider non-file-selected files and those
503 using the same selector. Reality is more complicated, but this should be enoguh
504 for most projects.
505 - If the current file is not using a file selector, we consider everything
506 */
507 m_rootScopeImports.setCurrentFileSelector(
508 QQmlJSUtils::fileSelectorFor(m_exportedRootScope));
509
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);
514
515 if (!m_qmldirFiles.isEmpty())
516 m_rootScopeImports.addWarnings(m_importer->importQmldirs(m_qmldirFiles));
517
518 // Pulling in the modules and neighboring qml files of the qmltypes we're trying to lint is not
519 // something we need to do.
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));
525
526 // Import all possible resource directories the file may belong to.
527 // This is somewhat fuzzy, but if you're mapping the same file to multiple resource
528 // locations, you're on your own anyway.
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('/'));
534 if (lastSlash == -1)
535 continue;
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));
541 }
542 }
543 }
544
545 processImportWarnings(QStringLiteral("base modules"), m_rootScopeImports.warnings());
546}
547
548bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiProgram *)
549{
550 importBaseModules();
551 // if the current file is a QML file, make it available, too
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 });
557 }
558
559 return true;
560}
561
562void QQmlJSImportVisitor::endVisit(UiProgram *)
563{
564 for (const auto &scope : std::as_const(m_objectBindingScopes)) {
565 breakInheritanceCycles(scope);
566 checkDeprecation(scope);
567 checkForComponentTypeWithProperties(scope);
568 }
569
570 for (const auto &scope : std::as_const(m_objectDefinitionScopes)) {
571 if (m_pendingDefaultProperties.contains(scope))
572 continue; // We're going to check this one below.
573 breakInheritanceCycles(scope);
574 checkDeprecation(scope);
575 checkForComponentTypeWithProperties(scope);
576 }
577
578 const auto &keys = m_pendingDefaultProperties.keys();
579 for (const auto &scope : keys) {
580 breakInheritanceCycles(scope);
581 checkDeprecation(scope);
582 checkForComponentTypeWithProperties(scope);
583 }
584
585 resolveAliases();
586 resolveGroupedProperties();
587
588 checkGroupedAndAttachedScopes();
589
590 setAllBindings();
591 processDefaultProperties();
592 processPropertyTypes();
593 processMethodTypes();
594 processPropertyBindings();
595 processPropertyBindingObjects();
596 checkRequiredProperties();
597
598 populateRuntimeFunctionIndicesForDocument();
599}
600
601static QQmlJSAnnotation::Value bindingToVariant(QQmlJS::AST::Statement *statement)
602{
603 ExpressionStatement *expr = cast<ExpressionStatement *>(statement);
604
605 if (!statement || !expr->expression)
606 return {};
607
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;
613 default:
614 return {};
615 }
616}
617
618QList<QQmlJSAnnotation> QQmlJSImportVisitor::parseAnnotations(QQmlJS::AST::UiAnnotationList *list)
619{
620
621 QList<QQmlJSAnnotation> annotationList;
622
623 for (UiAnnotationList *item = list; item != nullptr; item = item->next) {
624 UiAnnotation *annotation = item->annotation;
625
626 QQmlJSAnnotation qqmljsAnnotation;
627 qqmljsAnnotation.name = buildName(annotation->qualifiedTypeNameId);
628
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);
635 break;
636 }
637 default:
638 // We ignore all the other information contained in the annotation
639 break;
640 }
641 }
642
643 annotationList.append(qqmljsAnnotation);
644 }
645
646 return annotationList;
647}
648
650 const QQmlJS::SourceLocation &first, const QQmlJS::SourceLocation &second,
651 const QList<QQmlJS::SourceLocation> &groupedObjectDefinitions)
652{
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;
661 }
662 return innermostOffset;
663 };
664 return innermostDefinitionOffset(first) == innermostDefinitionOffset(second);
665}
666
667void QQmlJSImportVisitor::setAllBindings()
668{
669 using Key = std::pair<QQmlJSScope::ConstPtr, QString>;
670 QHash<Key, QQmlJS::SourceLocation> foundBindings;
671
672 for (auto it = m_bindings.cbegin(); it != m_bindings.cend(); ++it) {
673 // ensure the scope is resolved. If not, produce a warning.
674 const QQmlJSScope::Ptr type = it->owner;
675 if (!checkTypeResolved(type))
676 continue;
677
678 // create() expects that the types are fully resolved
679 // TODO: Ideally, this extra isFullyResolved shouldn't be needed.
680 // and should handled inside checkTypeResolved above but that function
681 // also contains checkCustomParser(type) for whatever reason.
682 // So if a type is not fully resolved but also has a custom parser,
683 // we would still call it->create without types being fully resolved.
684 if (!type->isFullyResolved())
685 continue;
686 auto binding = it->create();
687 if (!binding.isValid())
688 continue;
689 type->addOwnPropertyBinding(binding, it->specifier);
690
691 // we handle interceptors and value sources in processPropertyBindingObjects()
692 if (binding.hasInterceptor() || binding.hasValueSource())
693 continue;
694 const QString propertyName = binding.propertyName();
695 QQmlJSMetaProperty property = type->property(propertyName);
696
697 /* if we can't tell anything about the property, we don't emit warnings:
698 There might be a custom parser, or the type is unresolvable, but it
699 would be a list property – no reason to flood the user with warnings
700 There should be a warning about the property anyway (unless it's from
701 a custom parser).
702 */
703 if (!property.isValid())
704 continue;
705
706 // list can be bound multiple times
707 if (property.isList())
708 continue;
709
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());
714 continue;
715 }
716
717 const QQmlJS::SourceLocation location = binding.sourceLocation();
718 // IRBuilder only warns on duplicate grouped properties that are in the same
719 // grouped object definition, for example:
720 // font.pixelSize: 42; font.pixelSize: 43
721 // font { pixelSize: 42; pixelSize: 43 }
722 // IRBuilder does not warn for:
723 // font.pixelSize: 42; font { pixelSize: 43; }
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);
729 }
730 m_logger->log("Note: previous binding on '%1' here"_L1.arg(propertyName),
731 qmlDuplicatePropertyBinding, *sourceLocationIt, true, true, {},
732 location.startLine);
733 }
734}
735
736void QQmlJSImportVisitor::processDefaultProperties()
737{
738 for (auto it = m_pendingDefaultProperties.constBegin();
739 it != m_pendingDefaultProperties.constEnd(); ++it) {
740 QQmlJSScope::ConstPtr parentScope = it.key();
741
742 // We can't expect custom parser default properties to be sensible, discard them for now.
743 if (checkCustomParser(parentScope))
744 continue;
745
746 if (!checkTypeResolved(parentScope))
747 continue;
748
749 /* consider:
750 *
751 * QtObject { // <- parentScope
752 * default property var p // (1)
753 * QtObject {} // (2)
754 * }
755 *
756 * `p` (1) is a property of a subtype of QtObject, it couldn't be used
757 * in a property binding (2)
758 */
759 // thus, use a base type of parent scope to detect a default property
760 parentScope = parentScope->baseType();
761
762 const QString defaultPropertyName =
763 parentScope ? parentScope->defaultPropertyName() : QString();
764
765 if (defaultPropertyName.isEmpty()) {
766 // If the parent scope is based on Component it can have any child element
767 // TODO: We should also store these somewhere
768 bool isComponent = false;
769 for (QQmlJSScope::ConstPtr s = parentScope; s; s = s->baseType()) {
770 if (s->internalName() == QStringLiteral("QQmlComponent")) {
771 isComponent = true;
772 break;
773 }
774 }
775
776 if (!isComponent && checkTypeResolved(parentScope)) {
777 m_logger->log(QStringLiteral("Cannot assign to non-existent default property"),
778 qmlMissingProperty, it.value().constFirst()->sourceLocation());
779 }
780
781 continue;
782 }
783
784 const QQmlJSMetaProperty defaultProp = parentScope->property(defaultPropertyName);
785 auto propType = defaultProp.type();
786 const auto handleUnresolvedDefaultProperty = [&](const QQmlJSScope::ConstPtr &) {
787 // Property type is not fully resolved we cannot tell any more than this
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());
792 };
793
794 const auto assignToUnknownProperty = [&]() {
795 // We don't know the property type. It could be QQmlComponent, which would mean that
796 // IDs from the inner scopes are inaccessible.
797 for (const QQmlJSScope::Ptr &scope : std::as_const(*it))
798 scope->setAssignedToUnknownProperty(true);
799 };
800
801 if (propType.isNull()) {
802 if (checkTypeResolved(parentScope)
803 && QQmlJSScope::ownerOfProperty(parentScope, defaultPropertyName).scope->filePath()
804 != m_exportedRootScope->filePath()) {
805 handleUnresolvedDefaultProperty(propType);
806 }
807 assignToUnknownProperty();
808 continue;
809 }
810
811 if (it.value().size() > 1
812 && !defaultProp.isList()
813 && !propType->isListProperty()) {
814 m_logger->log(
815 QStringLiteral("Cannot assign multiple objects to a default non-list property"),
816 qmlNonListProperty, it.value().constFirst()->sourceLocation());
817 }
818
819 if (!checkTypeResolved(propType, handleUnresolvedDefaultProperty)) {
820 assignToUnknownProperty();
821 continue;
822 }
823
824 for (const QQmlJSScope::Ptr &scope : std::as_const(*it)) {
825 if (!checkTypeResolved(scope))
826 continue;
827
828 // Assigning any element to a QQmlComponent property implicitly wraps it into a Component
829 // Check whether the property can be assigned the scope
830 if (propType->canAssign(scope)) {
831 scope->setIsWrappedInImplicitComponent(
832 causesImplicitComponentWrapping(defaultProp, scope));
833 continue;
834 }
835
836 m_logger->log(QStringLiteral("Cannot assign to default property of incompatible type"),
837 qmlIncompatibleType, scope->sourceLocation());
838 }
839 }
840}
841
842void QQmlJSImportVisitor::processPropertyTypes()
843{
844 for (const PendingPropertyType &type : std::as_const(m_pendingPropertyTypes)) {
845 Q_ASSERT(type.scope->hasOwnProperty(type.name));
846
847 auto property = type.scope->ownProperty(type.name);
848
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);
853 } else {
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);
858 }
859 }
860}
861
862void QQmlJSImportVisitor::processMethodTypes()
863{
864 const auto isEnumUsedAsType = [&](QStringView typeName, const QQmlJS::SourceLocation &loc) {
865 if (typeName == "enum"_L1) {
866 // note: we already warned about 'enum' in the parser
867 return true;
868 }
869 const auto split = typeName.tokenize(u'.').toContainer<QVarLengthArray<QStringView, 4>>();
870 if (split.size() != 2)
871 return false;
872
873 const QStringView scopeName = split[0];
874 const QStringView enumName = split[1];
875
876 if (auto scope = QQmlJSScope::findType(scopeName.toString(),
877 m_rootScopeImports.contextualTypes()).scope) {
878 if (scope->enumeration(enumName.toString()).isValid()) {
879 m_logger->log(
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);
882 return true;
883 }
884 }
885 return false;
886 };
887
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]))
894 continue;
895 if (const auto parameterType = QQmlJSScope::findType(
896 parameter->typeName(), m_rootScopeImports.contextualTypes()).scope) {
897 parameter->setType({ parameterType });
898 } else {
899 m_logger->log(
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]);
903 }
904 }
905
906 if (isEnumUsedAsType(it->returnTypeName(), method.locations.last()))
907 continue;
908 if (const auto returnType = QQmlJSScope::findType(
909 it->returnTypeName(), m_rootScopeImports.contextualTypes()).scope) {
910 it->setReturnType({ returnType });
911 } else {
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());
915 }
916 }
917 }
918}
919
920// TODO: We should investigate whether bindings shouldn't resolve this earlier by themselves
921/*!
922\internal
923Resolves \a possiblyGroupedProperty on a type represented by \a scope.
924possiblyGroupedProperty can be either a simple name, or a grouped property ("foo.bar.baz")
925In the latter case, we resolve the "head" to a property, and then continue with the tail on
926the properties' type.
927We don't handle ids here
928 */
929static QQmlJSMetaProperty resolveProperty(const QString &possiblyGroupedProperty, QQmlJSScope::ConstPtr scope)
930{
931 QQmlJSMetaProperty property;
932 for (QStringView propertyName: possiblyGroupedProperty.tokenize(u".")) {
933 property = scope->property(propertyName.toString());
934 if (property.isValid())
935 scope = property.type();
936 else
937 return property;
938 }
939 return property;
940}
941
942void QQmlJSImportVisitor::processPropertyBindingObjects()
943{
944 QSet<std::pair<QQmlJSScope::Ptr, QString>> foundLiterals;
945 {
946 // Note: populating literals here is special, because we do not store
947 // them in m_pendingPropertyObjectBindings, so we have to lookup all
948 // bindings on a property for each scope and see if there are any
949 // literal bindings there. this is safe to do once at the beginning
950 // because this function doesn't add new literal bindings and all
951 // literal bindings must already be added at this point.
952 QSet<std::pair<QQmlJSScope::Ptr, QString>> visited;
953 for (const PendingPropertyObjectBinding &objectBinding :
954 std::as_const(m_pendingPropertyObjectBindings)) {
955 // unique because it's per-scope and per-property
956 const auto uniqueBindingId = std::make_pair(objectBinding.scope, objectBinding.name);
957 if (visited.contains(uniqueBindingId))
958 continue;
959 visited.insert(uniqueBindingId);
960
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);
968 }
969 }
970
971 QSet<std::pair<QQmlJSScope::Ptr, QString>> foundObjects;
972 QSet<std::pair<QQmlJSScope::Ptr, QString>> foundInterceptors;
973 QSet<std::pair<QQmlJSScope::Ptr, QString>> foundValueSources;
974
975 for (const PendingPropertyObjectBinding &objectBinding :
976 std::as_const(m_pendingPropertyObjectBindings)) {
977 const QString propertyName = objectBinding.name;
978 QQmlJSScope::Ptr childScope = objectBinding.childScope;
979
980 const auto assignToUnknownProperty = [&]() {
981 // We don't know the property type. It could be QQmlComponent which would mean
982 // that IDs from the child scope are inaccessible outside of it.
983 childScope->setAssignedToUnknownProperty(true);
984 };
985
986 // guarantees property lookup
987 if (!checkTypeResolved(objectBinding.scope)) {
988 assignToUnknownProperty();
989 continue;
990 }
991
992 QQmlJSMetaProperty property = resolveProperty(propertyName, objectBinding.scope);
993
994 if (!property.isValid()) {
995 warnMissingPropertyForBinding(propertyName, objectBinding.location);
996 continue;
997 }
998 const auto handleUnresolvedProperty = [&](const QQmlJSScope::ConstPtr &) {
999 // Property type is not fully resolved we cannot tell any more than this
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);
1004 };
1005
1006 if (property.type().isNull()) {
1007 assignToUnknownProperty();
1008 if (checkTypeResolved(objectBinding.scope)
1009 && QQmlJSScope::ownerOfProperty(objectBinding.scope, propertyName).scope->filePath()
1010 != m_exportedRootScope->filePath()) {
1011 // If this property was defined in the same QML document then we already warned about it
1012 // somewhere.
1013 handleUnresolvedProperty(property.type());
1014 }
1015 continue;
1016 }
1017
1018 // guarantee that canAssign() can be called
1019 if (!checkTypeResolved(property.type(), handleUnresolvedProperty)) {
1020 assignToUnknownProperty();
1021 continue;
1022 } else if (!checkTypeResolved(childScope)) {
1023 continue;
1024 }
1025
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());
1031 continue;
1032 }
1033
1034 childScope->setIsWrappedInImplicitComponent(
1035 causesImplicitComponentWrapping(property, childScope));
1036
1037 // unique because it's per-scope and per-property
1038 const auto uniqueBindingId = std::make_pair(objectBinding.scope, objectBinding.name);
1039 const QString typeName = QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope);
1040
1041 auto isConditionalBinding = [&]() -> bool {
1042 /* this is a heuristic; we don't want to warn about multiple
1043 mutually exclusive bindings, even if they target the same
1044 property. We don't have a proper way to detect this, so
1045 we check for the presence of some bindings as a hint
1046 */
1047 return childScope->hasOwnPropertyBindings(u"enabled"_s)
1048 || childScope->hasOwnPropertyBindings(u"when"_s)
1049 || childScope->hasOwnPropertyBindings(u"running"_s);
1050 };
1051
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\"")
1057 .arg(propertyName),
1058 qmlDuplicatePropertyBinding, objectBinding.location);
1059 }
1060 } else {
1061 foundInterceptors.insert(uniqueBindingId);
1062 }
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\"")
1067 .arg(propertyName),
1068 qmlDuplicatePropertyBinding, objectBinding.location);
1069 }
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 "
1074 "property \"%1\"")
1075 .arg(propertyName),
1076 qmlDuplicatePropertyBinding, objectBinding.location);
1077 }
1078 } else {
1079 foundValueSources.insert(uniqueBindingId);
1080 }
1081 } else {
1082 m_logger->log(QStringLiteral("On-binding for property \"%1\" has wrong type \"%2\"")
1083 .arg(propertyName, typeName),
1084 qmlIncompatibleType, objectBinding.location);
1085 }
1086 } else {
1087 if (foundValueSources.contains(uniqueBindingId)) {
1088 if (!isConditionalBinding()) {
1089 m_logger->log(
1090 QStringLiteral("Cannot combine value source and binding on property \"%1\"")
1091 .arg(propertyName),
1092 qmlDuplicatePropertyBinding, objectBinding.location);
1093 }
1094 } else {
1095 foundObjects.insert(uniqueBindingId);
1096 }
1097 }
1098 }
1099}
1100
1101static QList<QQmlJSScope::ConstPtr> qmlScopeDescendants(const QQmlJSScope::ConstPtr &scope)
1102{
1103 QList<QQmlJSScope::ConstPtr> descendants;
1104 std::vector<QQmlJSScope::ConstPtr> toVisit;
1105
1106 toVisit.push_back(scope);
1107 while (!toVisit.empty()) {
1108 const QQmlJSScope::ConstPtr s = toVisit.back();
1109 toVisit.pop_back();
1110 if (s->scopeType() == QQmlSA::ScopeType::QMLScope) {
1111 if (s != scope)
1112 descendants << s;
1113
1114 toVisit.insert(toVisit.end(), s->childScopesBegin(), s->childScopesEnd());
1115 }
1116 }
1117
1118 return descendants;
1119}
1120
1121void QQmlJSImportVisitor::populatePropertyAliases()
1122{
1123 for (const auto &alias : std::as_const(m_aliasDefinitions)) {
1124 const auto &[aliasScope, aliasName] = alias;
1125 if (aliasScope.isNull())
1126 continue;
1127
1128 auto property = aliasScope->ownProperty(aliasName);
1129 if (!property.isValid() || !property.aliasTargetScope())
1130 continue;
1131
1132 Property target(property.aliasTargetScope(), property.aliasTargetName());
1133
1134 do {
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);
1139 }
1140}
1141
1142void QQmlJSImportVisitor::checkRequiredProperties()
1143{
1144 for (const auto &required : std::as_const(m_requiredProperties)) {
1145 if (!required.scope->hasProperty(required.name)) {
1146 m_logger->log(
1147 QStringLiteral("Property \"%1\" was marked as required but does not exist.")
1148 .arg(required.name),
1149 qmlRequired, required.location);
1150 }
1151 }
1152
1153 const auto compType = m_rootScopeImports.type(u"Component"_s).scope;
1154 const auto isComponentRoot = [&](const QQmlJSScope::ConstPtr &requiredScope) {
1155 if (requiredScope->isWrappedInImplicitComponent())
1156 return true;
1157 if (const auto s = requiredScope->parentScope(); s && s->baseType() == compType)
1158 return true;
1159 return false;
1160 };
1161
1162 const auto scopeRequiresProperty = [&](const QQmlJSScope::ConstPtr &requiredScope,
1163 const QString &propName,
1164 const QQmlJSScope::ConstPtr &descendant) {
1165 if (!requiredScope->isPropertyLocallyRequired(propName))
1166 return false;
1167
1168 // check if property owners are the same: the owners can be different in case of shadowing.
1169 return QQmlJSScope::ownerOfProperty(requiredScope, propName).scope
1170 == QQmlJSScope::ownerOfProperty(descendant, propName).scope;
1171 };
1172
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())
1178 continue;
1179 const auto &[begin, end] = scope->ownPropertyBindings(propName);
1180 for (auto it = begin; it != end; ++it) {
1181 // attached and grouped bindings should not be considered here
1182 const bool isRelevantBinding = QQmlSA::isRegularBindingType(it->bindingType())
1183 || it->bindingType() == QQmlSA::BindingType::Interceptor
1184 || it->bindingType() == QQmlSA::BindingType::ValueSource;
1185 if (!isRelevantBinding)
1186 continue;
1187 if (QQmlJSScope::ownerOfProperty(scope, propName).scope == owner)
1188 return true;
1189 }
1190 }
1191
1192 return false;
1193 };
1194
1195 const auto requiredUsedInRootAlias = [&](const QQmlJSScope::ConstPtr &requiredScope,
1196 const QString &propName) {
1197 const Property target(requiredScope, propName);
1198 // m_propertyAliases contains all aliases that points to target, either directly or
1199 // indirectly.
1200 const auto allAliasesToTargetIt = m_propertyAliases.constFind(target);
1201 if (allAliasesToTargetIt == m_propertyAliases.constEnd())
1202 return false;
1203
1204 // If one alias is in the file root component, than the required property can be fulfilled
1205 // by the alias when it is instantiated, and we shouldn't warn in the current QML component
1206 // about the unsatisfied required property.
1207 return std::any_of(
1208 allAliasesToTargetIt->constBegin(), allAliasesToTargetIt->constEnd(),
1209 [](const Property &property) { return property.scope->isFileRootComponent(); });
1210 };
1211
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))
1220 return true;
1221 }
1222 }
1223 return false;
1224 };
1225
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)
1233 : u"here"_s;
1234
1235 std::optional<QQmlJSFixSuggestion> suggestion;
1236
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)
1242 : u"here"_s;
1243
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),
1251 requiredScopeName),
1252 sourceScope->sourceLocation()
1253 };
1254 // note: suggestions only accepts qml file paths, and can't open the
1255 // non-absolute paths in QQmlJSScope::filePath of C++ defined types
1256 if (sourceScope->isComposite())
1257 suggestion->setFilename(sourceScope->filePath());
1258 }
1259 } else {
1260 message += " (marked as required by %1)"_L1.arg(requiredScopeName);
1261 }
1262 }
1263
1264 m_logger->log(message, qmlRequired, defScope->sourceLocation(), true, true, suggestion);
1265 };
1266
1267 populatePropertyAliases();
1268
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) {
1273 continue;
1274 }
1275
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)) {
1281 // Ignore inline components of children. Base types need to be always checked for
1282 // required properties, even if they are defined in an inline component.
1283 if (descendant != scope && descendant->isInlineComponent())
1284 continue;
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))
1291 continue;
1292
1293 QQmlJSScope::ConstPtr prevRequiredScope;
1294 for (const QQmlJSScope::ConstPtr &requiredScope : std::as_const(scopesToSearch)) {
1295 // Stop at component boundaries. We don't want to report the same problem
1296 // multiple times.
1297 if (isComponentRoot(requiredScope))
1298 break;
1299
1300 if (!scopeRequiresProperty(requiredScope, propName, descendant)) {
1301 prevRequiredScope = requiredScope;
1302 continue;
1303 }
1304
1305 if (requiredHasBinding(scopesToSearch, descendant, propName))
1306 continue;
1307
1308 if (requiredUsedInRootAlias(requiredScope, propName))
1309 continue;
1310
1311 if (requiredSetThroughAlias(scopesToSearch, requiredScope, propName))
1312 continue;
1313
1314 warn(prevRequiredScope, propName, defScope, requiredScope, descendant);
1315 prevRequiredScope = requiredScope;
1316 }
1317 }
1318 }
1319 }
1320 }
1321}
1322
1323void QQmlJSImportVisitor::processPropertyBindings()
1324{
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()) {
1329 // These warnings do not apply for custom parsers and their children and need to be
1330 // handled on a case by case basis
1331
1332 if (checkCustomParser(scope))
1333 continue;
1334
1335 // TODO: Can this be in a better suited category?
1336 std::optional<QQmlJSFixSuggestion> fixSuggestion;
1337
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;
1344 break;
1345 }
1346 }
1347
1348 if (checkTypeResolved(scope))
1349 warnMissingPropertyForBinding(name, location, fixSuggestion);
1350 continue;
1351 }
1352
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 "
1357 "qmltypes files.")
1358 .arg(name),
1359 qmlMissingType, location);
1360 }
1361
1362 const auto &annotations = property.annotations();
1363
1364 const auto deprecationAnn =
1365 std::find_if(annotations.cbegin(), annotations.cend(),
1366 [](const QQmlJSAnnotation &ann) { return ann.isDeprecation(); });
1367
1368 if (deprecationAnn != annotations.cend()) {
1369 const auto deprecation = deprecationAnn->deprecation();
1370
1371 QString message = QStringLiteral("Binding on deprecated property \"%1\"")
1372 .arg(property.propertyName());
1373
1374 if (!deprecation.reason.isEmpty())
1375 message.append(QStringLiteral(" (Reason: %1)").arg(deprecation.reason));
1376
1377 m_logger->log(message, qmlDeprecated, location);
1378 }
1379 }
1380 }
1381}
1382
1383void QQmlJSImportVisitor::checkSignal(
1384 const QQmlJSScope::ConstPtr &signalScope, const QQmlJS::SourceLocation &location,
1385 const QString &handlerName, const QStringList &handlerParameters)
1386{
1387 const auto signal = QQmlSignalNames::handlerNameToSignalName(handlerName);
1388
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];
1394 };
1395
1396 if (signal.has_value()) {
1397 if (signalScope->hasMethod(*signal)) {
1398 setSignalMethod(signalScope, *signal);
1399 } else if (auto p = QQmlJSUtils::propertyFromChangedHandler(signalScope, handlerName)) {
1400 // we have a change handler of the form "onXChanged" where 'X'
1401 // is a property name
1402
1403 // NB: qqmltypecompiler prefers signal to bindable
1404 if (auto notify = p->notify(); !notify.isEmpty()) {
1405 setSignalMethod(signalScope, notify);
1406 } else {
1407 Q_ASSERT(!p->bindable().isEmpty());
1408 signalMethod = QQmlJSMetaMethod {}; // use dummy in this case
1409 }
1410 }
1411 }
1412
1413 if (!signalMethod.has_value()) { // haven't found anything
1414 // TODO: This should move into a new "Qml (module) Lint Plugin"
1415 // There is a small chance of suggesting this fix for things that are not actually
1416 // QtQml/Connections elements, but rather some other thing that is also called
1417 // "Connections". However, I guess we can live with this.
1418 if (signalScope->baseTypeName() == QStringLiteral("Connections")) {
1419 m_logger->log(
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);
1424 return;
1425 }
1426
1427 auto baseType = QQmlJSScope::nonCompositeBaseType(signalScope);
1428 if (baseType && baseType->hasCustomParser())
1429 return; // we can't know what custom parser actually supports
1430
1431 m_logger->log(
1432 QStringLiteral("no matching signal found for handler \"%1\"").arg(handlerName),
1433 qmlUnqualified, location, true, true);
1434 return;
1435 }
1436
1437 const auto signalParameters = signalMethod->parameters();
1438 QHash<QString, qsizetype> parameterNameIndexes;
1439 // check parameter positions and also if signal is suitable for onSignal handler
1440 for (int i = 0, end = signalParameters.size(); i < end; i++) {
1441 auto &p = signalParameters[i];
1442 parameterNameIndexes[p.name()] = i;
1443
1444 auto signalName = [&]() {
1445 if (signal)
1446 return u" called %1"_s.arg(*signal);
1447 return QString();
1448 };
1449 auto type = p.type();
1450 if (!type) {
1451 m_logger->log(
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);
1455 continue;
1456 }
1457
1458 if (type->isComposite())
1459 continue;
1460
1461 // only accept following parameters for non-composite types:
1462 // * QObjects by pointer (nonconst*, const*, const*const,*const)
1463 // * Value types by value (QFont, int)
1464 // * Value types by const ref (const QFont&, const int&)
1465
1466 auto parameterName = [&]() {
1467 if (p.name().isEmpty())
1468 return QString();
1469 return u" called %1"_s.arg(p.name());
1470 };
1471 switch (type->accessSemantics()) {
1472 case QQmlJSScope::AccessSemantics::Reference:
1473 if (!p.isPointer())
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(),
1477 handlerName),
1478 qmlSignalParameters, location);
1479 break;
1480 case QQmlJSScope::AccessSemantics::Value:
1481 case QQmlJSScope::AccessSemantics::Sequence:
1482 if (p.isPointer())
1483 m_logger->log(
1484 QStringLiteral(
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(),
1488 handlerName),
1489 qmlSignalParameters, location);
1490 break;
1491 case QQmlJSScope::AccessSemantics::None:
1492 m_logger->log(
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);
1497 break;
1498 }
1499 }
1500
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.")
1504 .arg(handlerName),
1505 qmlSignalParameters, location);
1506 return;
1507 }
1508
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())
1513 continue;
1514 const qsizetype j = *it;
1515
1516 if (j == i)
1517 continue;
1518
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);
1525 }
1526}
1527
1528void QQmlJSImportVisitor::addDefaultProperties()
1529{
1530 QQmlJSScope::ConstPtr parentScope = m_currentScope->parentScope();
1531 if (m_currentScope == m_exportedRootScope || parentScope->isArrayScope()
1532 || m_currentScope->isInlineComponent()) // inapplicable
1533 return;
1534
1535 m_pendingDefaultProperties[m_currentScope->parentScope()] << m_currentScope;
1536
1537 if (checkCustomParser(parentScope))
1538 return;
1539
1540 /* consider:
1541 *
1542 * QtObject { // <- parentScope
1543 * default property var p // (1)
1544 * QtObject {} // (2)
1545 * }
1546 *
1547 * `p` (1) is a property of a subtype of QtObject, it couldn't be used
1548 * in a property binding (2)
1549 */
1550 // thus, use a base type of parent scope to detect a default property
1551 parentScope = parentScope->baseType();
1552
1553 const QString defaultPropertyName =
1554 parentScope ? parentScope->defaultPropertyName() : QString();
1555
1556 if (defaultPropertyName.isEmpty()) // an error somewhere else
1557 return;
1558
1559 // Note: in this specific code path, binding on default property
1560 // means an object binding (we work with pending objects here)
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 });
1566}
1567
1568void QQmlJSImportVisitor::breakInheritanceCycles(const QQmlJSScope::Ptr &originalScope)
1569{
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(" -> "));
1577 }
1578 inheritenceCycle.append(scopes.first()->baseTypeName());
1579
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);
1585 break;
1586 }
1587
1588 scopes.append(scope);
1589
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()));
1603 }
1604 }
1605
1606 scope = newScope;
1607 }
1608}
1609
1610void QQmlJSImportVisitor::checkDeprecation(const QQmlJSScope::ConstPtr &originalScope)
1611{
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();
1616
1617 QString message =
1618 QStringLiteral("Type \"%1\" is deprecated").arg(scope->internalName());
1619
1620 if (!deprecation.reason.isEmpty())
1621 message.append(QStringLiteral(" (Reason: %1)").arg(deprecation.reason));
1622
1623 m_logger->log(message, qmlDeprecated, originalScope->sourceLocation());
1624 }
1625 }
1626 }
1627}
1628
1629void QQmlJSImportVisitor::checkForComponentTypeWithProperties(const QQmlJSScope::ConstPtr &scope)
1630{
1631 const QQmlJSScope::ConstPtr base = scope->baseType();
1632 if (!base)
1633 return;
1634
1635 // If the base type is composite itself, we ignore it being a QQmlCompoonent and
1636 // assume you actually mean its contents (and produce a deprecation warning).
1637 // We can ignore this case here.
1638 if (base->isComposite())
1639 return;
1640
1641 if (base->internalName() != "QQmlComponent"_L1)
1642 return;
1643
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());
1648 }
1649}
1650
1651bool QQmlJSImportVisitor::checkCustomParser(const QQmlJSScope::ConstPtr &scope)
1652{
1653 return scope->isInCustomParserParent();
1654}
1655
1656void QQmlJSImportVisitor::flushPendingSignalParameters()
1657{
1658 const QQmlJSMetaSignalHandler handler = m_signalHandlers[m_pendingSignalHandler];
1659 for (const QString &parameter : handler.signalParameters) {
1660 safeInsertJSIdentifier(m_currentScope, parameter,
1661 { QQmlJSScope::JavaScriptIdentifier::Injected,
1662 m_pendingSignalHandler, std::nullopt, false });
1663 }
1664 m_pendingSignalHandler = QQmlJS::SourceLocation();
1665}
1666
1667/*! \internal
1668
1669 Records a JS function or a Script binding for a given \a scope. Returns an
1670 index of a just recorded function-or-expression.
1671
1672 \sa synthesizeCompilationUnitRuntimeFunctionIndices
1673*/
1674QQmlJSMetaMethod::RelativeFunctionIndex
1675QQmlJSImportVisitor::addFunctionOrExpression(const QQmlJSScope::ConstPtr &scope,
1676 const QString &name)
1677{
1678 auto &array = m_functionsAndExpressions[scope];
1679 array.emplaceBack(name);
1680
1681 // add current function to all preceding functions in the stack. we don't
1682 // know which one is going to be the "publicly visible" one, so just blindly
1683 // add it to every level and let further logic take care of that. this
1684 // matches what m_innerFunctions represents as function at each level just
1685 // got a new inner function
1686 for (const auto &function : std::as_const(m_functionStack))
1687 m_innerFunctions[function]++;
1688 m_functionStack.push({ scope, name }); // create new function
1689
1690 return QQmlJSMetaMethod::RelativeFunctionIndex { int(array.size() - 1) };
1691}
1692
1693/*! \internal
1694
1695 Removes last FunctionOrExpressionIdentifier from m_functionStack, performing
1696 some checks on \a name.
1697
1698 \note \a name must match the name added via addFunctionOrExpression().
1699
1700 \sa addFunctionOrExpression, synthesizeCompilationUnitRuntimeFunctionIndices
1701*/
1702void QQmlJSImportVisitor::forgetFunctionExpression(const QString &name)
1703{
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();
1709}
1710
1711/*! \internal
1712
1713 Sets absolute runtime function indices for \a scope based on \a count
1714 (document-level variable). Returns count incremented by the number of
1715 runtime functions that the current \a scope has.
1716
1717 \note Not all scopes are considered as the function is compatible with the
1718 compilation unit output. The runtime functions are only recorded for
1719 QmlIR::Object (even if they don't strictly belong to it). Thus, in
1720 QQmlJSScope terms, we are only interested in QML scopes, group and attached
1721 property scopes.
1722*/
1723int QQmlJSImportVisitor::synthesizeCompilationUnitRuntimeFunctionIndices(
1724 const QQmlJSScope::Ptr &scope, int count) const
1725{
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;
1731 };
1732
1733 if (!suitableScope(scope))
1734 return count;
1735
1736 auto it = m_functionsAndExpressions.constFind(scope);
1737 if (it == m_functionsAndExpressions.cend()) // scope has no runtime functions
1738 return count;
1739
1740 const auto &functionsAndExpressions = *it;
1741 for (const QString &functionOrExpression : functionsAndExpressions) {
1742 scope->addOwnRuntimeFunctionIndex(
1743 static_cast<QQmlJSMetaMethod::AbsoluteFunctionIndex>(count));
1744 ++count;
1745
1746 // there are special cases: onSignal: function() { doSomethingUsefull }
1747 // in which we would register 2 functions in the runtime functions table
1748 // for the same expression. even more, we can have named and unnamed
1749 // closures inside a function or a script binding e.g.:
1750 // ```
1751 // function foo() {
1752 // var closure = () => { return 42; }; // this is an inner function
1753 // /* or:
1754 // property = Qt.binding(function() { return anotherProperty; });
1755 // */
1756 // return closure();
1757 // }
1758 // ```
1759 // see Codegen::defineFunction() in qv4codegen.cpp for more details
1760 count += m_innerFunctions.value({ scope, functionOrExpression }, 0);
1761 }
1762
1763 return count;
1764}
1765
1766void QQmlJSImportVisitor::populateRuntimeFunctionIndicesForDocument() const
1767{
1768 int count = 0;
1769 const auto synthesize = [&](const QQmlJSScope::Ptr &current) {
1770 count = synthesizeCompilationUnitRuntimeFunctionIndices(current, count);
1771 };
1772 QQmlJSUtils::traverseFollowingQmlIrObjectStructure(m_exportedRootScope, synthesize);
1773}
1774
1775bool QQmlJSImportVisitor::visit(QQmlJS::AST::ExpressionStatement *ast)
1776{
1777 if (m_pendingSignalHandler.isValid()) {
1778 enterEnvironment(QQmlSA::ScopeType::SignalHandlerFunctionScope, u"signalhandler"_s,
1779 ast->firstSourceLocation());
1780 flushPendingSignalParameters();
1781 }
1782 return true;
1783}
1784
1785void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ExpressionStatement *)
1786{
1787 if (m_currentScope->scopeType() == QQmlSA::ScopeType::SignalHandlerFunctionScope) {
1788 leaveEnvironment();
1789 }
1790}
1791
1793createNonUniqueScopeBinding(QQmlJSScope::Ptr &scope, const QString &name,
1794 const QQmlJS::SourceLocation &srcLocation);
1795
1796static void logLowerCaseImport(QStringView superType, QQmlJS::SourceLocation location,
1797 QQmlJSLogger *logger)
1798{
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);
1804}
1805
1806bool QQmlJSImportVisitor::visit(UiObjectDefinition *definition)
1807{
1808 const QString superType = buildName(definition->qualifiedTypeNameId);
1809
1810 const bool isRoot = !rootScopeIsValid();
1811 Q_ASSERT(!superType.isEmpty());
1812
1813 // we need to assume that it is a type based on its capitalization. Types defined in inline
1814 // components, for example, can have their type definition after their type usages:
1815 // Item { property IC myIC; component IC: Item{}; }
1816 // A QML type name always starts with an upper case letter; "_" is neither upper- nor
1817 // lower-case, so use !isUpper() to also catch names like "_bar".
1818 const qsizetype indexOfTypeName = superType.lastIndexOf(u'.');
1819 const bool looksLikeGroupedProperty = !superType.front().isUpper();
1820
1821 if (indexOfTypeName != -1 && looksLikeGroupedProperty) {
1822 logLowerCaseImport(superType, definition->qualifiedTypeNameId->identifierToken,
1823 m_logger);
1824 }
1825
1826 if (!looksLikeGroupedProperty) {
1827 if (!isRoot) {
1828 enterEnvironment(QQmlSA::ScopeType::QMLScope, superType,
1829 definition->firstSourceLocation());
1830 } else {
1831 enterRootScope(QQmlSA::ScopeType::QMLScope, superType,
1832 definition->firstSourceLocation());
1833 m_currentScope->setIsRootFileComponentFlag(true);
1834 }
1835
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);
1841 }
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,
1846 true, true);
1847
1848 } else if (!base->isCreatable()) {
1849 // composite type m_currentScope is allowed to be uncreatable, but it cannot be the base of anything else
1850 m_logger->log(u"Type %1 is not creatable."_s.arg(m_currentScope->baseTypeName()),
1851 qmlUncreatableType, definition->qualifiedTypeNameId->identifierToken,
1852 true, true);
1853 }
1854 }
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;
1864 }
1865
1866 addDefaultProperties();
1867 Q_ASSERT(m_currentScope->scopeType() == QQmlSA::ScopeType::QMLScope);
1868 m_qmlTypes.append(m_currentScope);
1869
1870 m_objectDefinitionScopes << m_currentScope;
1871 } else {
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(),
1879 usedTypes());
1880 }
1881
1882 m_currentScope->setAnnotations(parseAnnotations(definition->annotations));
1883
1884 return true;
1885}
1886
1887void QQmlJSImportVisitor::endVisit(UiObjectDefinition *)
1888{
1889 QQmlJSScope::resolveTypes(m_currentScope, m_rootScopeImports.contextualTypes(), usedTypes());
1890 leaveEnvironment();
1891}
1892
1893bool QQmlJSImportVisitor::visit(UiInlineComponent *component)
1894{
1895 if (!std::holds_alternative<RootDocumentNameType>(m_currentRootName)) {
1896 // we already warn in IRBuilder
1897 return true;
1898 }
1899
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);
1905 } else {
1906 m_seenInlineComponents[component->name] = component->firstSourceLocation();
1907 }
1908
1909 m_nextIsInlineComponent = true;
1910 m_currentRootName = component->name.toString();
1911 return true;
1912}
1913
1914void QQmlJSImportVisitor::endVisit(UiInlineComponent *component)
1915{
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());
1920 }
1921 m_nextIsInlineComponent = false; // might have missed an inline component if file contains invalid QML
1922}
1923
1924bool QQmlJSImportVisitor::visit(UiPublicMember *publicMember)
1925{
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()));
1938 while (param) {
1939 method.addParameter(
1940 QQmlJSMetaParameter(
1941 param->name.toString(),
1942 param->type ? param->type->toString() : QString()
1943 ));
1944 param = param->next;
1945 }
1946 m_currentScope->addOwnMethod(method);
1947 break;
1948 }
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);
1954 }
1955
1956 QString aliasExpr;
1957 const bool isAlias = (typeName == u"alias"_s);
1958 if (isAlias) {
1959 auto tryParseAlias = [&]() {
1960 typeName.clear(); // type name is useless for alias here, so keep it empty
1961 if (!publicMember->statement) {
1962 m_logger->log(QStringLiteral("Invalid alias expression - an initializer is needed."),
1963 qmlSyntax, publicMember->memberType->firstSourceLocation()); // TODO: extend warning to cover until endSourceLocation
1964 return;
1965 }
1966 const auto expression = cast<ExpressionStatement *>(publicMember->statement);
1967 auto node = expression ? expression->expression : nullptr;
1968 auto fex = cast<FieldMemberExpression *>(node);
1969 while (fex) {
1970 node = fex->base;
1971 aliasExpr.prepend(u'.' + fex->name.toString());
1972 fex = cast<FieldMemberExpression *>(node);
1973 }
1974
1975 if (const auto idExpression = cast<IdentifierExpression *>(node)) {
1976 aliasExpr.prepend(idExpression->name.toString());
1977 }
1978 };
1979 tryParseAlias();
1980 }
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));
1991 const auto type =
1992 isAlias ? QQmlJSScope::ConstPtr() : m_rootScopeImports.type(typeName).scope;
1993 if (type) {
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()
2000 };
2001 prop.setTypeName(typeName);
2002 } else {
2003 const QString internalName =
2004 factory ? factory->internalName() : type->internalName();
2005 prop.setTypeName(internalName.isEmpty() ? typeName : internalName);
2006 }
2007
2008 // Note: qml supports cyclic dependencies on properties, so don't lazy-load `type` here!
2009 // If `type` is lazy-loaded here and uses the currently-linted type, then `type` will only
2010 // see the incomplete definition of the currently-linted type and will complain about
2011 // missing properties for example.
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);
2017 }
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);
2023
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);
2031
2032 if (publicMember->isRequired())
2033 m_currentScope->setPropertyLocallyRequired(prop.propertyName(), true);
2034
2035 BindingExpressionParseResult parseResult = BindingExpressionParseResult::Invalid;
2036 // if property is an alias, initialization expression is not a binding
2037 if (!isAlias) {
2038 parseResult =
2039 parseBindingExpression(publicMember->name.toString(), publicMember->statement,
2040 publicMember);
2041 }
2042
2043 // however, if we have a property with a script binding assigned to it,
2044 // we have to create a new scope
2045 if (parseResult == BindingExpressionParseResult::Script) {
2046 Q_ASSERT(!m_savedBindingOuterScope); // automatically true due to grammar
2047 m_savedBindingOuterScope = m_currentScope;
2048 enterEnvironment(QQmlSA::ScopeType::BindingFunctionScope, QStringLiteral("binding"),
2049 publicMember->statement->firstSourceLocation());
2050 }
2051
2052 break;
2053 }
2054 }
2055
2056 return true;
2057}
2058
2059void QQmlJSImportVisitor::endVisit(UiPublicMember *publicMember)
2060{
2061 if (m_savedBindingOuterScope) {
2062 m_currentScope = m_savedBindingOuterScope;
2063 m_savedBindingOuterScope = {};
2064 // m_savedBindingOuterScope is only set if we encounter a script binding
2065 forgetFunctionExpression(publicMember->name.toString());
2066 }
2067}
2068
2069bool QQmlJSImportVisitor::visit(UiRequired *required)
2070{
2071 const QString name = required->name.toString();
2072
2073 m_requiredProperties << RequiredProperty { m_currentScope, name,
2074 required->firstSourceLocation() };
2075
2076 m_currentScope->setPropertyLocallyRequired(name, true);
2077 return true;
2078}
2079
2080void QQmlJSImportVisitor::visitFunctionExpressionHelper(QQmlJS::AST::FunctionExpression *fexpr)
2081{
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()));
2088
2089 if (!m_pendingMethodAnnotations.isEmpty()) {
2090 method.setAnnotations(m_pendingMethodAnnotations);
2091 m_pendingMethodAnnotations.clear();
2092 }
2093
2094 // If signatures are explicitly ignored, we don't parse the types
2095 const bool parseTypes = m_scopesById.signaturesAreEnforced();
2096
2097 bool formalsFullyTyped = parseTypes;
2098 bool anyFormalTyped = false;
2099 PendingMethodTypeAnnotations pending{ m_currentScope, name, {} };
2100
2101 // We potentially iterate twice over formals
2102 for (auto formals = fexpr->formals; formals; formals = formals->next) {
2103 PatternElement *e = formals->element;
2104 if (!e)
2105 continue;
2106 if (e->typeAnnotation && (e->bindingTarget || e->initializer))
2107 m_logger->log("Type annotations on default parameters are not supported"_L1,
2108 qmlSyntax,
2109 combine(e->firstSourceLocation(), e->lastSourceLocation()));
2110 }
2111
2112 if (const auto *formals = parseTypes ? fexpr->formals : nullptr) {
2113 const auto parameters = formals->formals();
2114 for (const auto &parameter : parameters) {
2115 const QString type = parameter.typeAnnotation
2116 ? parameter.typeAnnotation->type->toString()
2117 : QString();
2118 if (type.isEmpty()) {
2119 formalsFullyTyped = false;
2120 method.addParameter(QQmlJSMetaParameter(parameter.id, QStringLiteral("var")));
2121 pending.locations.emplace_back();
2122 } else {
2123 anyFormalTyped = true;
2124 method.addParameter(QQmlJSMetaParameter(parameter.id, type));
2125 pending.locations.append(
2126 combine(parameter.typeAnnotation->firstSourceLocation(),
2127 parameter.typeAnnotation->lastSourceLocation()));
2128 }
2129 }
2130 }
2131
2132 // If a function is fully typed, we can call it like a C++ function.
2133 method.setIsJavaScriptFunction(!formalsFullyTyped);
2134
2135 // Methods with explicit return type return that.
2136 // Methods with only untyped arguments return an untyped value.
2137 // Methods with at least one typed argument but no explicit return type return void.
2138 // In order to make a function without arguments return void, you have to specify that.
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"));
2145 } else {
2146 method.setReturnTypeName(QStringLiteral("var"));
2147 }
2148
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;
2152
2153 method.setCompiledFunctionIndex(addFunctionOrExpression(m_currentScope, method.methodName()));
2154 method.setMethodIndex(
2155 QQmlJSMetaMethod::RelativeFunctionIndex(m_currentScope->ownMethods().size()));
2156
2157 if (m_currentScope->scopeType() != QQmlSA::ScopeType::QMLScope) {
2158 // note: lambda methods have no identifier token
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(),
2165 false });
2166 }
2167 m_currentScope->addOwnMethod(method);
2168
2169 enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, name, fexpr->firstSourceLocation());
2170 } else {
2171 addFunctionOrExpression(m_currentScope, QStringLiteral("<anon>"));
2172 enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, QStringLiteral("<anon>"),
2173 fexpr->firstSourceLocation());
2174 }
2175}
2176
2177bool QQmlJSImportVisitor::visit(QQmlJS::AST::FunctionExpression *fexpr)
2178{
2179 visitFunctionExpressionHelper(fexpr);
2180 return true;
2181}
2182
2183void QQmlJSImportVisitor::endVisit(QQmlJS::AST::FunctionExpression *fexpr)
2184{
2185 forgetFunctionExpression(fexpr->name.toString());
2186 leaveEnvironment();
2187}
2188
2189bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiSourceElement *srcElement)
2190{
2191 m_pendingMethodAnnotations = parseAnnotations(srcElement->annotations);
2192 return true;
2193}
2194
2195bool QQmlJSImportVisitor::visit(QQmlJS::AST::FunctionDeclaration *fdecl)
2196{
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);
2204 }
2205 }
2206 visitFunctionExpressionHelper(fdecl);
2207 return true;
2208}
2209
2210void QQmlJSImportVisitor::endVisit(QQmlJS::AST::FunctionDeclaration *fdecl)
2211{
2212 forgetFunctionExpression(fdecl->name.toString());
2213 leaveEnvironment();
2214}
2215
2216bool QQmlJSImportVisitor::visit(QQmlJS::AST::ClassExpression *ast)
2217{
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());
2223 return true;
2224}
2225
2226void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ClassExpression *)
2227{
2228 leaveEnvironment();
2229}
2230
2231void handleTranslationBinding(QQmlJSMetaPropertyBinding &binding, QStringView base,
2232 QQmlJS::AST::ArgumentList *args)
2233{
2234 QStringView contextString;
2235 QStringView mainString;
2236 QStringView commentString;
2237 auto registerContextString = [&](QStringView string) {
2238 contextString = string;
2239 return 0;
2240 };
2241 auto registerMainString = [&](QStringView string) {
2242 mainString = string;
2243 return 0;
2244 };
2245 auto registerCommentString = [&](QStringView string) {
2246 commentString = string;
2247 return 0;
2248 };
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);
2255 } else {
2256 binding.setStringLiteral(mainString);
2257 }
2258 };
2259 QmlIR::tryGeneratingTranslationBindingBase(
2260 base, args,
2261 registerMainString, registerCommentString, registerContextString, finalizeBinding);
2262}
2263
2264QQmlJSImportVisitor::BindingExpressionParseResult
2265QQmlJSImportVisitor::parseBindingExpression(
2266 const QString &name, const QQmlJS::AST::Statement *statement,
2267 const UiPublicMember *associatedPropertyDefinition)
2268{
2269 if (statement == nullptr)
2270 return BindingExpressionParseResult::Invalid;
2271
2272 const auto *exprStatement = cast<const ExpressionStatement *>(statement);
2273
2274 if (exprStatement == nullptr) {
2275 QQmlJS::SourceLocation location = statement->firstSourceLocation();
2276
2277 if (const auto *block = cast<const Block *>(statement); block && block->statements) {
2278 location = block->statements->firstSourceLocation();
2279 }
2280
2281 QQmlJSMetaPropertyBinding binding(location, name);
2282 binding.setScriptBinding(addFunctionOrExpression(m_currentScope, name),
2283 QQmlSA::ScriptBindingKind::PropertyBinding, ScriptValue_Function);
2284 m_bindings.append(UnfinishedBinding {
2285 m_currentScope,
2286 [binding = std::move(binding)]() { return binding; }
2287 });
2288 return BindingExpressionParseResult::Script;
2289 }
2290
2291 auto expr = exprStatement->expression;
2292 QQmlJSMetaPropertyBinding binding(
2293 combine(expr->firstSourceLocation(), expr->lastSourceLocation()),
2294 name);
2295
2296 ScriptBindingValueType scriptBindingValuetype = ScriptValue_Unknown;
2297
2298 switch (expr->kind) {
2299 case Node::Kind_TrueLiteral:
2300 binding.setBoolLiteral(true);
2301 break;
2302 case Node::Kind_FalseLiteral:
2303 binding.setBoolLiteral(false);
2304 break;
2305 case Node::Kind_NullExpression:
2306 binding.setNullLiteral();
2307 break;
2308 case Node::Kind_IdentifierExpression: {
2309 auto idExpr = QQmlJS::AST::cast<QQmlJS::AST::IdentifierExpression *>(expr);
2310 Q_ASSERT(idExpr);
2311 if (idExpr->name == u"undefined")
2312 scriptBindingValuetype = ScriptValue_Undefined;
2313 break;
2314 }
2315 case Node::Kind_FunctionDeclaration:
2316 case Node::Kind_FunctionExpression:
2317 case Node::Kind_Block: {
2318 scriptBindingValuetype = ScriptValue_Function;
2319 break;
2320 }
2321 case Node::Kind_NumericLiteral:
2322 binding.setNumberLiteral(cast<NumericLiteral *>(expr)->value);
2323 break;
2324 case Node::Kind_StringLiteral:
2325 binding.setStringLiteral(cast<StringLiteral *>(expr)->value);
2326 break;
2327 case Node::Kind_RegExpLiteral:
2328 binding.setRegexpLiteral(cast<RegExpLiteral *>(expr)->pattern);
2329 break;
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);
2335 } else {
2336 binding.setScriptBinding(addFunctionOrExpression(m_currentScope, name),
2337 QQmlSA::ScriptBindingKind::PropertyBinding);
2338 }
2339 break;
2340 }
2341 default:
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);
2348 }
2349 break;
2350 }
2351
2352 if (!binding.isValid()) {
2353 // consider this to be a script binding (see IRBuilder::setBindingValue)
2354 binding.setScriptBinding(addFunctionOrExpression(m_currentScope, name),
2355 QQmlSA::ScriptBindingKind::PropertyBinding,
2356 scriptBindingValuetype);
2357 }
2358 m_bindings.append(UnfinishedBinding { m_currentScope, [=]() { return binding; } });
2359
2360 // translations are neither literal bindings nor script bindings
2361 if (binding.bindingType() == QQmlSA::BindingType::Translation
2362 || binding.bindingType() == QQmlSA::BindingType::TranslationById) {
2363 return BindingExpressionParseResult::Translation;
2364 }
2365 if (!QQmlJSMetaPropertyBinding::isLiteralBinding(binding.bindingType()))
2366 return BindingExpressionParseResult::Script;
2367
2368 if (associatedPropertyDefinition)
2369 handleLiteralBinding(binding, associatedPropertyDefinition);
2370
2371 return BindingExpressionParseResult::Literal;
2372}
2373
2374bool QQmlJSImportVisitor::isImportPrefix(QString prefix) const
2375{
2376 if (prefix.isEmpty() || !prefix.front().isUpper())
2377 return false;
2378
2379 return m_rootScopeImports.isNullType(prefix);
2380}
2381
2382void QQmlJSImportVisitor::handleIdDeclaration(QQmlJS::AST::UiScriptBinding *scriptBinding)
2383{
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());
2387 return;
2388 }
2389 const auto *statement = cast<ExpressionStatement *>(scriptBinding->statement);
2390 if (!statement) {
2391 // We already warn in IRBuilder
2392 return;
2393 }
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();
2401 }
2402 // we already warn in IRBuilder about the unparseable ID
2403 return QString();
2404 }();
2405
2406 m_currentScope->setIdSourceLocation(combine(scriptBinding->statement->firstSourceLocation(),
2407 scriptBinding->statement->lastSourceLocation()));
2408 if (m_scopesById.existsAnywhereInDocument(name)) {
2409 // ### TODO: find an alternative to breakInhertianceCycles here
2410 // we shouldn't need to search for the current root component in any case here
2411 breakInheritanceCycles(m_currentScope);
2412 m_scopesById.possibleScopes(
2413 name, m_currentScope, QQmlJSScopesByIdOption::Default,
2414 [&](const QQmlJSScope::ConstPtr &otherScopeWithID,
2415 QQmlJSScopesById::Confidence confidence) {
2416 // If it's a fuzzy match, that's still warning-worthy
2417 Q_UNUSED(confidence);
2418
2419 auto otherLocation = otherScopeWithID->sourceLocation();
2420
2421 // critical because subsequent analysis cannot cope with messed up ids
2422 // and the file is invalid
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;
2429 });
2430 }
2431 if (!name.isEmpty())
2432 m_scopesById.insert(name, m_currentScope);
2433}
2434
2435void QQmlJSImportVisitor::handleLiteralBinding(const QQmlJSMetaPropertyBinding &binding,
2436 const UiPublicMember *associatedPropertyDefinition)
2437{
2438 // stub
2439 Q_UNUSED(binding);
2440 Q_UNUSED(associatedPropertyDefinition);
2441}
2442
2443/*! \internal
2444
2445 Creates a new binding of either a GroupedProperty or an AttachedProperty type.
2446 The binding is added to the parentScope() of \a scope, under property name
2447 \a name and location \a srcLocation.
2448*/
2450createNonUniqueScopeBinding(QQmlJSScope::Ptr &scope, const QString &name,
2451 const QQmlJS::SourceLocation &srcLocation)
2452{
2453 const auto createBinding = [=]() {
2454 const QQmlJSScope::ScopeType type = scope->scopeType();
2457 const QQmlSA::BindingType bindingType = (type == QQmlSA::ScopeType::GroupedPropertyScope)
2460
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;
2465 });
2466 if (alreadyHasBinding) // no need to create any more
2467 return QQmlJSMetaPropertyBinding(QQmlJS::SourceLocation {});
2468
2469 QQmlJSMetaPropertyBinding binding(srcLocation, name);
2470 if (type == QQmlSA::ScopeType::GroupedPropertyScope)
2471 binding.setGroupBinding(static_cast<QSharedPointer<QQmlJSScope>>(scope));
2472 else
2473 binding.setAttachedBinding(static_cast<QSharedPointer<QQmlJSScope>>(scope));
2474 return binding;
2475 };
2476 return { scope->parentScope(), createBinding };
2477}
2478
2479bool QQmlJSImportVisitor::visit(UiScriptBinding *scriptBinding)
2480{
2481 Q_ASSERT(!m_savedBindingOuterScope); // automatically true due to grammar
2482 Q_ASSERT(!m_thisScriptBindingIsJavaScript); // automatically true due to grammar
2483 m_savedBindingOuterScope = m_currentScope;
2484 const auto id = scriptBinding->qualifiedId;
2485 if (!id->next && id->name == QLatin1String("id")) {
2486 handleIdDeclaration(scriptBinding);
2487 return true;
2488 }
2489
2490 auto group = id;
2491
2492 QString prefix;
2493 for (; group->next; group = group->next) {
2494 const QString name = group->name.toString();
2495 if (name.isEmpty())
2496 break;
2497
2498 if (group == id && isImportPrefix(name)) {
2499 prefix = name + u'.';
2500 continue;
2501 }
2502
2503 const bool isAttachedProperty = name.front().isUpper();
2504 if (isAttachedProperty) {
2505 // attached property
2506 enterEnvironmentNonUnique(QQmlSA::ScopeType::AttachedPropertyScope, prefix + name,
2507 group->firstSourceLocation());
2508 } else {
2509 // grouped property
2510 enterEnvironmentNonUnique(QQmlSA::ScopeType::GroupedPropertyScope, prefix + name,
2511 group->firstSourceLocation());
2512 }
2513 m_bindings.append(createNonUniqueScopeBinding(m_currentScope, prefix + name,
2514 group->firstSourceLocation()));
2515
2516 prefix.clear();
2517 }
2518
2519 const auto name = group->name.toString();
2520
2521 // This is a preliminary check.
2522 // Even if the name starts with "on", it might later turn out not to be a signal.
2523 const auto signal = QQmlSignalNames::handlerNameToSignalName(name);
2524
2525 if (!signal.has_value() || m_currentScope->hasProperty(name)) {
2526 m_propertyBindings[m_currentScope].append(
2527 { m_savedBindingOuterScope, group->firstSourceLocation(), name });
2528 // ### TODO: report Invalid parse status as a warning/error
2529 auto result = parseBindingExpression(name, scriptBinding->statement);
2530 m_thisScriptBindingIsJavaScript = (result == BindingExpressionParseResult::Script);
2531 } else {
2532 const auto statement = scriptBinding->statement;
2533 QStringList signalParameters;
2534
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();
2539 }
2540 }
2541
2542 QQmlJSMetaMethod scopeSignal;
2543 const auto methods = m_currentScope->methods(*signal, QQmlJSMetaMethodType::Signal);
2544 if (!methods.isEmpty())
2545 scopeSignal = methods[0];
2546
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 });
2553
2554 // NB: calculate runtime index right away to avoid miscalculation due to
2555 // losing real AST traversal order
2556 const auto index = addFunctionOrExpression(m_currentScope, name);
2557 const auto createBinding = [
2558 this,
2559 scope = m_currentScope,
2560 signalName = *signal,
2561 index,
2562 name,
2563 firstSourceLocation,
2564 groupLocation = group->firstSourceLocation(),
2565 signalParameters]() {
2566 // when encountering a signal handler, add it as a script binding
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)) {
2577 // Not a signal handler after all.
2578 // We can see this now because the type is fully resolved.
2579 kind = QQmlSA::ScriptBindingKind::PropertyBinding;
2580 m_signalHandlers.remove(firstSourceLocation);
2581 } else {
2582 // We already know it's bad, but let's allow checkSignal() to do its thing.
2583 checkSignal(scope, groupLocation, name, signalParameters);
2584 }
2585
2586 QQmlJSMetaPropertyBinding binding(firstSourceLocation, name);
2587 binding.setScriptBinding(index, kind, ScriptValue_Function);
2588 return binding;
2589 };
2590 m_bindings.append(UnfinishedBinding { m_currentScope, createBinding });
2591 m_thisScriptBindingIsJavaScript = true;
2592 }
2593
2594 // TODO: before leaving the scopes, we must create the binding.
2595
2596 // Leave any group/attached scopes so that the binding scope doesn't see its properties.
2597 while (m_currentScope->scopeType() == QQmlSA::ScopeType::GroupedPropertyScope
2598 || m_currentScope->scopeType() == QQmlSA::ScopeType::AttachedPropertyScope) {
2599 leaveEnvironment();
2600 }
2601
2602 if (signal) {
2603 enterEnvironment(QQmlSA::ScopeType::SignalHandlerFunctionScope,
2604 u"signalHandler"_s,
2605 scriptBinding->statement->firstSourceLocation());
2606 } else {
2607 enterEnvironment(QQmlSA::ScopeType::BindingFunctionScope,
2608 u"binding"_s,
2609 scriptBinding->statement->firstSourceLocation());
2610 }
2611
2612 return true;
2613}
2614
2615void QQmlJSImportVisitor::endVisit(UiScriptBinding *)
2616{
2617 if (m_savedBindingOuterScope) {
2618 m_currentScope = m_savedBindingOuterScope;
2619 m_savedBindingOuterScope = {};
2620 }
2621
2622 // forgetFunctionExpression() but without the name check since script
2623 // bindings are special (script bindings only sometimes result in java
2624 // script bindings. e.g. a literal binding is also a UiScriptBinding)
2625 if (m_thisScriptBindingIsJavaScript) {
2626 m_thisScriptBindingIsJavaScript = false;
2627 Q_ASSERT(!m_functionStack.isEmpty());
2628 m_functionStack.pop();
2629 }
2630}
2631
2632bool QQmlJSImportVisitor::visit(UiArrayBinding *arrayBinding)
2633{
2634 createAttachedAndGroupedScopes(arrayBinding->qualifiedId);
2635 enterEnvironment(QQmlSA::ScopeType::QMLScope, buildName(arrayBinding->qualifiedId),
2636 arrayBinding->firstSourceLocation());
2637 m_currentScope->setIsArrayScope(true);
2638 return true;
2639}
2640
2641void QQmlJSImportVisitor::endVisit(UiArrayBinding *arrayBinding)
2642{
2643 // immediate children (QML scopes) of m_currentScope are the objects inside
2644 // the array binding. note that we always work with object bindings here as
2645 // this is the only kind of bindings that UiArrayBinding is created for. any
2646 // other expressions involving lists (e.g. `var p: [1,2,3]`) are considered
2647 // to be script bindings
2648 const auto children = m_currentScope->childScopes();
2649 leaveEnvironment();
2650
2651 const int scopesEnteredCounter = openAttachedAndGroupedScopes(arrayBinding->qualifiedId);
2652 auto guard = qScopeGuard([this, scopesEnteredCounter]() {
2653 for (int i = 0; i < scopesEnteredCounter; ++i)
2654 leaveEnvironment();
2655 });
2656
2657 if (checkCustomParser(m_currentScope)) {
2658 // These warnings do not apply for custom parsers and their children and need to be handled
2659 // on a case by case basis
2660 return;
2661 }
2662
2663 auto group = arrayBinding->qualifiedId;
2664 for (; group->next; group = group->next) { }
2665 const QString propertyName = group->name.toString();
2666
2667 qsizetype i = 0;
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());
2673 return;
2674 }
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 {
2682 m_currentScope,
2683 [binding = std::move(binding)]() { return binding; },
2684 QQmlJSScope::ListPropertyTarget
2685 });
2686 }
2687}
2688
2689bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiEnumDeclaration *uied)
2690{
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));
2697 }
2698 m_currentScope->addOwnEnumeration(qmlEnum);
2699 return true;
2700}
2701
2702QList<QQmlJS::DiagnosticMessage> QQmlJSImportVisitor::importFromHost(
2703 const QString &path, const QString &prefix, const QQmlJS::SourceLocation &location)
2704{
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);
2709 return {};
2710 }
2711
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);
2718 return {};
2719 }
2720
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());
2730 return warnings;
2731 }
2732
2733 m_logger->log(
2734 "%1 is neither a file nor a directory. Are sure the import path is correct?"_L1.arg(
2735 path),
2736 qmlImport, location);
2737 return {};
2738}
2739
2740QList<QQmlJS::DiagnosticMessage> QQmlJSImportVisitor::importFromQrc(
2741 const QString &path, const QString &prefix, const QQmlJS::SourceLocation &location)
2742{
2743 Q_ASSERT(path.startsWith(u':'));
2744 const QQmlJSResourceFileMapper *mapper = m_importer->resourceFileMapper();
2745 if (!mapper)
2746 return {};
2747
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);
2758 return {};
2759 }
2760
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());
2768 return warnings;
2769}
2770
2771bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiImport *import)
2772{
2773 // construct path
2774 QString prefix = QLatin1String("");
2775 if (import->asToken.isValid()) {
2776 prefix += import->importId;
2777 m_seenModuleQualifiers.append(prefix);
2778 }
2779
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))
2789 : 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);
2794 return true;
2795 } else if (scheme == "file"_L1) {
2796 auto warnings = importFromHost(url.path(), prefix, importLocation);
2797 processImportWarnings("URL \"%1\""_L1.arg(url.path()), warnings, importLocation);
2798 return true;
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);
2802 return true;
2803 } else {
2804 m_logger->log("Unknown import syntax. Imports can be paths, qrc urls or file urls"_L1,
2805 qmlImport, import->firstSourceLocation());
2806 }
2807 }
2808
2809 const QString path = buildName(import->importUri);
2810
2811 QStringList staticModulesProvided;
2812
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());
2822
2823 if (prefix.isEmpty()) {
2824 for (const QString &staticModule : std::as_const(staticModulesProvided))
2825 addStaticImportWithLocation(path, import->firstSourceLocation(), path != staticModule);
2826 }
2827
2828 processImportWarnings(
2829 QStringLiteral("module \"%1\"").arg(path), warnings, import->firstSourceLocation());
2830 return true;
2831}
2832
2833#if QT_VERSION >= QT_VERSION_CHECK(6, 6, 0)
2834template<typename F>
2835void handlePragmaValues(QQmlJS::AST::UiPragma *pragma, F &&assign)
2836{
2837 for (const QQmlJS::AST::UiPragmaValueList *v = pragma->values; v; v = v->next)
2838 assign(v->value);
2839}
2840#else
2841template<typename F>
2842void handlePragmaValues(QQmlJS::AST::UiPragma *pragma, F &&assign)
2843{
2844 assign(pragma->value);
2845}
2846#endif
2847
2848bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiPragma *pragma)
2849{
2850 if (pragma->name == u"Strict"_s) {
2851 // If a file uses pragma Strict, it expects to be compiled, so automatically
2852 // enable compiler warnings unless the severity is set explicitly already (e.g.
2853 // by the user).
2854
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);
2863 } else {
2864 m_logger->log(u"Unknown argument \"%1\" to pragma ComponentBehavior"_s.arg(value),
2865 qmlSyntax, pragma->firstSourceLocation());
2866 }
2867 });
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);
2874 } else {
2875 m_logger->log(
2876 u"Unknown argument \"%1\" to pragma FunctionSignatureBehavior"_s.arg(value),
2877 qmlSyntax, pragma->firstSourceLocation());
2878 }
2879 });
2880 } else if (pragma->name == u"ValueTypeBehavior") {
2881 handlePragmaValues(pragma, [this, pragma](QStringView value) {
2882 if (value == u"Copy") {
2883 // Ignore
2884 } else if (value == u"Reference") {
2885 // Ignore
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);
2894 } else {
2895 m_logger->log(u"Unknown argument \"%1\" to pragma ValueTypeBehavior"_s.arg(value),
2896 qmlSyntax, pragma->firstSourceLocation());
2897 }
2898 });
2899 }
2900
2901 return true;
2902}
2903
2904void QQmlJSImportVisitor::throwRecursionDepthError()
2905{
2906 m_logger->log(QStringLiteral("Maximum statement or expression depth exceeded"),
2907 qmlRecursionDepthErrors, QQmlJS::SourceLocation());
2908}
2909
2910bool QQmlJSImportVisitor::visit(QQmlJS::AST::ClassDeclaration *ast)
2911{
2912 enterEnvironment(QQmlSA::ScopeType::JSFunctionScope, ast->name.toString(),
2913 ast->firstSourceLocation());
2914 return true;
2915}
2916
2917void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ClassDeclaration *)
2918{
2919 leaveEnvironment();
2920}
2921
2922bool QQmlJSImportVisitor::visit(QQmlJS::AST::ForStatement *ast)
2923{
2924 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral("forloop"),
2925 ast->firstSourceLocation());
2926 return true;
2927}
2928
2929void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ForStatement *)
2930{
2931 leaveEnvironment();
2932}
2933
2934bool QQmlJSImportVisitor::visit(QQmlJS::AST::ForEachStatement *ast)
2935{
2936 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral("foreachloop"),
2937 ast->firstSourceLocation());
2938 return true;
2939}
2940
2941void QQmlJSImportVisitor::endVisit(QQmlJS::AST::ForEachStatement *)
2942{
2943 leaveEnvironment();
2944}
2945
2946bool QQmlJSImportVisitor::visit(QQmlJS::AST::Block *ast)
2947{
2948 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral("block"),
2949 ast->firstSourceLocation());
2950
2951 if (m_pendingSignalHandler.isValid())
2952 flushPendingSignalParameters();
2953
2954 return true;
2955}
2956
2957void QQmlJSImportVisitor::endVisit(QQmlJS::AST::Block *)
2958{
2959 leaveEnvironment();
2960}
2961
2962bool QQmlJSImportVisitor::visit(QQmlJS::AST::CaseBlock *ast)
2963{
2964 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral("case"),
2965 ast->firstSourceLocation());
2966 return true;
2967}
2968
2969void QQmlJSImportVisitor::endVisit(QQmlJS::AST::CaseBlock *)
2970{
2971 leaveEnvironment();
2972}
2973
2974bool QQmlJSImportVisitor::visit(QQmlJS::AST::Catch *catchStatement)
2975{
2976 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral("catch"),
2977 catchStatement->firstSourceLocation());
2978 return true;
2979}
2980
2981void QQmlJSImportVisitor::endVisit(QQmlJS::AST::Catch *)
2982{
2983 leaveEnvironment();
2984}
2985
2986bool QQmlJSImportVisitor::visit(QQmlJS::AST::WithStatement *ast)
2987{
2988 enterEnvironment(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral("with"),
2989 ast->firstSourceLocation());
2990
2991 m_logger->log(QStringLiteral("with statements are strongly discouraged in QML "
2992 "and might cause false positives when analysing unqualified "
2993 "identifiers"),
2994 qmlWith, ast->firstSourceLocation());
2995
2996 return true;
2997}
2998
2999void QQmlJSImportVisitor::endVisit(QQmlJS::AST::WithStatement *)
3000{
3001 leaveEnvironment();
3002}
3003
3004bool QQmlJSImportVisitor::visit(QQmlJS::AST::FormalParameterList *fpl)
3005{
3006 const auto &boundedNames = fpl->boundNames();
3007 for (auto const &boundName : boundedNames) {
3008
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 });
3016 }
3017 return true;
3018}
3019
3020void QQmlJSImportVisitor::createAttachedAndGroupedScopes(UiQualifiedId *propertyName)
3021{
3022 bool needsResolution = false;
3023 int scopesEnteredCounter = 0;
3024 QString prefix;
3025 for (auto group = propertyName; group->next; group = group->next) {
3026 const QString idName = group->name.toString();
3027
3028 if (idName.isEmpty())
3029 break;
3030
3031 if (group == propertyName && isImportPrefix(idName)) {
3032 prefix = idName + u'.';
3033 continue;
3034 }
3035
3036 const auto scopeKind = idName.front().isUpper() ? QQmlSA::ScopeType::AttachedPropertyScope
3037 : QQmlSA::ScopeType::GroupedPropertyScope;
3038
3039 bool exists =
3040 enterEnvironmentNonUnique(scopeKind, prefix + idName, group->firstSourceLocation());
3041
3042 m_bindings.append(createNonUniqueScopeBinding(m_currentScope, prefix + idName,
3043 group->firstSourceLocation()));
3044
3045 ++scopesEnteredCounter;
3046 needsResolution = needsResolution || !exists;
3047
3048 prefix.clear();
3049 }
3050
3051 for (int i=0; i < scopesEnteredCounter; ++i) { // leave the scopes we entered again
3052 leaveEnvironment();
3053 }
3054
3055 // recursively resolve types for current scope if new scopes are found
3056 if (needsResolution) {
3057 QQmlJSScope::resolveTypes(m_currentScope, m_rootScopeImports.contextualTypes(),
3058 usedTypes());
3059 }
3060}
3061
3062bool QQmlJSImportVisitor::visit(QQmlJS::AST::UiObjectBinding *uiob)
3063{
3064 // ... __styleData: QtObject {...}
3065
3066 Q_ASSERT(uiob->qualifiedTypeNameId);
3067
3068 const QString typeName = buildName(uiob->qualifiedTypeNameId);
3069 if (typeName.front().isLower() && typeName.contains(u'.')) {
3070 logLowerCaseImport(typeName, uiob->qualifiedTypeNameId->identifierToken, m_logger);
3071 }
3072
3073 createAttachedAndGroupedScopes(uiob->qualifiedId);
3074
3075 enterEnvironment(QQmlSA::ScopeType::QMLScope, typeName,
3076 uiob->qualifiedTypeNameId->identifierToken);
3077
3078 m_qmlTypes.append(m_currentScope); // new QMLScope is created here, so add it
3079 m_objectBindingScopes << m_currentScope;
3080 return true;
3081}
3082
3083int QQmlJSImportVisitor::openAttachedAndGroupedScopes(UiQualifiedId *propertyName)
3084{
3085 QString prefix;
3086 int scopesEnteredCounter = 0;
3087 auto group = propertyName;
3088 for (; group->next; group = group->next) {
3089 const QString idName = group->name.toString();
3090
3091 if (idName.isEmpty())
3092 break;
3093
3094 if (group == propertyName && isImportPrefix(idName)) {
3095 prefix = idName + u'.';
3096 continue;
3097 }
3098
3099 const auto scopeKind = idName.front().isUpper() ? QQmlSA::ScopeType::AttachedPropertyScope
3100 : QQmlSA::ScopeType::GroupedPropertyScope;
3101 // definitely exists
3102 [[maybe_unused]] bool exists =
3103 enterEnvironmentNonUnique(scopeKind, prefix + idName, group->firstSourceLocation());
3104 Q_ASSERT(exists);
3105 scopesEnteredCounter++;
3106
3107 prefix.clear();
3108 }
3109 return scopesEnteredCounter;
3110}
3111
3112void QQmlJSImportVisitor::endVisit(QQmlJS::AST::UiObjectBinding *uiob)
3113{
3114 QQmlJSScope::resolveTypes(m_currentScope, m_rootScopeImports.contextualTypes(), usedTypes());
3115 // must be mutable, as we might mark it as implicitly wrapped in a component
3116 const QQmlJSScope::Ptr childScope = m_currentScope;
3117 leaveEnvironment();
3118
3119 const int scopesEnteredCounter = openAttachedAndGroupedScopes(uiob->qualifiedId);
3120
3121 // on ending the visit to UiObjectBinding, set the property type to the
3122 // just-visited one if the property exists and this type is valid
3123
3124 auto group = uiob->qualifiedId;
3125 for (; group->next; group = group->next) { }
3126 const QString propertyName = group->name.toString();
3127
3128 if (m_currentScope->isNameDeferred(propertyName)) {
3129 bool foundIds = false;
3130 QList<QQmlJSScope::ConstPtr> childScopes { childScope };
3131
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) {
3137 // Any ID is enough to trigger the warning, no matter how confident we are about it.
3138 Q_UNUSED(id);
3139 Q_UNUSED(confidence);
3140 foundIds = true;
3141 return QQmlJSScopesById::CallbackResult::StopSearch;
3142 });
3143
3144 childScopes << scope->childScopes();
3145 }
3146
3147 if (foundIds) {
3148 m_logger->log(
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
3150 .arg(propertyName),
3151 qmlDeferredPropertyId, uiob->firstSourceLocation());
3152 }
3153 }
3154
3155 if (checkCustomParser(m_currentScope)) {
3156 // These warnings do not apply for custom parsers and their children and need to be handled
3157 // on a case by case basis
3158 } else {
3159 m_pendingPropertyObjectBindings
3160 << PendingPropertyObjectBinding { m_currentScope, childScope, propertyName,
3161 uiob->firstSourceLocation(), uiob->hasOnToken };
3162
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));
3168 } else { // if (childScope->hasInterface(u"QQmlPropertyValueSource"_s))
3169 binding.setValueSource(QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope),
3170 QQmlJSScope::ConstPtr(childScope));
3171 }
3172 } else {
3173 binding.setObject(QQmlJSUtils::getScopeName(childScope, QQmlSA::ScopeType::QMLScope),
3174 QQmlJSScope::ConstPtr(childScope));
3175 }
3176 m_bindings.append(UnfinishedBinding { m_currentScope, [=]() { return binding; } });
3177 }
3178
3179 for (int i = 0; i < scopesEnteredCounter; ++i)
3180 leaveEnvironment();
3181}
3182
3183bool QQmlJSImportVisitor::visit(ExportDeclaration *)
3184{
3185 Q_ASSERT(rootScopeIsValid());
3186 Q_ASSERT(m_exportedRootScope != m_globalScope);
3187 Q_ASSERT(m_currentScope == m_globalScope);
3188 m_currentScope = m_exportedRootScope;
3189 return true;
3190}
3191
3192void QQmlJSImportVisitor::endVisit(ExportDeclaration *)
3193{
3194 Q_ASSERT(rootScopeIsValid());
3195 m_currentScope = m_exportedRootScope->parentScope();
3196 Q_ASSERT(m_currentScope == m_globalScope);
3197}
3198
3199bool QQmlJSImportVisitor::visit(ESModule *module)
3200{
3201 Q_ASSERT(!rootScopeIsValid());
3202 enterRootScope(QQmlSA::ScopeType::JSLexicalScope, QStringLiteral("module"),
3203 module->firstSourceLocation());
3204 m_currentScope->setIsScript(true);
3205 importBaseModules();
3206 leaveEnvironment();
3207 return true;
3208}
3209
3210void QQmlJSImportVisitor::endVisit(ESModule *)
3211{
3212 QQmlJSScope::resolveTypes(m_exportedRootScope, m_rootScopeImports.contextualTypes(),
3213 usedTypes());
3214}
3215
3216bool QQmlJSImportVisitor::visit(Program *program)
3217{
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();
3223 return true;
3224}
3225
3226void QQmlJSImportVisitor::endVisit(Program *)
3227{
3228 QQmlJSScope::resolveTypes(m_exportedRootScope, m_rootScopeImports.contextualTypes(),
3229 usedTypes());
3230}
3231
3232bool QQmlJSImportVisitor::visit(QQmlJS::AST::PatternElement *element)
3233{
3234 // Handles variable declarations such as var x = [1,2,3].
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,
3252 location);
3253 m_logger->log("Note: previous declaration of '%1' here"_L1.arg(variableName), qmlSyntax,
3254 previousDeclaration->location);
3255 }
3256 }
3257 const bool isConstVariable = element->scope == QQmlJS::AST::VariableScope::Const;
3258 const bool couldInsert = safeInsertJSIdentifier(m_currentScope,
3259 name.id,
3260 { (element->scope == QQmlJS::AST::VariableScope::Var)
3261 ? QQmlJSScope::JavaScriptIdentifier::FunctionScoped
3262 : QQmlJSScope::JavaScriptIdentifier::LexicalScoped,
3263 name.location, typeName,
3264 isConstVariable});
3265 if (!couldInsert)
3266 break;
3267 }
3268 }
3269
3270 return true;
3271}
3272
3273bool QQmlJSImportVisitor::visit(IfStatement *statement)
3274{
3275 if (BinaryExpression *binary = cast<BinaryExpression *>(statement->expression)) {
3276 if (binary->op == QSOperator::Assign) {
3277 m_logger->log(
3278 "Assignment in condition: did you mean to use \"===\" or \"==\" instead of \"=\"?"_L1,
3279 qmlAssignmentInCondition, binary->operatorToken);
3280 }
3281 }
3282 return true;
3283}
3284
3285QT_END_NAMESPACE
\inmodule QtQmlCompiler
\inmodule QtQmlCompiler
void handleTranslationBinding(QQmlJSMetaPropertyBinding &binding, QStringView base, QQmlJS::AST::ArgumentList *args)
static bool mayBeUnresolvedGroupedProperty(const QQmlJSScope::ConstPtr &scope)
static QList< QQmlJSScope::ConstPtr > qmlScopeDescendants(const QQmlJSScope::ConstPtr &scope)
static QQmlJSMetaProperty resolveProperty(const QString &possiblyGroupedProperty, QQmlJSScope::ConstPtr scope)
static bool causesImplicitComponentWrapping(const QQmlJSMetaProperty &property, const QQmlJSScope::ConstPtr &assignedType)
static const QLatin1StringView wasNotFound
static void logLowerCaseImport(QStringView superType, QQmlJS::SourceLocation location, QQmlJSLogger *logger)
static bool groupedPropertiesInSameGroupedObjectDefinition(const QQmlJS::SourceLocation &first, const QQmlJS::SourceLocation &second, const QList< QQmlJS::SourceLocation > &groupedObjectDefinitions)
QQmlJSImportVisitor::UnfinishedBinding createNonUniqueScopeBinding(QQmlJSScope::Ptr &scope, const QString &name, const QQmlJS::SourceLocation &srcLocation)
QString buildName(const Node *node)
static QQmlJSAnnotation::Value bindingToVariant(QQmlJS::AST::Statement *statement)