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
qqmldomastcreator.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant
4
11#include "qqmldomtop_p.h"
14
15#include <QtQml/private/qqmljsast_p.h>
16#include <QtQmlCompiler/private/qqmljsutils_p.h>
17
18#include <QtCore/QDir>
19#include <QtCore/QFileInfo>
20#include <QtCore/QScopeGuard>
21#include <QtCore/QLoggingCategory>
22
23#include <memory>
24#include <optional>
25#include <type_traits>
26#include <variant>
27#include <vector>
28
29Q_STATIC_LOGGING_CATEGORY(creatorLog, "qt.qmldom.astcreator", QtWarningMsg);
30
31/*
32 Avoid crashing on files with JS-elements that are not implemented yet.
33 Might be removed (definition + usages) once all script elements are implemented.
34*/
35#define Q_SCRIPTELEMENT_DISABLE()
36 do {
37 qCDebug(creatorLog) << "Could not construct the JS DOM at" << __FILE__ << ":" << __LINE__
38 << ", skipping JS elements...";
39 disableScriptElements();
40 } while (false)
41
42#define Q_SCRIPTELEMENT_EXIT_IF(check)
43 do {
44 if (m_enableScriptExpressions && (check)) {
45 Q_SCRIPTELEMENT_DISABLE();
46 return;
47 }
48 } while (false)
49
50QT_BEGIN_NAMESPACE
51namespace QQmlJS {
52namespace Dom {
53
54using namespace AST;
55
56template<typename K, typename V>
57V *valueFromMultimap(QMultiMap<K, V> &mmap, const K &key, index_type idx)
58{
59 if (idx < 0)
60 return nullptr;
61 auto it = mmap.find(key);
62 auto end = mmap.end();
63 if (it == end)
64 return nullptr;
65 auto it2 = it;
66 index_type nEl = 0;
67 while (it2 != end && it2.key() == key) {
68 ++it2;
69 ++nEl;
70 }
71 if (nEl <= idx)
72 return nullptr;
73 for (index_type i = idx + 1; i < nEl; ++i)
74 ++it;
75 return &(*it);
76}
77
78static ErrorGroups astParseErrors()
79{
80 static ErrorGroups errs = { { NewErrorGroup("Dom"), NewErrorGroup("QmlFile"),
81 NewErrorGroup("Parsing") } };
82 return errs;
83}
84
85static QString toString(const UiQualifiedId *qualifiedId, QChar delimiter = QLatin1Char('.'))
86{
87 QString result;
88
89 for (const UiQualifiedId *iter = qualifiedId; iter; iter = iter->next) {
90 if (iter != qualifiedId)
91 result += delimiter;
92
93 result += iter->name;
94 }
95
96 return result;
97}
98
99static QString typeToString(AST::Type *t)
100{
101 Q_ASSERT(t);
102 QString res = toString(t->typeId);
103
104 if (UiQualifiedId *arg = t->typeArgument)
105 res += u'<' + toString(arg) + u'>';
106
107 return res;
108}
109
110SourceLocation combineLocations(SourceLocation s1, SourceLocation s2)
111{
112 return combine(s1, s2);
113}
114
115SourceLocation combineLocations(Node *n)
116{
117 return combineLocations(n->firstSourceLocation(), n->lastSourceLocation());
118}
119
120static ScriptElementVariant wrapIntoFieldMemberExpression(const ScriptElementVariant &left,
121 const SourceLocation &dotToken,
122 const ScriptElementVariant &right)
123{
124 SourceLocation s1, s2;
125 left.visitConst([&s1](auto &&el) { s1 = el->mainRegionLocation(); });
126 right.visitConst([&s2](auto &&el) { s2 = el->mainRegionLocation(); });
127
128 auto result = std::make_shared<ScriptElements::BinaryExpression>(s1, s2);
129 result->addLocation(OperatorTokenRegion, dotToken);
131 result->setLeft(left);
132 result->setRight(right);
133 return ScriptElementVariant::fromElement(result);
134};
135
136/*!
137 \internal
138 Creates a FieldMemberExpression if the qualified id has dots.
139*/
141fieldMemberExpressionForQualifiedId(const AST::UiQualifiedId *qualifiedId)
142{
143 ScriptElementVariant bindable;
144 bool first = true;
145 for (auto exp = qualifiedId; exp; exp = exp->next) {
146 const SourceLocation identifierLoc = exp->identifierToken;
147 auto id = std::make_shared<ScriptElements::IdentifierExpression>(identifierLoc);
148 id->setName(exp->name);
149 if (first) {
150 first = false;
151 bindable = ScriptElementVariant::fromElement(id);
152 continue;
153 }
154 bindable = wrapIntoFieldMemberExpression(bindable, exp->dotToken,
155 ScriptElementVariant::fromElement(id));
156 }
157
158 return bindable;
159}
160
161QQmlDomAstCreatorBase::QmlStackElement &QQmlDomAstCreatorBase::currentQmlObjectOrComponentEl(int idx)
162{
163 Q_ASSERT_X(idx < nodeStack.size() && idx >= 0, "currentQmlObjectOrComponentEl",
164 "Stack does not contain enough elements!");
165 int i = nodeStack.size() - idx;
166 while (i-- > 0) {
167 DomType k = nodeStack.at(i).item.kind;
168 if (k == DomType::QmlObject || k == DomType::QmlComponent)
169 return nodeStack[i];
170 }
171 Q_ASSERT_X(false, "currentQmlObjectEl", "No QmlObject or component in stack");
172 return nodeStack.last();
173}
174
175QQmlDomAstCreatorBase::QmlStackElement &QQmlDomAstCreatorBase::currentNodeEl(int i)
176{
177 Q_ASSERT_X(i < nodeStack.size() && i >= 0, "currentNode", "Stack does not contain element!");
178 return nodeStack[nodeStack.size() - i - 1];
179}
180
181QQmlDomAstCreatorBase::ScriptStackElement &QQmlDomAstCreatorBase::currentScriptNodeEl(int i)
182{
183 Q_ASSERT_X(i < scriptNodeStack.size() && i >= 0, "currentNode",
184 "Stack does not contain element!");
185 return scriptNodeStack[scriptNodeStack.size() - i - 1];
186}
187
188QQmlDomAstCreatorBase::DomValue &QQmlDomAstCreatorBase::currentNode(int i)
189{
190 Q_ASSERT_X(i < nodeStack.size() && i >= 0, "currentNode",
191 "Stack does not contain element!");
192 return nodeStack[nodeStack.size() - i - 1].item;
193}
194
195void QQmlDomAstCreatorBase::removeCurrentNode(std::optional<DomType> expectedType)
196{
197 Q_ASSERT_X(!nodeStack.isEmpty(), className, "popCurrentNode() without any node");
198 if (expectedType)
199 Q_ASSERT(nodeStack.last().item.kind == *expectedType);
200 nodeStack.removeLast();
201}
202
203void QQmlDomAstCreatorBase::removeCurrentScriptNode(std::optional<DomType> expectedType)
204{
205 Q_SCRIPTELEMENT_EXIT_IF(scriptNodeStack.isEmpty());
206 Q_ASSERT_X(!scriptNodeStack.isEmpty(), className,
207 "popCurrentScriptNode() without any node");
208 if (expectedType)
209 Q_ASSERT(scriptNodeStack.last().kind == *expectedType);
210 scriptNodeStack.removeLast();
211}
212
213/*!
214 \internal
215 Prepares a script element DOM representation such that it can be used inside a QML DOM element.
216 This recursively sets the pathFromOwner and creates the FileLocations::Tree for all children of
217 element.
218
219 Beware that pathFromOwner is appended to ownerFileLocations when creating the FileLocations!
220
221 Make sure to add, for each of its use, a test in tst_qmldomitem:finalizeScriptExpressions, as
222 using a wrong pathFromOwner and/or a wrong base might lead to bugs hard to debug and spurious
223 crashes.
224 */
226QQmlDomAstCreatorBase::finalizeScriptExpression(const ScriptElementVariant &element, const Path &pathFromOwner,
227 const FileLocations::Tree &ownerFileLocations)
228{
229 auto e = element.base();
230 Q_ASSERT(e);
231
232 qCDebug(creatorLog) << "Finalizing script expression with path:"
233 << FileLocations::canonicalPathForTesting(ownerFileLocations)
234 .append(pathFromOwner.toString());
235 e->updatePathFromOwner(pathFromOwner);
236 e->createFileLocations(ownerFileLocations);
237 return element;
238}
239
240FileLocations::Tree QQmlDomAstCreatorBase::createMap(const FileLocations::Tree &base, const Path &p, AST::Node *n)
241{
242 FileLocations::Tree res = FileLocations::ensure(base, p);
243 if (n)
244 FileLocations::addRegion(res, MainRegion, combineLocations(n));
245 return res;
246}
247
248FileLocations::Tree QQmlDomAstCreatorBase::createMap(DomType k, const Path &p, AST::Node *n)
249{
250 Path relative;
251 FileLocations::Tree base;
252 switch (k) {
254 switch (currentNode().kind) {
258 case DomType::Binding:
259 case DomType::Id:
261 break;
262 default:
263 qCWarning(domLog) << "unexpected type" << domTypeToString(currentNode().kind);
264 Q_UNREACHABLE();
265 }
266 base = currentNodeEl().fileLocations;
267 if (p.length() > 2) {
268 Path p2 = p[p.length() - 2];
269 const auto fn = p2.headField();
270 if (fn
271 && (*fn == Fields::children || *fn == Fields::objects || *fn == Fields::value
272 || *fn == Fields::annotations))
273 relative = p.mid(p.length() - 2, 2);
274 else if (auto lastFn = p.last().headField(); lastFn && *lastFn == Fields::value)
275 relative = p.last();
276 else {
277 qCWarning(domLog) << "unexpected path to QmlObject in createMap" << p;
278 Q_UNREACHABLE();
279 }
280 } else {
281 qCWarning(domLog) << "unexpected path to QmlObject in createMap" << p;
282 Q_UNREACHABLE();
283 }
284 break;
286 relative = p;
287 base = currentNodeEl().fileLocations;
288 break;
290 case DomType::Pragma:
291 case DomType::Import:
292 case DomType::Id:
294 relative = p;
295 base = rootMap;
296 break;
297 case DomType::Binding:
300 base = currentEl<QmlObject>().fileLocations;
301 if (p.length() > 3)
302 relative = p.mid(p.length() - 3, 3);
303 else
304 relative = p;
305 break;
306
307 default:
308 qCWarning(domLog) << "Unexpected type in createMap:" << domTypeToString(k);
309 Q_UNREACHABLE();
310 break;
311 }
312 return createMap(base, relative, n);
313}
314
316 : qmlFile(qmlFile),
319{
320}
321
322bool QQmlDomAstCreatorBase::visit(UiProgram *program)
323{
324 QFileInfo fInfo(qmlFile.canonicalFilePath());
325 QString componentName = fInfo.baseName();
326 QmlComponent *cPtr;
327 Path p = qmlFilePtr->addComponent(QmlComponent(componentName), AddOption::KeepExisting,
328 &cPtr);
329 MutableDomItem newC(qmlFile.item(), p);
330 Q_ASSERT_X(newC.item(), className, "could not recover component added with addComponent");
331 // QmlFile region == Component region == program span
332 // we hide the component span because the component s written after the imports
333 FileLocations::addRegion(rootMap, MainRegion, combineLocations(program));
334 pushEl(p, *cPtr, program);
335
336 auto envPtr = qmlFile.environment().ownerAs<DomEnvironment>();
337 const bool loadDependencies =
338 !envPtr->options().testFlag(DomEnvironment::Option::NoDependencies);
339 if (m_loadFileLazily && loadDependencies) {
340 envPtr->loadPendingDependencies();
341 envPtr->commitToBase(qmlFile.environment().item());
342 }
343
344 return true;
345}
346
347void QQmlDomAstCreatorBase::endVisit(AST::UiProgram *)
348{
349 MutableDomItem newC = qmlFile.path(currentNodeEl().path);
350 QmlComponent &comp = current<QmlComponent>();
351 for (const Pragma &p : qmlFilePtr->pragmas()) {
352 if (p.name.compare(u"singleton", Qt::CaseInsensitive) == 0) {
353 comp.setIsSingleton(true);
354 comp.setIsCreatable(false); // correct?
355 }
356 }
357 *newC.mutableAs<QmlComponent>() = comp;
358 removeCurrentNode(DomType::QmlComponent);
359 Q_ASSERT_X(nodeStack.isEmpty(), className, "ui program did not finish node stack");
360}
361
362bool QQmlDomAstCreatorBase::visit(UiPragma *el)
363{
364 QStringList valueList;
365 for (auto t = el->values; t; t = t->next)
366 valueList << t->value.toString();
367
368 auto fileLocation = createMap(
369 DomType::Pragma, qmlFilePtr->addPragma(Pragma(el->name.toString(), valueList)), el);
370 FileLocations::addRegion(fileLocation, PragmaKeywordRegion, el->pragmaToken);
371 FileLocations::addRegion(fileLocation, IdentifierRegion, el->pragmaIdToken);
372 if (el->colonToken.isValid()) {
373 FileLocations::addRegion(fileLocation, ColonTokenRegion, el->colonToken);
374 }
375 int i = 0;
376 for (auto t = el->values; t; t = t->next) {
377 auto subMap = createMap(fileLocation, Path().withField(Fields::values).withIndex(i), t);
378 FileLocations::addRegion(subMap, PragmaValuesRegion, t->location);
379 ++i;
380 }
381
382 return true;
383}
384
385bool QQmlDomAstCreatorBase::visit(UiImport *el)
386{
387 Version v(Version::Latest, Version::Latest);
388 if (el->version && el->version->version.hasMajorVersion())
389 v.majorVersion = el->version->version.majorVersion();
390 if (el->version && el->version->version.hasMinorVersion())
391 v.minorVersion = el->version->version.minorVersion();
392
393 auto envPtr = qmlFile.environment().ownerAs<DomEnvironment>();
394 const bool loadDependencies =
395 !envPtr->options().testFlag(DomEnvironment::Option::NoDependencies);
396 FileLocations::Tree fileLocation;
397 if (el->importUri != nullptr) {
398 const Import import =
399 Import::fromUriString(toString(el->importUri), v, el->importId.toString());
400 fileLocation = createMap(DomType::Import, qmlFilePtr->addImport(import), el);
401
402 FileLocations::addRegion(fileLocation, ImportUriRegion, combineLocations(el->importUri));
403 } else {
404 const Import import =
405 Import::fromFileString(el->fileName.toString(), el->importId.toString());
406 fileLocation = createMap(DomType::Import, qmlFilePtr->addImport(import), el);
407
408 FileLocations::addRegion(fileLocation, ImportUriRegion, el->fileNameToken);
409 }
410 if (m_loadFileLazily && loadDependencies) {
411 envPtr->loadPendingDependencies();
412 envPtr->commitToBase(qmlFile.environment().item());
413 }
414
415 if (el->importToken.isValid())
416 FileLocations::addRegion(fileLocation, ImportTokenRegion, el->importToken);
417
418 if (el->asToken.isValid())
419 FileLocations::addRegion(fileLocation, AsTokenRegion, el->asToken);
420
421 if (el->importIdToken.isValid())
422 FileLocations::addRegion(fileLocation, IdNameRegion, el->importIdToken);
423
424 if (el->version)
425 FileLocations::addRegion(fileLocation, VersionRegion, combineLocations(el->version));
426
427
428 return true;
429}
430
431bool QQmlDomAstCreatorBase::visit(AST::UiPublicMember *el)
432{
433 switch (el->type) {
434 case AST::UiPublicMember::Signal: {
435 MethodInfo m;
436 m.name = el->name.toString();
437 m.typeName = toString(el->memberType);
438 m.isReadonly = el->isReadonly();
439 m.access = MethodInfo::Public;
440 m.methodType = MethodInfo::Signal;
441 m.isList = el->typeModifier == QLatin1String("list");
442 MethodInfo *mPtr;
443 Path p = current<QmlObject>().addMethod(m, AddOption::KeepExisting, &mPtr);
444 pushEl(p, *mPtr, el);
445
446 const auto fileLocations = nodeStack.last().fileLocations;
447 FileLocations::addRegion(fileLocations, SignalKeywordRegion, el->propertyToken());
448 FileLocations::addRegion(fileLocations, IdentifierRegion, el->identifierToken);
449 if (el->lparenToken.isValid())
450 FileLocations::addRegion(fileLocations, LeftParenthesisRegion, el->lparenToken);
451 if (el->rparenToken.isValid())
452 FileLocations::addRegion(fileLocations, RightParenthesisRegion, el->rparenToken);
453
454 MethodInfo &mInfo = std::get<MethodInfo>(currentNode().value);
455 AST::UiParameterList *args = el->parameters;
456 while (args) {
457 MethodParameter param;
458 param.name = args->name.toString();
459 param.typeName = args->type ? args->type->toString() : QString();
460 index_type idx = index_type(mInfo.parameters.size());
461 if (!args->colonToken.isValid())
463 mInfo.parameters.append(param);
464 auto argLocs = FileLocations::ensure(nodeStack.last().fileLocations,
465 Path::fromField(Fields::parameters).withIndex(idx));
466 FileLocations::addRegion(argLocs, MainRegion, combineLocations(args));
467 FileLocations::addRegion(argLocs, IdentifierRegion, args->identifierToken);
468 if (args->type) {
469 if (args->colonToken.isValid())
470 FileLocations::addRegion(argLocs, ColonTokenRegion, args->colonToken);
471 FileLocations::addRegion(argLocs, TypeIdentifierRegion, args->propertyTypeToken);
472 }
473 args = args->next;
474 }
475 break;
476 }
477 case AST::UiPublicMember::Property: {
479 p.name = el->name.toString();
480 p.typeName = toString(el->memberType);
481 p.isReadonly = el->isReadonly();
482 p.isDefaultMember = el->isDefaultMember();
483 p.isRequired = el->isRequired();
484 p.isList = el->typeModifier == QLatin1String("list");
485 p.isVirtual = el->isVirtual();
486 p.isOverride = el->isOverride();
487 p.isFinal = el->isFinal();
488 if (!el->typeModifier.isEmpty())
489 p.typeName = el->typeModifier.toString() + QChar(u'<') + p.typeName + QChar(u'>');
490 PropertyDefinition *pPtr;
491 Path pPathFromOwner =
492 current<QmlObject>().addPropertyDef(p, AddOption::KeepExisting, &pPtr);
493 if (m_enableScriptExpressions) {
494 auto qmlObjectType = makeGenericScriptElement(el->memberType, DomType::ScriptType);
495 qmlObjectType->insertChild(Fields::typeName,
496 fieldMemberExpressionForQualifiedId(el->memberType));
497 pPtr->setNameIdentifiers(finalizeScriptExpression(
498 ScriptElementVariant::fromElement(qmlObjectType),
499 pPathFromOwner.withField(Fields::nameIdentifiers), rootMap));
500 // skip binding identifiers of the binding inside the property definition, if there is
501 // one
502 m_skipBindingIdentifiers = el->binding;
503 }
504 pushEl(pPathFromOwner, *pPtr, el);
505 FileLocations::addRegion(nodeStack.last().fileLocations, PropertyKeywordRegion,
506 el->propertyToken());
507 FileLocations::addRegion(nodeStack.last().fileLocations, IdentifierRegion,
508 el->identifierToken);
509 FileLocations::addRegion(nodeStack.last().fileLocations, TypeIdentifierRegion,
510 el->typeToken);
511 FileLocations::addRegion(nodeStack.last().fileLocations, ColonTokenRegion, el->colonToken);
512 if (el->typeModifierToken.isValid())
513 FileLocations::addRegion(nodeStack.last().fileLocations, TypeModifierRegion, el->typeModifierToken);
514 if (p.name == u"id")
515 qmlFile.addError(std::move(astParseErrors()
516 .warning(tr("id is a special attribute, that should not be "
517 "used as property name"))
518 .withPath(currentNodeEl().path)));
519 if (p.isDefaultMember) {
520 FileLocations::addRegion(nodeStack.last().fileLocations, DefaultKeywordRegion,
521 el->defaultToken());
522 }
523 if (p.isVirtual) {
524 FileLocations::addRegion(nodeStack.last().fileLocations, VirtualKeywordRegion,
525 el->virtualToken());
526 }
527 if (p.isOverride) {
528 FileLocations::addRegion(nodeStack.last().fileLocations, OverrideKeywordRegion,
529 el->overrideToken());
530 }
531 if (p.isFinal) {
532 FileLocations::addRegion(nodeStack.last().fileLocations, FinalKeywordRegion,
533 el->finalToken());
534 }
535 if (p.isRequired) {
536 FileLocations::addRegion(nodeStack.last().fileLocations, RequiredKeywordRegion,
537 el->requiredToken());
538 }
539 if (p.isReadonly) {
540 FileLocations::addRegion(nodeStack.last().fileLocations, ReadonlyKeywordRegion,
541 el->readonlyToken());
542 }
543 if (el->statement) {
544 ++m_nestedFunctionDepth;
546 SourceLocation loc = combineLocations(el->statement);
547 QStringView code = qmlFilePtr->code();
548
549 auto script = std::make_shared<ScriptExpression>(
550 code.mid(loc.offset, loc.length), qmlFilePtr->engine(), el->statement,
551 qmlFilePtr->astComments(), ScriptExpression::ExpressionType::BindingExpression,
552 loc);
553 Binding *bPtr;
554 Path bPathFromOwner = current<QmlObject>().addBinding(Binding(p.name, script, bType),
556 FileLocations::Tree bLoc = createMap(DomType::Binding, bPathFromOwner, el->statement);
557 FileLocations::addRegion(bLoc, ColonTokenRegion, el->colonToken);
558 FileLocations::Tree valueLoc = FileLocations::ensure(bLoc, Path::fromField(Fields::value));
559 FileLocations::addRegion(valueLoc, MainRegion, combineLocations(el->statement));
560 // push it also: its needed in endVisit to add the scriptNode to it
561 // do not use pushEl to avoid recreating the already created "bLoc" Map
562 nodeStack.append({ std::move(bPathFromOwner), *bPtr, std::move(bLoc) });
563 }
564 break;
565 }
566 }
567 return true;
568}
569
570void QQmlDomAstCreatorBase::endVisit(AST::UiPublicMember *el)
571{
572 if (auto &lastEl = currentNode(); lastEl.kind == DomType::Binding) {
573 --m_nestedFunctionDepth;
574 Binding &b = std::get<Binding>(lastEl.value);
575 if (m_enableScriptExpressions
576 && (scriptNodeStack.size() != 1 || scriptNodeStack.last().isList())) {
578 }
579 if (m_enableScriptExpressions) {
580 b.scriptExpressionValue()->setScriptElement(finalizeScriptExpression(
581 currentScriptNodeEl().takeVariant(), Path().withField(Fields::scriptElement),
582 FileLocations::ensure(currentNodeEl().fileLocations,
583 Path().withField(Fields::value))));
584 removeCurrentScriptNode({});
585 }
586
587 QmlObject &containingObject = current<QmlObject>();
588 Binding *bPtr =
589 valueFromMultimap(containingObject.m_bindings, b.name(), currentIndex());
590 Q_ASSERT(bPtr);
591 removeCurrentNode({});
592 }
593 Node::accept(el->parameters, this);
594 loadAnnotations(el);
595 if ((el->binding || el->statement)
596 && nodeStack.last().item.kind == DomType::PropertyDefinition) {
597 PropertyDefinition &pDef = std::get<PropertyDefinition>(nodeStack.last().item.value);
598 if (!pDef.annotations.isEmpty()) {
599 QmlObject duplicate;
600 duplicate.setName(QLatin1String("duplicate"));
601 QmlObject &obj = current<QmlObject>();
602 auto it = obj.m_bindings.find(pDef.name);
603 if (it != obj.m_bindings.end()) {
604 for (QmlObject ann : pDef.annotations) {
605 ann.addAnnotation(duplicate);
606 it->addAnnotation(currentEl<QmlObject>()
607 .path.withField(Fields::bindings)
608 .withKey(pDef.name)
609 .withIndex(obj.m_bindings.values(pDef.name).size() - 1),
610 ann);
611 }
612 }
613 }
614 }
615 QmlObject &obj = current<QmlObject>();
616 QmlStackElement &sEl = nodeStack.last();
617 switch (sEl.item.kind) {
619 PropertyDefinition pDef = std::get<PropertyDefinition>(sEl.item.value);
620 PropertyDefinition *pDefPtr =
621 valueFromMultimap(obj.m_propertyDefs, pDef.name, *sEl.path.last().headIndex());
622 Q_ASSERT(pDefPtr);
623 *pDefPtr = std::move(pDef);
624 } break;
625 case DomType::MethodInfo: {
626 MethodInfo m = std::get<MethodInfo>(sEl.item.value);
627 MethodInfo *mPtr = valueFromMultimap(obj.m_methods, m.name, *sEl.path.last().headIndex());
628 Q_ASSERT(mPtr);
629 *mPtr = std::move(m);
630 } break;
631 default:
632 Q_UNREACHABLE();
633 }
634 removeCurrentNode({});
635}
636
637void QQmlDomAstCreatorBase::endVisit(AST::FormalParameterList *list)
638{
639 endVisitForLists(list);
640}
641
642bool QQmlDomAstCreatorBase::visit(AST::FunctionExpression *)
643{
644 ++m_nestedFunctionDepth;
645 if (!m_enableScriptExpressions)
646 return false;
647
648 return true;
649}
650
651ScriptElementVariant QQmlDomAstCreatorBase::prepareBodyForFunction(AST::FunctionExpression *fExpression)
652{
653 Q_ASSERT(!scriptNodeStack.isEmpty() || !fExpression->body);
654
655 if (fExpression->body) {
656 if (currentScriptNodeEl().isList()) {
657 // It is more intuitive to have functions with a block as a body instead of a
658 // list.
659 auto body = std::make_shared<ScriptElements::BlockStatement>(
660 combineLocations(fExpression->lbraceToken, fExpression->rbraceToken));
661 body->setStatements(currentScriptNodeEl().takeList());
662 if (auto semanticScope = body->statements().semanticScope())
663 body->setSemanticScope(semanticScope);
664 auto result = ScriptElementVariant::fromElement(body);
665 removeCurrentScriptNode({});
666 return result;
667 } else {
668 auto result = currentScriptNodeEl().takeVariant();
669 removeCurrentScriptNode({});
670 return result;
671 }
672 Q_UNREACHABLE_RETURN({});
673 }
674
675 // for convenience purposes: insert an empty BlockStatement
676 auto body = std::make_shared<ScriptElements::BlockStatement>(
677 combineLocations(fExpression->lbraceToken, fExpression->rbraceToken));
678 return ScriptElementVariant::fromElement(body);
679}
680
681void QQmlDomAstCreatorBase::endVisit(AST::FunctionExpression *fExpression)
682{
683 --m_nestedFunctionDepth;
684 if (!m_enableScriptExpressions)
685 return;
686
687 auto current = makeGenericScriptElement(fExpression, DomType::ScriptFunctionExpression);
688 if (fExpression->identifierToken.isValid())
689 current->addLocation(IdentifierRegion, fExpression->identifierToken);
690 if (fExpression->functionToken.isValid())
691 current->addLocation(FunctionKeywordRegion, fExpression->functionToken);
692 if (fExpression->starToken.isValid())
693 current->addLocation(StarTokenRegion, fExpression->starToken);
694 if (fExpression->lparenToken.isValid())
695 current->addLocation(LeftParenthesisRegion, fExpression->lparenToken);
696 if (fExpression->rparenToken.isValid())
697 current->addLocation(RightParenthesisRegion, fExpression->rparenToken);
698 if (fExpression->lbraceToken.isValid())
699 current->addLocation(LeftBraceRegion, fExpression->lbraceToken);
700 if (fExpression->rbraceToken.isValid())
701 current->addLocation(RightBraceRegion, fExpression->rbraceToken);
702 if (fExpression->typeAnnotation) {
703 current->addLocation(TypeIdentifierRegion,
704 combineLocations(fExpression->typeAnnotation->type));
705 }
706
707 Q_SCRIPTELEMENT_EXIT_IF(scriptNodeStack.isEmpty() && fExpression->body);
708 current->insertChild(Fields::body, prepareBodyForFunction(fExpression));
709
710 if (fExpression->typeAnnotation) {
712 current->insertChild(Fields::returnType, currentScriptNodeEl().takeVariant());
713 scriptNodeStack.removeLast();
714 }
715 if (fExpression->formals) {
717 current->insertChild(Fields::parameters, currentScriptNodeEl().takeList());
718 scriptNodeStack.removeLast();
719 }
720
721 if (!fExpression->name.isEmpty())
722 current->insertValue(Fields::name, fExpression->name);
723
724 pushScriptElement(current);
725}
726
727bool QQmlDomAstCreatorBase::visit(AST::FunctionDeclaration *fDef)
728{
729 // Treat nested functions as (named) lambdas instead of Qml Object methods.
730 if (m_nestedFunctionDepth > 0) {
731 return visit(static_cast<FunctionExpression *>(fDef));
732 }
733 ++m_nestedFunctionDepth;
734 const QStringView code(qmlFilePtr->code());
735 MethodInfo m;
736 m.name = fDef->name.toString();
737 if (AST::TypeAnnotation *tAnn = fDef->typeAnnotation) {
738 if (AST::Type *t = tAnn->type)
739 m.typeName = typeToString(t);
740 }
741 m.access = MethodInfo::Public;
742 m.methodType = MethodInfo::Method;
743 m.isGenerator = fDef->isGenerator;
744
745 SourceLocation bodyLoc = fDef->body ? combineLocations(fDef->body)
746 : combineLocations(fDef->lbraceToken, fDef->rbraceToken);
747 m.body = std::make_shared<ScriptExpression>(
748 code.mid(bodyLoc.offset, bodyLoc.length), qmlFilePtr->engine(), fDef->body,
749 qmlFilePtr->astComments(), ScriptExpression::ExpressionType::FunctionBody, bodyLoc);
750
751 if (fDef->typeAnnotation) {
752 SourceLocation typeLoc = combineLocations(fDef->typeAnnotation);
753 m.returnType = std::make_shared<ScriptExpression>(
754 code.mid(typeLoc.offset, typeLoc.length), qmlFilePtr->engine(),
755 fDef->typeAnnotation, qmlFilePtr->astComments(),
756 ScriptExpression::ExpressionType::ReturnType, typeLoc);
757 }
758
759 MethodInfo *mPtr;
760 Path mPathFromOwner = current<QmlObject>().addMethod(m, AddOption::KeepExisting, &mPtr);
761 pushEl(mPathFromOwner, *mPtr,
762 fDef); // add at the start and use the normal recursive visit?
763 FileLocations::Tree &fLoc = nodeStack.last().fileLocations;
764 if (fDef->identifierToken.isValid())
765 FileLocations::addRegion(fLoc, IdentifierRegion, fDef->identifierToken);
766 auto bodyTree = FileLocations::ensure(fLoc, Path::fromField(Fields::body));
767 FileLocations::addRegion(bodyTree, MainRegion, bodyLoc);
768 if (fDef->functionToken.isValid())
769 FileLocations::addRegion(fLoc, FunctionKeywordRegion, fDef->functionToken);
770 if (fDef->starToken.isValid())
771 FileLocations::addRegion(fLoc, StarTokenRegion, fDef->starToken);
772 if (fDef->lparenToken.length != 0)
773 FileLocations::addRegion(fLoc, LeftParenthesisRegion, fDef->lparenToken);
774 if (fDef->rparenToken.length != 0)
775 FileLocations::addRegion(fLoc, RightParenthesisRegion, fDef->rparenToken);
776 if (fDef->lbraceToken.length != 0)
777 FileLocations::addRegion(fLoc, LeftBraceRegion, fDef->lbraceToken);
778 if (fDef->rbraceToken.length != 0)
779 FileLocations::addRegion(fLoc, RightBraceRegion, fDef->rbraceToken);
780 if (fDef->typeAnnotation)
781 FileLocations::addRegion(fLoc, TypeIdentifierRegion, combineLocations(fDef->typeAnnotation->type));
782 MethodInfo &mInfo = std::get<MethodInfo>(currentNode().value);
783 AST::FormalParameterList *args = fDef->formals;
784 while (args) {
785 MethodParameter param;
786 param.name = args->element->bindingIdentifier.toString();
787 if (AST::TypeAnnotation *tAnn = args->element->typeAnnotation) {
788 if (AST::Type *t = tAnn->type)
789 param.typeName = typeToString(t);
790 }
791 if (args->element->initializer) {
792 SourceLocation loc = combineLocations(args->element->initializer);
793 param.defaultValue = std::make_shared<ScriptExpression>(
794 code.mid(loc.offset, loc.length), qmlFilePtr->engine(),
795 args->element->initializer, qmlFilePtr->astComments(),
796 ScriptExpression::ExpressionType::ArgInitializer, loc);
797 }
798 if (args->element->type == AST::PatternElement::SpreadElement)
799 param.isRestElement = true;
800 SourceLocation parameterLoc = combineLocations(args->element);
801 param.value = std::make_shared<ScriptExpression>(
802 code.mid(parameterLoc.offset, parameterLoc.length), qmlFilePtr->engine(),
803 args->element, qmlFilePtr->astComments(),
804 ScriptExpression::ExpressionType::ArgumentStructure, parameterLoc);
805
806 index_type idx = index_type(mInfo.parameters.size());
807 mInfo.parameters.append(param);
808 auto argLocs = FileLocations::ensure(nodeStack.last().fileLocations,
809 Path::fromField(Fields::parameters).withIndex(idx));
810 FileLocations::addRegion(argLocs, MainRegion, combineLocations(args));
811 if (args->element->identifierToken.isValid())
812 FileLocations::addRegion(argLocs, IdentifierRegion, args->element->identifierToken);
813 if (args->element->typeAnnotation)
814 FileLocations::addRegion(argLocs, TypeIdentifierRegion, combineLocations(args->element->typeAnnotation->type));
815 args = args->next;
816 }
817 return true;
818}
819
820bool QQmlDomAstCreatorBase::visit(AST::UiSourceElement *el)
821{
822 if (AST::cast<VariableStatement *>(el->sourceElement)) {
823 qmlFile.addError(astParseErrors().warning(
824 "JavaScript declarations are not allowed in QML elements"_L1));
825 return false;
826 }
827 return true;
828}
829
830static void setFormalParameterKind(ScriptElementVariant &variant)
831{
832 if (auto data = variant.data()) {
833 if (auto genericElement =
834 std::get_if<std::shared_ptr<ScriptElements::GenericScriptElement>>(&*data)) {
835 (*genericElement)->setKind(DomType::ScriptFormalParameter);
836 }
837 }
838}
839
840void QQmlDomAstCreatorBase::endVisit(AST::FunctionDeclaration *fDef)
841{
842 // Treat nested functions as (named) lambdas instead of Qml Object methods.
843 if (m_nestedFunctionDepth > 1) {
844 endVisit(static_cast<FunctionExpression *>(fDef));
845 return;
846 }
847 --m_nestedFunctionDepth;
848 MethodInfo &m = std::get<MethodInfo>(currentNode().value);
849 const FileLocations::Tree bodyTree =
850 FileLocations::ensure(currentNodeEl().fileLocations, Path().withField(Fields::body));
851 const Path bodyPath = Path().withField(Fields::scriptElement);
852
853 if (!m_enableScriptExpressions)
854 return;
855
856 Q_SCRIPTELEMENT_EXIT_IF(scriptNodeStack.isEmpty() && fDef->body);
857 m.body->setScriptElement(
858 finalizeScriptExpression(prepareBodyForFunction(fDef), bodyPath, bodyTree));
859
860 if (fDef->typeAnnotation) {
861 auto argLoc = FileLocations::ensure(nodeStack.last().fileLocations,
862 Path().withField(Fields::returnType));
863 const Path pathToReturnType = Path().withField(Fields::scriptElement);
864
866 ScriptElementVariant variant = currentScriptNodeEl().takeVariant();
867 finalizeScriptExpression(variant, pathToReturnType, argLoc);
868 m.returnType->setScriptElement(variant);
869 removeCurrentScriptNode({});
870 }
871 if (fDef->formals) {
873 const auto parameterList = scriptNodeStack.takeLast().takeList();
874 const auto &parameterQList = parameterList.qList();
875 size_t size = (size_t)parameterQList.size();
876 for (size_t idx = size - 1; idx < size; --idx) {
877 auto argLoc = FileLocations::ensure(
878 nodeStack.last().fileLocations,
879 Path().withField(Fields::parameters).withIndex(idx).withField(Fields::value));
880 const Path pathToArgument = Path().withField(Fields::scriptElement);
881
882 ScriptElementVariant variant = parameterQList[idx];
883 setFormalParameterKind(variant);
884 finalizeScriptExpression(variant, pathToArgument, argLoc);
885 m.parameters[idx].value->setScriptElement(variant);
886 }
887 }
888
889 // there should be no more uncollected script elements
890 if (m_enableScriptExpressions && !scriptNodeStack.empty()) {
892 }
893}
894
895void QQmlDomAstCreatorBase::endVisit(AST::UiSourceElement *el)
896{
897 if (AST::cast<VariableStatement *>(el->sourceElement))
898 return;
899 MethodInfo &m = std::get<MethodInfo>(currentNode().value);
900 loadAnnotations(el);
901 QmlObject &obj = current<QmlObject>();
902 MethodInfo *mPtr =
903 valueFromMultimap(obj.m_methods, m.name, *nodeStack.last().path.last().headIndex());
904 Q_ASSERT(mPtr);
905 *mPtr = m;
906 removeCurrentNode(DomType::MethodInfo);
907}
908
909bool QQmlDomAstCreatorBase::visit(AST::UiObjectDefinition *el)
910{
911 QmlObject scope;
912 scope.setName(toString(el->qualifiedTypeNameId));
913 scope.addPrototypePath(Paths::lookupTypePath(scope.name()));
914 QmlObject *sPtr = nullptr;
915 Path sPathFromOwner;
916 if (!arrayBindingLevels.isEmpty() && nodeStack.size() == arrayBindingLevels.last()) {
917 if (currentNode().kind == DomType::Binding) {
918 QList<QmlObject> *vals = std::get<Binding>(currentNode().value).arrayValue();
919 if (vals) {
920 int idx = vals->size();
921 vals->append(scope);
922 sPathFromOwner = currentNodeEl().path.withField(Fields::value).withIndex(idx);
923 sPtr = &((*vals)[idx]);
924 sPtr->updatePathFromOwner(sPathFromOwner);
925 } else {
926 Q_ASSERT_X(false, className,
927 "expected an array binding with a valid QList<QmlScope> as value");
928 }
929 } else {
930 Q_ASSERT_X(false, className, "expected an array binding as last node on the stack");
931 }
932 } else {
933 DomValue &containingObject = currentQmlObjectOrComponentEl().item;
934 switch (containingObject.kind) {
936 sPathFromOwner = std::get<QmlComponent>(containingObject.value).addObject(scope, &sPtr);
937 break;
939 sPathFromOwner = std::get<QmlObject>(containingObject.value).addChild(scope, &sPtr);
940 break;
941 default:
942 Q_UNREACHABLE();
943 }
944 Path pathFromContainingObject = sPathFromOwner.mid(currentNodeEl().path.length());
945 FileLocations::Tree fLoc =
946 FileLocations::ensure(currentNodeEl().fileLocations, pathFromContainingObject);
947 FileLocations::addRegion(fLoc, IdentifierRegion,
948 el->qualifiedTypeNameId->identifierToken);
949 }
950 Q_ASSERT_X(sPtr, className, "could not recover new scope");
951
952 if (m_enableScriptExpressions) {
953 auto qmlObjectType = makeGenericScriptElement(el->qualifiedTypeNameId, DomType::ScriptType);
954 qmlObjectType->insertChild(Fields::typeName,
955 fieldMemberExpressionForQualifiedId(el->qualifiedTypeNameId));
957 finalizeScriptExpression(ScriptElementVariant::fromElement(qmlObjectType),
958 sPathFromOwner.withField(Fields::nameIdentifiers), rootMap));
959 }
960 pushEl(sPathFromOwner, *sPtr, el);
961
962 if (el->initializer) {
963 FileLocations::addRegion(nodeStack.last().fileLocations, LeftBraceRegion,
964 el->initializer->lbraceToken);
965 FileLocations::addRegion(nodeStack.last().fileLocations, RightBraceRegion,
966 el->initializer->rbraceToken);
967 }
968 loadAnnotations(el);
969 return true;
970}
971
972void QQmlDomAstCreatorBase::endVisit(AST::UiObjectDefinition *)
973{
974 QmlObject &obj = current<QmlObject>();
975 int idx = currentIndex();
976 if (!arrayBindingLevels.isEmpty() && nodeStack.size() == arrayBindingLevels.last() + 1) {
977 if (currentNode(1).kind == DomType::Binding) {
978 Binding &b = std::get<Binding>(currentNode(1).value);
979 QList<QmlObject> *vals = b.arrayValue();
980 Q_ASSERT_X(vals, className,
981 "expected an array binding with a valid QList<QmlScope> as value");
982 (*vals)[idx] = obj;
983 } else {
984 Q_ASSERT_X(false, className, "expected an array binding as last node on the stack");
985 }
986 } else {
987 DomValue &containingObject = currentNodeEl(1).item;
988 Path p = currentNodeEl().path;
989 switch (containingObject.kind) {
991 if (p[p.length() - 2] == Path::fromField(Fields::objects))
992 std::get<QmlComponent>(containingObject.value).m_objects[idx] = obj;
993 else
994 Q_UNREACHABLE();
995 break;
997 if (p[p.length() - 2] == Path::fromField(Fields::children))
998 std::get<QmlObject>(containingObject.value).m_children[idx] = obj;
999 else
1000 Q_UNREACHABLE();
1001 break;
1002 default:
1003 Q_UNREACHABLE();
1004 }
1005 }
1006 removeCurrentNode(DomType::QmlObject);
1007}
1008
1009void QQmlDomAstCreatorBase::setBindingIdentifiers(const Path &pathFromOwner,
1010 const UiQualifiedId *identifiers, Binding *bindingPtr)
1011{
1012 const bool skipBindingIdentifiers = std::exchange(m_skipBindingIdentifiers, false);
1013 if (!m_enableScriptExpressions || skipBindingIdentifiers)
1014 return;
1015
1016 ScriptElementVariant bindable = fieldMemberExpressionForQualifiedId(identifiers);
1017 bindingPtr->setBindingIdentifiers(finalizeScriptExpression(
1018 bindable, pathFromOwner.withField(Fields::bindingIdentifiers), rootMap));
1019}
1020
1021bool QQmlDomAstCreatorBase::visit(AST::UiObjectBinding *el)
1022{
1023 BindingType bType = (el->hasOnToken ? BindingType::OnBinding : BindingType::Normal);
1024 QmlObject value;
1025 value.setName(toString(el->qualifiedTypeNameId));
1026 Binding *bPtr;
1027 Path bPathFromOwner = current<QmlObject>().addBinding(
1028 Binding(toString(el->qualifiedId), value, bType), AddOption::KeepExisting, &bPtr);
1029 if (bPtr->name() == u"id")
1030 qmlFile.addError(std::move(astParseErrors()
1031 .warning(tr("id attributes should only be a lower case letter "
1032 "followed by letters, numbers or underscore, "
1033 "assuming they refer to an id property"))
1034 .withPath(bPathFromOwner)));
1035 setBindingIdentifiers(bPathFromOwner, el->qualifiedId, bPtr);
1036
1037 pushEl(bPathFromOwner, *bPtr, el);
1038 if (el->hasOnToken)
1039 FileLocations::addRegion(nodeStack.last().fileLocations, OnTokenRegion, el->colonToken);
1040 else
1041 FileLocations::addRegion(nodeStack.last().fileLocations, ColonTokenRegion, el->colonToken);
1042 FileLocations::addRegion(nodeStack.last().fileLocations, IdentifierRegion, combineLocations(el->qualifiedId));
1043 loadAnnotations(el);
1044 QmlObject *objValue = bPtr->objectValue();
1045 Q_ASSERT_X(objValue, className, "could not recover objectValue");
1046 objValue->setName(toString(el->qualifiedTypeNameId));
1047
1048 if (m_enableScriptExpressions) {
1049 auto qmlObjectType = makeGenericScriptElement(el->qualifiedTypeNameId, DomType::ScriptType);
1050 qmlObjectType->insertChild(Fields::typeName,
1051 fieldMemberExpressionForQualifiedId(el->qualifiedTypeNameId));
1052 objValue->setNameIdentifiers(finalizeScriptExpression(
1053 ScriptElementVariant::fromElement(qmlObjectType),
1054 bPathFromOwner.withField(Fields::value).withField(Fields::nameIdentifiers), rootMap));
1055 }
1056
1057 objValue->addPrototypePath(Paths::lookupTypePath(objValue->name()));
1058 pushEl(bPathFromOwner.withField(Fields::value), *objValue, el->initializer);
1059 if (m_enableScriptExpressions && el->initializer) {
1060 FileLocations::addRegion(nodeStack.last().fileLocations, LeftBraceRegion,
1061 el->initializer->lbraceToken);
1062 FileLocations::addRegion(nodeStack.last().fileLocations, RightBraceRegion,
1063 el->initializer->rbraceToken);
1064 }
1065 return true;
1066}
1067
1068void QQmlDomAstCreatorBase::endVisit(AST::UiObjectBinding *)
1069{
1070 QmlObject &objValue = current<QmlObject>();
1071 QmlObject &containingObj = current<QmlObject>(1);
1072 Binding &b = std::get<Binding>(currentNode(1).value);
1073 QmlObject *objPtr = b.objectValue();
1074 Q_ASSERT(objPtr);
1075 *objPtr = objValue;
1076 index_type idx = *currentNodeEl(1).path.last().headIndex();
1077 Binding *bPtr = valueFromMultimap(containingObj.m_bindings, b.name(), idx);
1078 Q_ASSERT(bPtr);
1079 *bPtr = b;
1080 removeCurrentNode(DomType::QmlObject);
1081 removeCurrentNode(DomType::Binding);
1082}
1083
1084bool QQmlDomAstCreatorBase::visit(AST::UiScriptBinding *el)
1085{
1086 ++m_nestedFunctionDepth;
1087 QStringView code = qmlFilePtr->code();
1088 SourceLocation loc = combineLocations(el->statement);
1089 const auto script = std::make_shared<ScriptExpression>(
1090 code.mid(loc.offset, loc.length), qmlFilePtr->engine(), el->statement,
1091 qmlFilePtr->astComments(), ScriptExpression::ExpressionType::BindingExpression, loc);
1092 Binding bindingV(toString(el->qualifiedId), script, BindingType::Normal);
1093 Binding *bindingPtr = nullptr;
1094 Id *idPtr = nullptr;
1095 Path pathFromOwner;
1096 if (bindingV.name() == u"id") {
1097 Node *exp = script->ast();
1098 if (ExpressionStatement *eStat = cast<ExpressionStatement *>(script->ast()))
1099 exp = eStat->expression;
1100 if (IdentifierExpression *iExp = cast<IdentifierExpression *>(exp)) {
1101 QmlStackElement &containingObjectEl = currentEl<QmlObject>();
1102 QmlObject &containingObject = std::get<QmlObject>(containingObjectEl.item.value);
1103 QString idName = iExp->name.toString();
1104 Id idVal(idName, qmlFile.canonicalPath().withPath(containingObject.pathFromOwner()));
1105 idVal.value = script;
1106 containingObject.setIdStr(idName);
1107 FileLocations::addRegion(containingObjectEl.fileLocations, IdTokenRegion,
1108 combineLocations(el->qualifiedId));
1109 FileLocations::addRegion(containingObjectEl.fileLocations, IdColonTokenRegion,
1110 el->colonToken);
1111 FileLocations::addRegion(containingObjectEl.fileLocations, IdNameRegion,
1112 iExp->identifierToken);
1113 QmlComponent &comp = current<QmlComponent>();
1114 pathFromOwner = comp.addId(idVal, AddOption::KeepExisting, &idPtr);
1115 QRegularExpression idRe(QRegularExpression::anchoredPattern(
1116 QStringLiteral(uR"([[:lower:]_][[:lower:][:upper:]0-9_]*)")));
1117 auto m = idRe.matchView(iExp->name);
1118 if (!m.hasMatch()) {
1119 const auto m = "id attributes should only be a lower case letter or an underscore "
1120 "followed by letters, numbers or underscores, not %1";
1121 qmlFile.addError(std::move(
1122 astParseErrors().warning(tr(m).arg(iExp->name)).withPath(pathFromOwner)));
1123 }
1124 } else {
1125 pathFromOwner =
1126 current<QmlObject>().addBinding(bindingV, AddOption::KeepExisting, &bindingPtr);
1127 Q_ASSERT_X(bindingPtr, className, "binding could not be retrieved");
1128 const auto m = "id attributes should only be a lower case letter or an underscore "
1129 "followed by letters, numbers or underscores, not %1 %2, assuming they "
1130 "refer to a property";
1131 qmlFile.addError(std::move(
1132 astParseErrors()
1133 .warning(tr(m).arg(script->code(), script->astRelocatableDump()))
1134 .withPath(pathFromOwner)));
1135 }
1136 } else {
1137 pathFromOwner =
1138 current<QmlObject>().addBinding(bindingV, AddOption::KeepExisting, &bindingPtr);
1139 QmlStackElement &containingObjectEl = currentEl<QmlObject>();
1140 // remove the containingObjectEl.path prefix from pathFromOwner
1141 Path pathFromContainingObject = pathFromOwner.mid(containingObjectEl.path.length());
1142 auto bindingFileLocation =
1143 FileLocations::ensure(containingObjectEl.fileLocations, pathFromContainingObject);
1144 FileLocations::addRegion(bindingFileLocation, IdentifierRegion,
1145 el->qualifiedId->identifierToken);
1146 FileLocations::addRegion(bindingFileLocation, ColonTokenRegion, el->colonToken);
1147
1148 setBindingIdentifiers(pathFromOwner, el->qualifiedId, bindingPtr);
1149
1150 Q_ASSERT_X(bindingPtr, className, "binding could not be retrieved");
1151 }
1152 if (bindingPtr)
1153 pushEl(pathFromOwner, *bindingPtr, el);
1154 else if (idPtr)
1155 pushEl(pathFromOwner, *idPtr, el);
1156 else
1157 Q_UNREACHABLE();
1158 loadAnnotations(el);
1159 // avoid duplicate colon location for id?
1160 FileLocations::addRegion(nodeStack.last().fileLocations, ColonTokenRegion, el->colonToken);
1161 return true;
1162}
1163
1164void QQmlDomAstCreatorBase::setScriptExpression (const std::shared_ptr<ScriptExpression>& value)
1165{
1166 if (m_enableScriptExpressions
1167 && (scriptNodeStack.size() != 1 || currentScriptNodeEl().isList()))
1169 if (m_enableScriptExpressions) {
1170 FileLocations::Tree valueLoc = FileLocations::ensure(currentNodeEl().fileLocations,
1171 Path().withField(Fields::value));
1172 value->setScriptElement(finalizeScriptExpression(currentScriptNodeEl().takeVariant(),
1173 Path().withField(Fields::scriptElement),
1174 valueLoc));
1175 removeCurrentScriptNode({});
1176 }
1177};
1178
1179void QQmlDomAstCreatorBase::endVisit(AST::UiScriptBinding *)
1180{
1181 --m_nestedFunctionDepth;
1182 DomValue &lastEl = currentNode();
1183 index_type idx = currentIndex();
1184 if (lastEl.kind == DomType::Binding) {
1185 Binding &b = std::get<Binding>(lastEl.value);
1186
1187 setScriptExpression(b.scriptExpressionValue());
1188
1189 QmlObject &containingObject = current<QmlObject>();
1190 Binding *bPtr = valueFromMultimap(containingObject.m_bindings, b.name(), idx);
1191 Q_ASSERT(bPtr);
1192 *bPtr = b;
1193 } else if (lastEl.kind == DomType::Id) {
1194 Id &id = std::get<Id>(lastEl.value);
1195
1196 setScriptExpression(id.value);
1197
1198 QmlComponent &comp = current<QmlComponent>();
1199 Id *idPtr = valueFromMultimap(comp.m_ids, id.name, idx);
1200 *idPtr = id;
1201 } else {
1202 Q_UNREACHABLE();
1203 }
1204
1205 // there should be no more uncollected script elements
1206 if (m_enableScriptExpressions && !scriptNodeStack.empty()) {
1208 }
1209 removeCurrentNode({});
1210}
1211
1212bool QQmlDomAstCreatorBase::visit(AST::UiArrayBinding *el)
1213{
1214 QList<QmlObject> value;
1215 Binding bindingV(toString(el->qualifiedId), value, BindingType::Normal);
1216 Binding *bindingPtr;
1217 Path bindingPathFromOwner =
1218 current<QmlObject>().addBinding(bindingV, AddOption::KeepExisting, &bindingPtr);
1219 if (bindingV.name() == u"id")
1220 qmlFile.addError(std::move(
1221 astParseErrors()
1222 .error(tr("id attributes should have only simple strings as values"))
1223 .withPath(bindingPathFromOwner)));
1224
1225 setBindingIdentifiers(bindingPathFromOwner, el->qualifiedId, bindingPtr);
1226
1227 pushEl(bindingPathFromOwner, *bindingPtr, el);
1228 FileLocations::addRegion(currentNodeEl().fileLocations, ColonTokenRegion, el->colonToken);
1229 loadAnnotations(el);
1230 FileLocations::Tree arrayList =
1231 createMap(currentNodeEl().fileLocations, Path::fromField(Fields::value), nullptr);
1232 FileLocations::addRegion(arrayList, LeftBracketRegion, el->lbracketToken);
1233 FileLocations::addRegion(arrayList, RightBracketRegion, el->rbracketToken);
1234 arrayBindingLevels.append(nodeStack.size());
1235 return true;
1236}
1237
1238void QQmlDomAstCreatorBase::endVisit(AST::UiArrayBinding *)
1239{
1240 index_type idx = currentIndex();
1241 Binding &b = std::get<Binding>(currentNode().value);
1242 Binding *bPtr = valueFromMultimap(current<QmlObject>().m_bindings, b.name(), idx);
1243 *bPtr = b;
1244 arrayBindingLevels.removeLast();
1245 removeCurrentNode(DomType::Binding);
1246}
1247
1248void QQmlDomAstCreatorBase::endVisit(AST::ArgumentList *list)
1249{
1250 endVisitForLists(list);
1251}
1252
1253bool QQmlDomAstCreatorBase::visit(AST::UiParameterList *)
1254{
1255 return false; // do not create script node for Ui stuff
1256}
1257
1258void QQmlDomAstCreatorBase::endVisit(AST::PatternElementList *list)
1259{
1260 endVisitForLists<AST::PatternElementList>(list, [](AST::PatternElementList *current) {
1261 int toCollect = 0;
1262 toCollect += bool(current->elision);
1263 toCollect += bool(current->element);
1264 return toCollect;
1265 });
1266}
1267
1268void QQmlDomAstCreatorBase::endVisit(AST::PatternPropertyList *list)
1269{
1270 endVisitForLists(list);
1271}
1272
1273/*!
1274 \internal
1275 Implementing the logic of this method in \c QQmlDomAstCreator::visit(AST::UiQualifiedId *)
1276 would create scriptelements at places where there are not needed. This is mainly because
1277 UiQualifiedId's appears inside and outside of script parts.
1278*/
1279ScriptElementVariant QQmlDomAstCreatorBase::scriptElementForQualifiedId(AST::UiQualifiedId *expression)
1280{
1281 auto id = std::make_shared<ScriptElements::IdentifierExpression>(
1282 expression->firstSourceLocation(), expression->lastSourceLocation());
1283 id->setName(expression->toString());
1284
1285 return ScriptElementVariant::fromElement(id);
1286}
1287
1288bool QQmlDomAstCreatorBase::visit(AST::UiQualifiedId *)
1289{
1290 if (!m_enableScriptExpressions)
1291 return false;
1292
1293 return false;
1294}
1295
1296bool QQmlDomAstCreatorBase::visit(AST::UiEnumDeclaration *el)
1297{
1298 EnumDecl eDecl;
1299 eDecl.setName(el->name.toString());
1300 EnumDecl *ePtr;
1301 Path enumPathFromOwner =
1302 current<QmlComponent>().addEnumeration(eDecl, AddOption::KeepExisting, &ePtr);
1303 pushEl(enumPathFromOwner, *ePtr, el);
1304 FileLocations::addRegion(nodeStack.last().fileLocations, EnumKeywordRegion, el->enumToken);
1305 FileLocations::addRegion(nodeStack.last().fileLocations, IdentifierRegion, el->identifierToken);
1306 FileLocations::addRegion(nodeStack.last().fileLocations, LeftBraceRegion, el->lbraceToken);
1307 FileLocations::addRegion(nodeStack.last().fileLocations, RightBraceRegion, el->rbraceToken);
1308 loadAnnotations(el);
1309 return true;
1310}
1311
1312void QQmlDomAstCreatorBase::endVisit(AST::UiEnumDeclaration *)
1313{
1314 EnumDecl &e = std::get<EnumDecl>(currentNode().value);
1315 EnumDecl *ePtr =
1316 valueFromMultimap(current<QmlComponent>().m_enumerations, e.name(), currentIndex());
1317 Q_ASSERT(ePtr);
1318 *ePtr = e;
1319 removeCurrentNode(DomType::EnumDecl);
1320}
1321
1322bool QQmlDomAstCreatorBase::visit(AST::UiEnumMemberList *el)
1323{
1324 EnumItem it(el->member.toString(), el->value,
1325 el->valueToken.isValid() ? EnumItem::ValueKind::ExplicitValue
1327 EnumDecl &eDecl = std::get<EnumDecl>(currentNode().value);
1328 Path itPathFromDecl = eDecl.addValue(it);
1329 const auto map = createMap(DomType::EnumItem, itPathFromDecl, nullptr);
1330 if (el->commaToken.isValid())
1331 FileLocations::addRegion(map, CommaTokenRegion, el->commaToken);
1332 if (el->memberToken.isValid())
1333 FileLocations::addRegion(map, IdentifierRegion, el->memberToken);
1334 if (el->equalToken.isValid())
1335 FileLocations::addRegion(map, EqualTokenRegion, el->equalToken);
1336 if (el->valueToken.isValid())
1337 FileLocations::addRegion(map, EnumValueRegion, el->valueToken);
1339 map, MainRegion, combine(combine(el->memberToken, el->commaToken), el->valueToken));
1340 return true;
1341}
1342
1343void QQmlDomAstCreatorBase::endVisit(AST::UiEnumMemberList *el)
1344{
1345 Node::accept(el->next, this); // put other enum members at the same level as this one...
1346}
1347
1348bool QQmlDomAstCreatorBase::visit(AST::UiInlineComponent *el)
1349{
1350 QStringList els = current<QmlComponent>().name().split(QLatin1Char('.'));
1351 els.append(el->name.toString());
1352 QString cName = els.join(QLatin1Char('.'));
1353 QmlComponent *compPtr;
1354 Path p = qmlFilePtr->addComponent(QmlComponent(cName), AddOption::KeepExisting, &compPtr);
1355
1356 if (m_enableScriptExpressions) {
1357 auto inlineComponentType =
1358 makeGenericScriptElement(el->identifierToken, DomType::ScriptType);
1359
1360 auto typeName = std::make_shared<ScriptElements::IdentifierExpression>(el->identifierToken);
1361 typeName->setName(el->name);
1362 inlineComponentType->insertChild(Fields::typeName,
1363 ScriptElementVariant::fromElement(typeName));
1365 finalizeScriptExpression(ScriptElementVariant::fromElement(inlineComponentType),
1366 p.withField(Fields::nameIdentifiers), rootMap));
1367 }
1368
1369 pushEl(p, *compPtr, el);
1370 FileLocations::addRegion(nodeStack.last().fileLocations, ComponentKeywordRegion,
1371 el->componentToken);
1372 FileLocations::addRegion(nodeStack.last().fileLocations, IdentifierRegion, el->identifierToken);
1373 loadAnnotations(el);
1374 return true;
1375}
1376
1377void QQmlDomAstCreatorBase::endVisit(AST::UiInlineComponent *)
1378{
1379 QmlComponent &component = std::get<QmlComponent>(currentNode().value);
1380 QStringList nameEls = component.name().split(QChar::fromLatin1('.'));
1381 QString key = nameEls.mid(1).join(QChar::fromLatin1('.'));
1382 QmlComponent *cPtr = valueFromMultimap(qmlFilePtr->lazyMembers().m_components, key, currentIndex());
1383 Q_ASSERT(cPtr);
1384 *cPtr = component;
1385 removeCurrentNode(DomType::QmlComponent);
1386}
1387
1388bool QQmlDomAstCreatorBase::visit(UiRequired *el)
1389{
1390 PropertyDefinition pDef;
1391 pDef.name = el->name.toString();
1392 pDef.isRequired = true;
1393 PropertyDefinition *pDefPtr;
1394 Path pathFromOwner =
1395 current<QmlObject>().addPropertyDef(pDef, AddOption::KeepExisting, &pDefPtr);
1396 createMap(DomType::PropertyDefinition, pathFromOwner, el);
1397 return false;
1398}
1399
1400bool QQmlDomAstCreatorBase::visit(AST::UiAnnotation *el)
1401{
1402 QmlObject a;
1403 a.setName(QStringLiteral(u"@") + toString(el->qualifiedTypeNameId));
1404 // add annotation prototype?
1405 DomValue &containingElement = currentNode();
1406 Path pathFromOwner;
1407 QmlObject *aPtr = nullptr;
1408 switch (containingElement.kind) {
1409 case DomType::QmlObject:
1410 pathFromOwner = std::get<QmlObject>(containingElement.value).addAnnotation(a, &aPtr);
1411 break;
1412 case DomType::Binding:
1413 pathFromOwner = std::get<Binding>(containingElement.value)
1414 .addAnnotation(currentNodeEl().path, a, &aPtr);
1415 break;
1416 case DomType::Id:
1417 pathFromOwner =
1418 std::get<Id>(containingElement.value).addAnnotation(currentNodeEl().path, a, &aPtr);
1419 break;
1421 pathFromOwner = std::get<PropertyDefinition>(containingElement.value)
1422 .addAnnotation(currentNodeEl().path, a, &aPtr);
1423 break;
1425 pathFromOwner = std::get<MethodInfo>(containingElement.value)
1426 .addAnnotation(currentNodeEl().path, a, &aPtr);
1427 break;
1428 default:
1429 qCWarning(domLog) << "Unexpected container object for annotation:"
1430 << domTypeToString(containingElement.kind);
1431 Q_UNREACHABLE();
1432 }
1433 pushEl(pathFromOwner, *aPtr, el);
1434 return true;
1435}
1436
1437void QQmlDomAstCreatorBase::endVisit(AST::UiAnnotation *)
1438{
1439 DomValue &containingElement = currentNode(1);
1440 Path pathFromOwner;
1441 QmlObject &a = std::get<QmlObject>(currentNode().value);
1442 switch (containingElement.kind) {
1443 case DomType::QmlObject:
1444 std::get<QmlObject>(containingElement.value).m_annotations[currentIndex()] = a;
1445 break;
1446 case DomType::Binding:
1447 std::get<Binding>(containingElement.value).m_annotations[currentIndex()] = a;
1448 break;
1449 case DomType::Id:
1450 std::get<Id>(containingElement.value).annotations[currentIndex()] = a;
1451 break;
1452 case DomType::PropertyDefinition:
1453 std::get<PropertyDefinition>(containingElement.value).annotations[currentIndex()] = a;
1454 break;
1455 case DomType::MethodInfo:
1456 std::get<MethodInfo>(containingElement.value).annotations[currentIndex()] = a;
1457 break;
1458 default:
1459 Q_UNREACHABLE();
1460 }
1461 removeCurrentNode(DomType::QmlObject);
1462}
1463
1465{
1466 qmlFile.addError(astParseErrors().error(
1467 tr("Maximum statement or expression depth exceeded in QmlDomAstCreator")));
1468}
1469
1470void QQmlDomAstCreatorBase::endVisit(AST::StatementList *list)
1471{
1472 endVisitForLists(list);
1473}
1474
1475bool QQmlDomAstCreatorBase::visit(AST::BinaryExpression *)
1476{
1477 if (!m_enableScriptExpressions)
1478 return false;
1479
1480 return true;
1481}
1482
1483void QQmlDomAstCreatorBase::endVisit(AST::BinaryExpression *exp)
1484{
1485 if (!m_enableScriptExpressions)
1486 return;
1487
1488 auto current = makeScriptElement<ScriptElements::BinaryExpression>(exp);
1489 current->addLocation(OperatorTokenRegion, exp->operatorToken);
1491 current->setRight(currentScriptNodeEl().takeVariant());
1492 removeCurrentScriptNode({});
1494 current->setLeft(currentScriptNodeEl().takeVariant());
1495 removeCurrentScriptNode({});
1496
1497 pushScriptElement(current);
1498}
1499
1500bool QQmlDomAstCreatorBase::visit(AST::Block *)
1501{
1502 if (!m_enableScriptExpressions)
1503 return false;
1504
1505 return true;
1506}
1507
1508void QQmlDomAstCreatorBase::endVisit(AST::Block *block)
1509{
1510 if (!m_enableScriptExpressions)
1511 return;
1512
1513 auto current = makeScriptElement<ScriptElements::BlockStatement>(block);
1514
1515 if (block->statements) {
1517 current->setStatements(currentScriptNodeEl().takeList());
1518 removeCurrentScriptNode(DomType::List);
1519 }
1520
1521 pushScriptElement(current);
1522}
1523
1524bool QQmlDomAstCreatorBase::visit(AST::ForStatement *)
1525{
1526 if (!m_enableScriptExpressions)
1527 return false;
1528
1529 return true;
1530}
1531
1532void QQmlDomAstCreatorBase::endVisit(AST::ForStatement *forStatement)
1533{
1534 if (!m_enableScriptExpressions)
1535 return;
1536
1537 auto current = makeScriptElement<ScriptElements::ForStatement>(forStatement);
1538 current->addLocation(FileLocationRegion::ForKeywordRegion, forStatement->forToken);
1539 current->addLocation(FileLocationRegion::LeftParenthesisRegion, forStatement->lparenToken);
1540 current->addLocation(FileLocationRegion::FirstSemicolonTokenRegion,
1541 forStatement->firstSemicolonToken);
1542 current->addLocation(FileLocationRegion::SecondSemicolonRegion,
1543 forStatement->secondSemicolonToken);
1544 current->addLocation(FileLocationRegion::RightParenthesisRegion, forStatement->rparenToken);
1545
1546 if (forStatement->statement) {
1548 current->setBody(currentScriptNodeEl().takeVariant());
1549 removeCurrentScriptNode(std::nullopt);
1550 }
1551
1552 if (forStatement->expression) {
1554 current->setExpression(currentScriptNodeEl().takeVariant());
1555 removeCurrentScriptNode(std::nullopt);
1556 }
1557
1558 if (forStatement->condition) {
1560 current->setCondition(currentScriptNodeEl().takeVariant());
1561 removeCurrentScriptNode(std::nullopt);
1562 }
1563
1564 if (forStatement->declarations) {
1566 auto variableDeclaration = makeGenericScriptElement(forStatement->declarations,
1568
1569 ScriptElements::ScriptList list = currentScriptNodeEl().takeList();
1572 variableDeclaration->insertChild(Fields::declarations, std::move(list));
1573 removeCurrentScriptNode({});
1574
1575 current->setDeclarations(ScriptElementVariant::fromElement(variableDeclaration));
1576
1577 if (auto pe = forStatement->declarations->declaration;
1578 pe && pe->declarationKindToken.isValid()) {
1579 current->addLocation(FileLocationRegion::TypeIdentifierRegion,
1580 pe->declarationKindToken);
1581 }
1582 }
1583
1584 if (forStatement->initialiser) {
1586 current->setInitializer(currentScriptNodeEl().takeVariant());
1587 removeCurrentScriptNode(std::nullopt);
1588 }
1589 pushScriptElement(current);
1590}
1591
1592bool QQmlDomAstCreatorBase::visit(AST::IdentifierExpression *expression)
1593{
1594 if (!m_enableScriptExpressions)
1595 return false;
1596
1597 auto current = makeScriptElement<ScriptElements::IdentifierExpression>(expression);
1598 current->setName(expression->name);
1599 pushScriptElement(current);
1600 return true;
1601}
1602
1603bool QQmlDomAstCreatorBase::visit(AST::NumericLiteral *expression)
1604{
1605 if (!m_enableScriptExpressions)
1606 return false;
1607
1608 auto current = makeScriptElement<ScriptElements::Literal>(expression);
1609 current->setLiteralValue(expression->value);
1610 pushScriptElement(current);
1611 return true;
1612}
1613
1614bool QQmlDomAstCreatorBase::visit(AST::StringLiteral *expression)
1615{
1616 if (!m_enableScriptExpressions)
1617 return false;
1618
1619 pushScriptElement(makeStringLiteral(expression->value, expression));
1620 return true;
1621}
1622
1623bool QQmlDomAstCreatorBase::visit(AST::NullExpression *expression)
1624{
1625 if (!m_enableScriptExpressions)
1626 return false;
1627
1628 auto current = makeScriptElement<ScriptElements::Literal>(expression);
1629 current->setLiteralValue(nullptr);
1630 pushScriptElement(current);
1631 return true;
1632}
1633
1634bool QQmlDomAstCreatorBase::visit(AST::TrueLiteral *expression)
1635{
1636 if (!m_enableScriptExpressions)
1637 return false;
1638
1639 auto current = makeScriptElement<ScriptElements::Literal>(expression);
1640 current->setLiteralValue(true);
1641 pushScriptElement(current);
1642 return true;
1643}
1644
1645bool QQmlDomAstCreatorBase::visit(AST::FalseLiteral *expression)
1646{
1647 if (!m_enableScriptExpressions)
1648 return false;
1649
1650 auto current = makeScriptElement<ScriptElements::Literal>(expression);
1651 current->setLiteralValue(false);
1652 pushScriptElement(current);
1653 return true;
1654}
1655
1656bool QQmlDomAstCreatorBase::visit(AST::IdentifierPropertyName *expression)
1657{
1658 if (!m_enableScriptExpressions)
1659 return false;
1660
1661 auto current = makeScriptElement<ScriptElements::IdentifierExpression>(expression);
1662 current->setName(expression->id);
1663 pushScriptElement(current);
1664 return true;
1665}
1666
1667bool QQmlDomAstCreatorBase::visit(AST::StringLiteralPropertyName *expression)
1668{
1669 if (!m_enableScriptExpressions)
1670 return false;
1671
1672 pushScriptElement(makeStringLiteral(expression->id, expression));
1673 return true;
1674}
1675
1676bool QQmlDomAstCreatorBase::visit(AST::TypeAnnotation *)
1677{
1678 if (!m_enableScriptExpressions)
1679 return false;
1680
1681 // do nothing: the work is done in (end)visit(AST::Type*).
1682 return true;
1683}
1684
1685bool QQmlDomAstCreatorBase::visit(AST::RegExpLiteral *literal)
1686{
1687 if (!m_enableScriptExpressions)
1688 return false;
1689
1690 auto current = makeGenericScriptElement(literal, DomType::ScriptRegExpLiteral);
1691 current->insertValue(Fields::regExpPattern, literal->pattern);
1692 current->insertValue(Fields::regExpFlags, literal->flags);
1693 pushScriptElement(current);
1694
1695 return true;
1696}
1697
1698bool QQmlDomAstCreatorBase::visit(AST::ThisExpression *expression)
1699{
1700 if (!m_enableScriptExpressions)
1701 return false;
1702
1703 auto current = makeGenericScriptElement(expression, DomType::ScriptThisExpression);
1704 if (expression->thisToken.isValid())
1705 current->addLocation(ThisKeywordRegion, expression->thisToken);
1706 pushScriptElement(current);
1707 return true;
1708}
1709
1710bool QQmlDomAstCreatorBase::visit(AST::SuperLiteral *expression)
1711{
1712 if (!m_enableScriptExpressions)
1713 return false;
1714
1715 auto current = makeGenericScriptElement(expression, DomType::ScriptSuperLiteral);
1716 if (expression->superToken.isValid())
1717 current->addLocation(SuperKeywordRegion, expression->superToken);
1718 pushScriptElement(current);
1719 return true;
1720}
1721
1722bool QQmlDomAstCreatorBase::visit(AST::NumericLiteralPropertyName *expression)
1723{
1724 if (!m_enableScriptExpressions)
1725 return false;
1726
1727 auto current = makeScriptElement<ScriptElements::Literal>(expression);
1728 current->setLiteralValue(expression->id);
1729 pushScriptElement(current);
1730 return true;
1731}
1732
1733bool QQmlDomAstCreatorBase::visit(AST::ComputedPropertyName *)
1734{
1735 if (!m_enableScriptExpressions)
1736 return false;
1737
1738 // nothing to do, just forward the underlying expression without changing/wrapping it
1739 return true;
1740}
1741
1742template<typename T>
1743void QQmlDomAstCreatorBase::endVisitForLists(T *list,
1744 const std::function<int(T *)> &scriptElementsPerEntry)
1745{
1746 if (!m_enableScriptExpressions)
1747 return;
1748
1749 auto current = makeScriptList(list);
1750 for (auto it = list; it; it = it->next) {
1751 const int entriesToCollect = scriptElementsPerEntry ? scriptElementsPerEntry(it) : 1;
1752 for (int i = 0; i < entriesToCollect; ++i) {
1753 Q_SCRIPTELEMENT_EXIT_IF(scriptNodeStack.isEmpty());
1754 auto last = scriptNodeStack.takeLast();
1755 if (last.isList())
1756 current.append(last.takeList());
1757 else
1758 current.append(last.takeVariant());
1759 }
1760 }
1761
1762 current.reverse();
1763 pushScriptElement(current);
1764}
1765
1766void QQmlDomAstCreatorBase::endVisit(AST::VariableDeclarationList *list)
1767{
1768 endVisitForLists(list);
1769}
1770
1771bool QQmlDomAstCreatorBase::visit(AST::Elision *list)
1772{
1773 if (!m_enableScriptExpressions)
1774 return false;
1775
1776 auto currentList = makeScriptList(list);
1777
1778 for (auto it = list; it; it = it->next) {
1779 auto current = makeGenericScriptElement(it->commaToken, DomType::ScriptElision);
1780 currentList.append(ScriptElementVariant::fromElement(current));
1781 }
1782 pushScriptElement(currentList);
1783
1784 return false; // return false because we already iterated over the children using the custom
1785 // iteration above
1786}
1787
1788bool QQmlDomAstCreatorBase::visit(AST::PatternElement *)
1789{
1790 if (!m_enableScriptExpressions)
1791 return false;
1792
1793 return true;
1794}
1795
1796/*!
1797 \internal
1798 Avoid code-duplication, reuse this code when doing endVisit on types inheriting from
1799 AST::PatternElement.
1800*/
1802 AST::PatternElement *pe,
1803 const std::shared_ptr<ScriptElements::GenericScriptElement> &current)
1804{
1805 if (pe->equalToken.isValid())
1806 current->addLocation(FileLocationRegion::EqualTokenRegion, pe->equalToken);
1807
1808 if (pe->identifierToken.isValid() && !pe->bindingIdentifier.isEmpty()) {
1809 auto identifier =
1810 std::make_shared<ScriptElements::IdentifierExpression>(pe->identifierToken);
1811 identifier->setName(pe->bindingIdentifier);
1812 current->insertChild(Fields::identifier, ScriptElementVariant::fromElement(identifier));
1813 }
1814 if (pe->initializer) {
1816 current->insertChild(Fields::initializer, scriptNodeStack.last().takeVariant());
1817 scriptNodeStack.removeLast();
1818 }
1819 if (pe->typeAnnotation) {
1821 current->insertChild(Fields::type, scriptNodeStack.last().takeVariant());
1822 scriptNodeStack.removeLast();
1823 }
1824 if (pe->bindingTarget) {
1826 current->insertChild(Fields::bindingElement, scriptNodeStack.last().takeVariant());
1827 scriptNodeStack.removeLast();
1828 }
1829}
1830
1831void QQmlDomAstCreatorBase::endVisit(AST::PatternElement *pe)
1832{
1833 if (!m_enableScriptExpressions)
1834 return;
1835
1836 auto element = makeGenericScriptElement(pe, DomType::ScriptPattern);
1837 endVisitHelper(pe, element);
1838 // check if helper disabled scriptexpressions
1839 if (!m_enableScriptExpressions)
1840 return;
1841
1842 pushScriptElement(element);
1843}
1844
1845bool QQmlDomAstCreatorBase::visit(AST::IfStatement *)
1846{
1847 if (!m_enableScriptExpressions)
1848 return false;
1849
1850 return true;
1851}
1852
1853void QQmlDomAstCreatorBase::endVisit(AST::IfStatement *ifStatement)
1854{
1855 if (!m_enableScriptExpressions)
1856 return;
1857
1858 auto current = makeScriptElement<ScriptElements::IfStatement>(ifStatement);
1859 current->addLocation(LeftParenthesisRegion, ifStatement->lparenToken);
1860 current->addLocation(RightParenthesisRegion, ifStatement->rparenToken);
1861 current->addLocation(ElseKeywordRegion, ifStatement->elseToken);
1862 current->addLocation(IfKeywordRegion, ifStatement->ifToken);
1863
1864 if (ifStatement->ko) {
1866 current->setAlternative(scriptNodeStack.last().takeVariant());
1867 scriptNodeStack.removeLast();
1868 }
1869
1870 if (ifStatement->ok) {
1872 current->setConsequence(scriptNodeStack.last().takeVariant());
1873 scriptNodeStack.removeLast();
1874 }
1875 if (ifStatement->expression) {
1877 current->setCondition(scriptNodeStack.last().takeVariant());
1878 scriptNodeStack.removeLast();
1879 }
1880
1881 pushScriptElement(current);
1882}
1883
1884bool QQmlDomAstCreatorBase::visit(AST::ReturnStatement *)
1885{
1886 if (!m_enableScriptExpressions)
1887 return false;
1888
1889 return true;
1890}
1891
1892void QQmlDomAstCreatorBase::endVisit(AST::ReturnStatement *returnStatement)
1893{
1894 if (!m_enableScriptExpressions)
1895 return;
1896
1897 auto current = makeScriptElement<ScriptElements::ReturnStatement>(returnStatement);
1898 current->addLocation(ReturnKeywordRegion, returnStatement->returnToken);
1899
1900 if (returnStatement->expression) {
1902 current->setExpression(currentScriptNodeEl().takeVariant());
1903 removeCurrentScriptNode({});
1904 }
1905
1906 pushScriptElement(current);
1907}
1908
1909bool QQmlDomAstCreatorBase::visit(AST::YieldExpression *)
1910{
1911 if (!m_enableScriptExpressions)
1912 return false;
1913
1914 return true;
1915}
1916
1917void QQmlDomAstCreatorBase::endVisit(AST::YieldExpression *yExpression)
1918{
1919 if (!m_enableScriptExpressions)
1920 return;
1921
1922 auto current = makeGenericScriptElement(yExpression, DomType::ScriptYieldExpression);
1923 current->addLocation(YieldKeywordRegion, yExpression->yieldToken);
1924
1925 if (yExpression->expression) {
1927 current->insertChild(Fields::expression, currentScriptNodeEl().takeVariant());
1928 removeCurrentScriptNode({});
1929 }
1930
1931 pushScriptElement(current);
1932}
1933
1934bool QQmlDomAstCreatorBase::visit(AST::FieldMemberExpression *)
1935{
1936 if (!m_enableScriptExpressions)
1937 return false;
1938
1939 return true;
1940}
1941
1942void QQmlDomAstCreatorBase::endVisit(AST::FieldMemberExpression *expression)
1943{
1944 if (!m_enableScriptExpressions)
1945 return;
1946
1947 auto current = makeScriptElement<ScriptElements::BinaryExpression>(expression);
1949 current->addLocation(FileLocationRegion::OperatorTokenRegion, expression->dotToken);
1950
1951 if (expression->base) {
1953 current->setLeft(currentScriptNodeEl().takeVariant());
1954 removeCurrentScriptNode({});
1955 }
1956
1957 auto scriptIdentifier =
1958 std::make_shared<ScriptElements::IdentifierExpression>(expression->identifierToken);
1959 scriptIdentifier->setName(expression->name);
1960 current->setRight(ScriptElementVariant::fromElement(scriptIdentifier));
1961
1962 pushScriptElement(current);
1963}
1964
1965bool QQmlDomAstCreatorBase::visit(AST::ArrayMemberExpression *)
1966{
1967 if (!m_enableScriptExpressions)
1968 return false;
1969
1970 return true;
1971}
1972
1973void QQmlDomAstCreatorBase::endVisit(AST::ArrayMemberExpression *expression)
1974{
1975 if (!m_enableScriptExpressions)
1976 return;
1977
1978 auto current = makeScriptElement<ScriptElements::BinaryExpression>(expression);
1980 current->addLocation(FileLocationRegion::OperatorTokenRegion, expression->lbracketToken);
1981
1982 if (expression->expression) {
1984 // if scriptNodeStack.last() is fieldmember expression, add expression to it instead of
1985 // creating new one
1986 current->setRight(currentScriptNodeEl().takeVariant());
1987 removeCurrentScriptNode({});
1988 }
1989
1990 if (expression->base) {
1992 current->setLeft(currentScriptNodeEl().takeVariant());
1993 removeCurrentScriptNode({});
1994 }
1995
1996 pushScriptElement(current);
1997}
1998
1999bool QQmlDomAstCreatorBase::visit(AST::CallExpression *)
2000{
2001 if (!m_enableScriptExpressions)
2002 return false;
2003
2004 return true;
2005}
2006
2007void QQmlDomAstCreatorBase::endVisit(AST::CallExpression *exp)
2008{
2009 if (!m_enableScriptExpressions)
2010 return;
2011
2012 auto current = makeGenericScriptElement(exp, DomType::ScriptCallExpression);
2013 current->addLocation(LeftParenthesisRegion, exp->lparenToken);
2014 current->addLocation(RightParenthesisRegion, exp->rparenToken);
2015
2016 if (exp->arguments) {
2018 current->insertChild(Fields::arguments, currentScriptNodeEl().takeList());
2019 removeCurrentScriptNode({});
2020 } else {
2021 // insert empty list
2022 current->insertChild(Fields::arguments,
2023 ScriptElements::ScriptList(exp->lparenToken, exp->rparenToken));
2024 }
2025
2026 if (exp->base) {
2028 current->insertChild(Fields::callee, currentScriptNodeEl().takeVariant());
2029 removeCurrentScriptNode({});
2030 }
2031
2032 pushScriptElement(current);
2033}
2034
2035bool QQmlDomAstCreatorBase::visit(AST::ArrayPattern *)
2036{
2037 if (!m_enableScriptExpressions)
2038 return false;
2039
2040 return true;
2041}
2042
2043void QQmlDomAstCreatorBase::endVisit(AST::ArrayPattern *exp)
2044{
2045 if (!m_enableScriptExpressions)
2046 return;
2047
2048 auto current = makeGenericScriptElement(exp, DomType::ScriptArray);
2049
2050 if (exp->elements) {
2052 ScriptElements::ScriptList list = currentScriptNodeEl().takeList();
2054 current->insertChild(Fields::elements, std::move(list));
2055
2056 removeCurrentScriptNode({});
2057 } else {
2058 // insert empty list
2059 current->insertChild(Fields::elements,
2060 ScriptElements::ScriptList(exp->lbracketToken, exp->rbracketToken));
2061 }
2062
2063 pushScriptElement(current);
2064}
2065
2066bool QQmlDomAstCreatorBase::visit(AST::ObjectPattern *)
2067{
2068 if (!m_enableScriptExpressions)
2069 return false;
2070
2071 return true;
2072}
2073
2074void QQmlDomAstCreatorBase::endVisit(AST::ObjectPattern *exp)
2075{
2076 if (!m_enableScriptExpressions)
2077 return;
2078
2079 auto current = makeGenericScriptElement(exp, DomType::ScriptObject);
2080
2081 if (exp->properties) {
2083 current->insertChild(Fields::properties, currentScriptNodeEl().takeList());
2084 removeCurrentScriptNode({});
2085 } else {
2086 // insert empty list
2087 current->insertChild(Fields::properties,
2088 ScriptElements::ScriptList(exp->lbraceToken, exp->rbraceToken));
2089 }
2090
2091 pushScriptElement(current);
2092}
2093
2094bool QQmlDomAstCreatorBase::visit(AST::PatternProperty *)
2095{
2096 if (!m_enableScriptExpressions)
2097 return false;
2098
2099 return true;
2100}
2101
2102void QQmlDomAstCreatorBase::endVisit(AST::PatternProperty *exp)
2103{
2104 if (!m_enableScriptExpressions)
2105 return;
2106
2107 auto current = makeGenericScriptElement(exp, DomType::ScriptProperty);
2108
2109 // handle the stuff from PatternProperty's base class PatternElement
2110 endVisitHelper(static_cast<PatternElement *>(exp), current);
2111
2112 // check if helper disabled scriptexpressions
2113 if (!m_enableScriptExpressions)
2114 return;
2115
2116 if (exp->name) {
2118 current->insertChild(Fields::name, currentScriptNodeEl().takeVariant());
2119 removeCurrentScriptNode({});
2120 }
2121
2122 pushScriptElement(current);
2123}
2124
2125bool QQmlDomAstCreatorBase::visit(AST::VariableStatement *)
2126{
2127 if (!m_enableScriptExpressions)
2128 return false;
2129
2130 return true;
2131}
2132
2133void QQmlDomAstCreatorBase::endVisit(AST::VariableStatement *statement)
2134{
2135 if (!m_enableScriptExpressions)
2136 return;
2137
2138 auto current = makeGenericScriptElement(statement, DomType::ScriptVariableDeclaration);
2139 current->addLocation(FileLocationRegion::TypeIdentifierRegion, statement->declarationKindToken);
2140
2141 if (statement->declarations) {
2143
2144 ScriptElements::ScriptList list = currentScriptNodeEl().takeList();
2147 current->insertChild(Fields::declarations, std::move(list));
2148
2149 removeCurrentScriptNode({});
2150 }
2151
2152 pushScriptElement(current);
2153}
2154
2155bool QQmlDomAstCreatorBase::visit(AST::Type *)
2156{
2157 if (!m_enableScriptExpressions)
2158 return false;
2159
2160 return true;
2161}
2162
2163void QQmlDomAstCreatorBase::endVisit(AST::Type *exp)
2164{
2165 if (!m_enableScriptExpressions)
2166 return;
2167
2168 auto current = makeGenericScriptElement(exp, DomType::ScriptType);
2169
2170 if (exp->typeArgument) {
2171 current->insertChild(Fields::typeArgumentName,
2172 fieldMemberExpressionForQualifiedId(exp->typeArgument));
2173 current->addLocation(FileLocationRegion::IdentifierRegion, combineLocations(exp->typeArgument));
2174 }
2175
2176 if (exp->typeId) {
2177 current->insertChild(Fields::typeName, fieldMemberExpressionForQualifiedId(exp->typeId));
2178 current->addLocation(FileLocationRegion::TypeIdentifierRegion, combineLocations(exp->typeId));
2179 }
2180
2181 pushScriptElement(current);
2182}
2183
2184bool QQmlDomAstCreatorBase::visit(AST::DefaultClause *)
2185{
2186 if (!m_enableScriptExpressions)
2187 return false;
2188
2189 return true;
2190}
2191
2192void QQmlDomAstCreatorBase::endVisit(AST::DefaultClause *exp)
2193{
2194 if (!m_enableScriptExpressions)
2195 return;
2196
2197 auto current = makeGenericScriptElement(exp, DomType::ScriptDefaultClause);
2198 current->addLocation(DefaultKeywordRegion, exp->defaultToken);
2199 current->addLocation(ColonTokenRegion, exp->colonToken);
2200
2201 if (exp->statements) {
2203 current->insertChild(Fields::statements, currentScriptNodeEl().takeList());
2204 removeCurrentScriptNode({});
2205 }
2206
2207 pushScriptElement(current);
2208}
2209
2210bool QQmlDomAstCreatorBase::visit(AST::CaseClause *)
2211{
2212 if (!m_enableScriptExpressions)
2213 return false;
2214
2215 return true;
2216}
2217
2218void QQmlDomAstCreatorBase::endVisit(AST::CaseClause *exp)
2219{
2220 if (!m_enableScriptExpressions)
2221 return;
2222
2223 auto current = makeGenericScriptElement(exp, DomType::ScriptCaseClause);
2224 current->addLocation(FileLocationRegion::CaseKeywordRegion, exp->caseToken);
2225 current->addLocation(FileLocationRegion::ColonTokenRegion, exp->colonToken);
2226
2227 if (exp->statements) {
2229 current->insertChild(Fields::statements, currentScriptNodeEl().takeList());
2230 removeCurrentScriptNode({});
2231 }
2232
2233 if (exp->expression) {
2235 current->insertChild(Fields::expression, currentScriptNodeEl().takeVariant());
2236 removeCurrentScriptNode({});
2237 }
2238
2239 pushScriptElement(current);
2240}
2241
2242bool QQmlDomAstCreatorBase::visit(AST::CaseClauses *)
2243{
2244 if (!m_enableScriptExpressions)
2245 return false;
2246
2247 return true;
2248}
2249
2250void QQmlDomAstCreatorBase::endVisit(AST::CaseClauses *list)
2251{
2252 if (!m_enableScriptExpressions)
2253 return;
2254
2255 auto current = makeScriptList(list);
2256
2257 for (auto it = list; it; it = it->next) {
2259 current.append(scriptNodeStack.takeLast().takeVariant());
2260 }
2261
2262 current.reverse();
2263 pushScriptElement(current);
2264}
2265
2266bool QQmlDomAstCreatorBase::visit(AST::CaseBlock *)
2267{
2268 if (!m_enableScriptExpressions)
2269 return false;
2270
2271 return true;
2272}
2273
2274void QQmlDomAstCreatorBase::endVisit(AST::CaseBlock *exp)
2275{
2276 if (!m_enableScriptExpressions)
2277 return;
2278
2279 auto current = makeGenericScriptElement(exp, DomType::ScriptCaseBlock);
2280 current->addLocation(FileLocationRegion::LeftBraceRegion, exp->lbraceToken);
2281 current->addLocation(FileLocationRegion::RightBraceRegion, exp->rbraceToken);
2282
2283 if (exp->moreClauses) {
2285 current->insertChild(Fields::moreCaseClauses, currentScriptNodeEl().takeList());
2286 removeCurrentScriptNode({});
2287 }
2288
2289 if (exp->defaultClause) {
2291 current->insertChild(Fields::defaultClause, currentScriptNodeEl().takeVariant());
2292 removeCurrentScriptNode({});
2293 }
2294
2295 if (exp->clauses) {
2297 current->insertChild(Fields::caseClauses, currentScriptNodeEl().takeList());
2298 removeCurrentScriptNode({});
2299 }
2300 pushScriptElement(current);
2301}
2302
2303bool QQmlDomAstCreatorBase::visit(AST::SwitchStatement *)
2304{
2305 if (!m_enableScriptExpressions)
2306 return false;
2307
2308 return true;
2309}
2310
2311void QQmlDomAstCreatorBase::endVisit(AST::SwitchStatement *exp)
2312{
2313 if (!m_enableScriptExpressions)
2314 return;
2315
2316 auto current = makeGenericScriptElement(exp, DomType::ScriptSwitchStatement);
2317 current->addLocation(FileLocationRegion::SwitchKeywordRegion, exp->switchToken);
2318 current->addLocation(FileLocationRegion::LeftParenthesisRegion, exp->lparenToken);
2319 current->addLocation(FileLocationRegion::RightParenthesisRegion, exp->rparenToken);
2320
2321 if (exp->block) {
2323 current->insertChild(Fields::caseBlock, currentScriptNodeEl().takeVariant());
2324 removeCurrentScriptNode({});
2325 }
2326 if (exp->expression) {
2328 current->insertChild(Fields::expression, currentScriptNodeEl().takeVariant());
2329 removeCurrentScriptNode({});
2330 }
2331
2332 pushScriptElement(current);
2333}
2334
2335bool QQmlDomAstCreatorBase::visit(AST::WhileStatement *)
2336{
2337 if (!m_enableScriptExpressions)
2338 return false;
2339
2340 return true;
2341}
2342
2343void QQmlDomAstCreatorBase::endVisit(AST::WhileStatement *exp)
2344{
2345 if (!m_enableScriptExpressions)
2346 return;
2347
2348 auto current = makeGenericScriptElement(exp, DomType::ScriptWhileStatement);
2349 current->addLocation(FileLocationRegion::WhileKeywordRegion, exp->whileToken);
2350 current->addLocation(FileLocationRegion::LeftParenthesisRegion, exp->lparenToken);
2351 current->addLocation(FileLocationRegion::RightParenthesisRegion, exp->rparenToken);
2352
2353 if (exp->statement) {
2355 current->insertChild(Fields::body, currentScriptNodeEl().takeVariant());
2356 removeCurrentScriptNode({});
2357 }
2358
2359 if (exp->expression) {
2361 current->insertChild(Fields::expression, currentScriptNodeEl().takeVariant());
2362 removeCurrentScriptNode({});
2363 }
2364
2365 pushScriptElement(current);
2366}
2367
2368bool QQmlDomAstCreatorBase::visit(AST::DoWhileStatement *)
2369{
2370 if (!m_enableScriptExpressions)
2371 return false;
2372
2373 return true;
2374}
2375
2376void QQmlDomAstCreatorBase::endVisit(AST::DoWhileStatement *exp)
2377{
2378 if (!m_enableScriptExpressions)
2379 return;
2380
2381 auto current = makeGenericScriptElement(exp, DomType::ScriptDoWhileStatement);
2382 current->addLocation(FileLocationRegion::DoKeywordRegion, exp->doToken);
2383 current->addLocation(FileLocationRegion::WhileKeywordRegion, exp->whileToken);
2384 current->addLocation(FileLocationRegion::LeftParenthesisRegion, exp->lparenToken);
2385 current->addLocation(FileLocationRegion::RightParenthesisRegion, exp->rparenToken);
2386
2387 if (exp->expression) {
2389 current->insertChild(Fields::expression, currentScriptNodeEl().takeVariant());
2390 removeCurrentScriptNode({});
2391 }
2392
2393 if (exp->statement) {
2395 current->insertChild(Fields::body, currentScriptNodeEl().takeVariant());
2396 removeCurrentScriptNode({});
2397 }
2398
2399 pushScriptElement(current);
2400}
2401
2402bool QQmlDomAstCreatorBase::visit(AST::ForEachStatement *)
2403{
2404 if (!m_enableScriptExpressions)
2405 return false;
2406
2407 return true;
2408}
2409
2410void QQmlDomAstCreatorBase::endVisit(AST::ForEachStatement *exp)
2411{
2412 if (!m_enableScriptExpressions)
2413 return;
2414
2415 auto current = makeGenericScriptElement(exp, DomType::ScriptForEachStatement);
2416 current->addLocation(FileLocationRegion::ForKeywordRegion, exp->forToken);
2417 current->addLocation(FileLocationRegion::InOfTokenRegion, exp->inOfToken);
2418 current->addLocation(FileLocationRegion::LeftParenthesisRegion, exp->lparenToken);
2419 current->addLocation(FileLocationRegion::RightParenthesisRegion, exp->rparenToken);
2420
2421 if (exp->statement) {
2423 current->insertChild(Fields::body, currentScriptNodeEl().takeVariant());
2424 removeCurrentScriptNode({});
2425 }
2426 if (exp->expression) {
2428 current->insertChild(Fields::expression, currentScriptNodeEl().takeVariant());
2429 removeCurrentScriptNode({});
2430 }
2431
2432 if (exp->lhs) {
2434 current->insertChild(Fields::bindingElement, currentScriptNodeEl().takeVariant());
2435 removeCurrentScriptNode({});
2436
2437 if (auto pe = AST::cast<PatternElement *>(exp->lhs);
2438 pe && pe->declarationKindToken.isValid()) {
2439 current->addLocation(FileLocationRegion::TypeIdentifierRegion,
2440 pe->declarationKindToken);
2441 }
2442 }
2443
2444 pushScriptElement(current);
2445}
2446
2447
2448bool QQmlDomAstCreatorBase::visit(AST::ClassExpression *)
2449{
2450 // TODO: Add support for js expressions in classes
2451 // For now, turning off explicitly to avoid unwanted problems
2452 if (m_enableScriptExpressions)
2454 return true;
2455}
2456
2457void QQmlDomAstCreatorBase::endVisit(AST::ClassExpression *)
2458{
2459}
2460
2461void QQmlDomAstCreatorBase::endVisit(AST::TaggedTemplate *literal)
2462{
2463 if (!m_enableScriptExpressions)
2464 return;
2465 auto current = makeGenericScriptElement(literal, DomType::ScriptTaggedTemplate);
2467 current->insertChild(Fields::templateLiteral, scriptNodeStack.takeLast().takeVariant());
2469 current->insertChild(Fields::callee, scriptNodeStack.takeLast().takeVariant());
2470 pushScriptElement(current);
2471}
2472
2473/*!
2474\internal
2475Denotes the position of a template part in a template string. For example, in \c{`a${b}c${d}`}, \c a
2476is \c AtBeginning and \c{${d}} is \c AtEnd while the others are \c InMiddle, and in \c{`a`}, \c a is
2477\c AtBeginning and \c AtEnd.
2478 */
2479enum TemplatePartPosition : quint8 {
2480 InMiddle = 0,
2481 AtBeginning = 0x1,
2482 AtEnd = 0x2,
2483};
2484
2485Q_DECLARE_FLAGS(TemplatePartPositions, TemplatePartPosition)
2486
2487/*!
2488\internal
2489Sets the DollarLeftBraceTokenRegion sourcelocation in currentExpression if templatePartLocation
2490claims that toBeSplit ends in \c{${}.
2491*/
2492static void extractDollarBraceSourceLocationInto(
2493 const std::shared_ptr<ScriptElements::GenericScriptElement> &currentExpression,
2494 const SourceLocation &toBeSplit, QStringView code,
2495 TemplatePartPositions templatePartLocation)
2496{
2497 if (templatePartLocation & AtEnd || !currentExpression)
2498 return;
2499
2500 const auto offset = toBeSplit.offset + toBeSplit.length - 2;
2501 constexpr auto length = quint32(std::char_traits<char>::length("${"));
2502 const auto [row, column] = SourceLocation::rowAndColumnFrom(code, offset, toBeSplit);
2503 currentExpression->addLocation(FileLocationRegion::DollarLeftBraceTokenRegion,
2504 SourceLocation{ offset, length, row, column });
2505 return;
2506}
2507
2508/*!
2509\internal
2510See also \l extractDollarBraceSourceLocationInto.
2511*/
2512static void extractRightBacktickSourceLocationInto(
2513 const std::shared_ptr<ScriptElements::GenericScriptElement> &currentTemplate,
2514 const SourceLocation &toBeSplit, QStringView code,
2515 TemplatePartPositions templatePartLocation)
2516{
2517 if (!(templatePartLocation & AtEnd))
2518 return;
2519
2520 const auto offset = toBeSplit.offset + toBeSplit.length - 1;
2521 constexpr auto length = quint32(std::char_traits<char>::length("`"));
2522 const auto [row, column] = SourceLocation::rowAndColumnFrom(code, offset, toBeSplit);
2523 currentTemplate->addLocation(FileLocationRegion::RightBacktickTokenRegion,
2524 SourceLocation{ offset, length, row, column });
2525}
2526
2527/*!
2528\internal
2529See also \l extractDollarBraceSourceLocationInto.
2530*/
2531static void extractLeftBacktickSourceLocationInto(
2532 const std::shared_ptr<ScriptElements::GenericScriptElement> &currentTemplate,
2533 const SourceLocation &toBeSplit, TemplatePartPositions templatePartLocation)
2534{
2535 if (!(templatePartLocation & AtBeginning))
2536 return;
2537
2538 constexpr auto length = quint32(std::char_traits<char>::length("`"));
2539 const QQmlJS::SourceLocation leftBacktick{ toBeSplit.offset, length, toBeSplit.startLine,
2540 toBeSplit.startColumn };
2541 currentTemplate->addLocation(FileLocationRegion::LeftBacktickTokenRegion, leftBacktick);
2542}
2543
2544/*!
2545\internal
2546See also \l extractDollarBraceSourceLocationInto, but returns the extracted right brace instead of
2547inserting right away.
2548*/
2549static SourceLocation extractRightBraceSourceLocation(const SourceLocation &toBeSplit,
2550 TemplatePartPositions templatePartLocation)
2551{
2552 if (templatePartLocation & AtBeginning)
2553 return SourceLocation{};
2554
2555 // extract } at the beginning and insert in next loop iteration
2556 return SourceLocation{ toBeSplit.offset, 1, toBeSplit.startLine, toBeSplit.startColumn };
2557}
2558
2559/*!
2560\internal
2561Cleans the toBeSplit sourcelocation from potential backticks, dollar braces and right braces to only
2562contain the location of the string part.
2563*/
2564static SourceLocation extractStringLocation(const SourceLocation &toBeSplit, QStringView code,
2565 TemplatePartPositions location)
2566{
2567
2568 // remove "`" or "}" at beginning and "`" or "${" at the end of this location.
2569 const quint32 length = toBeSplit.length - (location & AtEnd ? 2 : 3);
2570 const quint32 offset = toBeSplit.offset + 1;
2571 const auto [row, column] = SourceLocation::rowAndColumnFrom(code, offset, toBeSplit);
2572 return SourceLocation{ offset, length, row, column };
2573}
2574
2575void QQmlDomAstCreatorBase::endVisit(AST::TemplateLiteral *literal)
2576{
2577 if (!m_enableScriptExpressions)
2578 return;
2579
2580 // AST::TemplateLiteral is a list and a TemplateLiteral at the same time:
2581 // in the Dom representation wrap the list into a separate TemplateLiteral Item.
2582 auto currentList = makeScriptList(literal);
2583 auto currentTemplate = makeGenericScriptElement(literal, DomType::ScriptTemplateLiteral);
2584
2585 const auto children = [&literal]() {
2586 std::vector<AST::TemplateLiteral *> result;
2587 for (auto it = literal; it; it = it->next) {
2588 result.push_back(it);
2589 }
2590 return result;
2591 }();
2592
2593 SourceLocation rightBrace;
2594 for (auto it = children.crbegin(); it != children.crend(); ++it) {
2595 // literalToken contains "`", "${", "}", for example "`asdf${" or "}asdf${"
2596 const QQmlJS::SourceLocation toBeSplit = (*it)->literalToken;
2597 std::shared_ptr<ScriptElements::GenericScriptElement> currentExpression;
2598
2599 if ((*it)->expression) {
2601 currentExpression = makeGenericScriptElement((*it)->expression,
2603
2604 currentExpression->insertChild(Fields::expression,
2605 scriptNodeStack.takeLast().takeVariant());
2606 if (rightBrace.isValid()) {
2607 currentExpression->addLocation(FileLocationRegion::RightBraceRegion,
2608 std::exchange(rightBrace, SourceLocation{}));
2609 }
2610 currentList.append(ScriptElementVariant::fromElement(currentExpression));
2611 }
2612
2613 if (!toBeSplit.isValid())
2614 continue;
2615
2616 const TemplatePartPositions location = [&it, &children]() {
2617 TemplatePartPositions result;
2618 if (it == children.crbegin())
2619 result |= AtEnd;
2620 if (it == std::prev(children.crend()))
2621 result |= AtBeginning;
2622 return result;
2623 }();
2624
2625 extractRightBacktickSourceLocationInto(currentTemplate, toBeSplit, qmlFilePtr->code(),
2626 location);
2627 extractLeftBacktickSourceLocationInto(currentTemplate, toBeSplit, location);
2628
2629 extractDollarBraceSourceLocationInto(currentExpression, toBeSplit, qmlFilePtr->code(),
2630 location);
2631 rightBrace = extractRightBraceSourceLocation(toBeSplit, location);
2632
2633 if ((*it)->rawValue.isEmpty())
2634 continue;
2635
2636 const SourceLocation stringLocation =
2637 extractStringLocation(toBeSplit, qmlFilePtr->code(), location);
2638 auto currentString =
2639 makeGenericScriptElement(stringLocation, DomType::ScriptTemplateStringPart);
2640 currentString->insertValue(Fields::value, (*it)->rawValue);
2641
2642 currentList.append(ScriptElementVariant::fromElement(currentString));
2643 }
2644 currentList.reverse();
2645
2646 currentTemplate->insertChild(Fields::components, currentList);
2647 pushScriptElement(currentTemplate);
2648}
2649
2650bool QQmlDomAstCreatorBase::visit(AST::TryStatement *)
2651{
2652 return m_enableScriptExpressions;
2653}
2654
2655void QQmlDomAstCreatorBase::endVisit(AST::TryStatement *statement)
2656{
2657 if (!m_enableScriptExpressions)
2658 return;
2659
2660 auto current = makeGenericScriptElement(statement, DomType::ScriptTryCatchStatement);
2661 current->addLocation(FileLocationRegion::TryKeywordRegion, statement->tryToken);
2662
2663 if (auto exp = statement->finallyExpression) {
2664 current->addLocation(FileLocationRegion::FinallyKeywordRegion, exp->finallyToken);
2665
2667 current->insertChild(Fields::finallyBlock, currentScriptNodeEl().takeVariant());
2668 removeCurrentScriptNode({});
2669 }
2670
2671 if (auto exp = statement->catchExpression) {
2672 current->addLocation(FileLocationRegion::CatchKeywordRegion, exp->catchToken);
2673 current->addLocation(FileLocationRegion::LeftParenthesisRegion, exp->lparenToken);
2674 current->addLocation(FileLocationRegion::RightParenthesisRegion, exp->rparenToken);
2675
2677 current->insertChild(Fields::catchBlock, currentScriptNodeEl().takeVariant());
2678 removeCurrentScriptNode({});
2680 current->insertChild(Fields::catchParameter, currentScriptNodeEl().takeVariant());
2681 removeCurrentScriptNode({});
2682 }
2683
2684 if (statement->statement) {
2686 current->insertChild(Fields::block, currentScriptNodeEl().takeVariant());
2687 removeCurrentScriptNode({});
2688 }
2689
2690 pushScriptElement(current);
2691}
2692
2693bool QQmlDomAstCreatorBase::visit(AST::Catch *)
2694{
2695 // handled in visit(AST::TryStatement* )
2696 return m_enableScriptExpressions;
2697}
2698
2699void QQmlDomAstCreatorBase::endVisit(AST::Catch *)
2700{
2701 // handled in endVisit(AST::TryStatement* )
2702}
2703
2704bool QQmlDomAstCreatorBase::visit(AST::Finally *)
2705{
2706 // handled in visit(AST::TryStatement* )
2707 return m_enableScriptExpressions;
2708}
2709
2710void QQmlDomAstCreatorBase::endVisit(AST::Finally *)
2711{
2712 // handled in endVisit(AST::TryStatement* )
2713}
2714
2715bool QQmlDomAstCreatorBase::visit(AST::ThrowStatement *)
2716{
2717 return m_enableScriptExpressions;
2718}
2719
2720void QQmlDomAstCreatorBase::endVisit(AST::ThrowStatement *statement)
2721{
2722 if (!m_enableScriptExpressions)
2723 return;
2724
2725 auto current = makeGenericScriptElement(statement, DomType::ScriptThrowStatement);
2726 current->addLocation(FileLocationRegion::ThrowKeywordRegion, statement->throwToken);
2727
2728 if (statement->expression) {
2730 current->insertChild(Fields::expression, currentScriptNodeEl().takeVariant());
2731 removeCurrentScriptNode({});
2732 }
2733
2734 pushScriptElement(current);
2735}
2736
2737bool QQmlDomAstCreatorBase::visit(AST::LabelledStatement *)
2738{
2739 return m_enableScriptExpressions;
2740}
2741
2742void QQmlDomAstCreatorBase::endVisit(AST::LabelledStatement *statement)
2743{
2744 if (!m_enableScriptExpressions)
2745 return;
2746
2747 auto current = makeGenericScriptElement(statement, DomType::ScriptLabelledStatement);
2748 current->addLocation(FileLocationRegion::ColonTokenRegion, statement->colonToken);
2749
2750 auto label = std::make_shared<ScriptElements::IdentifierExpression>(statement->identifierToken);
2751 label->setName(statement->label);
2752 current->insertChild(Fields::label, ScriptElementVariant::fromElement(label));
2753
2754
2755 if (statement->statement) {
2757 current->insertChild(Fields::statement, currentScriptNodeEl().takeVariant());
2758 removeCurrentScriptNode({});
2759 }
2760
2761 pushScriptElement(current);
2762}
2763
2764bool QQmlDomAstCreatorBase::visit(AST::BreakStatement *)
2765{
2766 return m_enableScriptExpressions;
2767}
2768
2769void QQmlDomAstCreatorBase::endVisit(AST::BreakStatement *statement)
2770{
2771 if (!m_enableScriptExpressions)
2772 return;
2773
2774 auto current = makeGenericScriptElement(statement, DomType::ScriptBreakStatement);
2775 current->addLocation(FileLocationRegion::BreakKeywordRegion, statement->breakToken);
2776
2777 if (!statement->label.isEmpty()) {
2778 auto label =
2779 std::make_shared<ScriptElements::IdentifierExpression>(statement->identifierToken);
2780 label->setName(statement->label);
2781 current->insertChild(Fields::label, ScriptElementVariant::fromElement(label));
2782 }
2783
2784 pushScriptElement(current);
2785}
2786
2787bool QQmlDomAstCreatorBase::visit(AST::CommaExpression *)
2788{
2789 return m_enableScriptExpressions;
2790}
2791
2792void QQmlDomAstCreatorBase::endVisit(AST::CommaExpression *commaExpression)
2793{
2794 if (!m_enableScriptExpressions)
2795 return;
2796
2797 auto current = makeScriptElement<ScriptElements::BinaryExpression>(commaExpression);
2798 current->addLocation(OperatorTokenRegion, commaExpression->commaToken);
2799
2800 if (commaExpression->right) {
2802 current->setRight(currentScriptNodeEl().takeVariant());
2803 removeCurrentScriptNode({});
2804 }
2805
2806 if (commaExpression->left) {
2808 current->setLeft(currentScriptNodeEl().takeVariant());
2809 removeCurrentScriptNode({});
2810 }
2811
2812 pushScriptElement(current);
2813}
2814
2815bool QQmlDomAstCreatorBase::visit(AST::ConditionalExpression *)
2816{
2817 return m_enableScriptExpressions;
2818}
2819
2820void QQmlDomAstCreatorBase::endVisit(AST::ConditionalExpression *expression)
2821{
2822 if (!m_enableScriptExpressions)
2823 return;
2824
2825 auto current = makeGenericScriptElement(expression, DomType::ScriptConditionalExpression);
2826 current->addLocation(FileLocationRegion::QuestionMarkTokenRegion, expression->questionToken);
2827 current->addLocation(FileLocationRegion::ColonTokenRegion, expression->colonToken);
2828
2829 if (expression->ko) {
2831 current->insertChild(Fields::alternative, currentScriptNodeEl().takeVariant());
2832 removeCurrentScriptNode({});
2833 }
2834
2835 if (expression->ok) {
2837 current->insertChild(Fields::consequence, currentScriptNodeEl().takeVariant());
2838 removeCurrentScriptNode({});
2839 }
2840
2841 if (expression->expression) {
2843 current->insertChild(Fields::condition, currentScriptNodeEl().takeVariant());
2844 removeCurrentScriptNode({});
2845 }
2846
2847 pushScriptElement(current);
2848}
2849
2850bool QQmlDomAstCreatorBase::visit(AST::ContinueStatement *)
2851{
2852 return m_enableScriptExpressions;
2853}
2854
2855void QQmlDomAstCreatorBase::endVisit(AST::ContinueStatement *statement)
2856{
2857 if (!m_enableScriptExpressions)
2858 return;
2859
2860 auto current = makeGenericScriptElement(statement, DomType::ScriptContinueStatement);
2861 current->addLocation(FileLocationRegion::ContinueKeywordRegion, statement->continueToken);
2862
2863 if (!statement->label.isEmpty()) {
2864 auto label =
2865 std::make_shared<ScriptElements::IdentifierExpression>(statement->identifierToken);
2866 label->setName(statement->label);
2867 current->insertChild(Fields::label, ScriptElementVariant::fromElement(label));
2868 }
2869
2870 pushScriptElement(current);
2871}
2872
2873/*!
2874 \internal
2875 Helper to create unary expressions from AST nodes.
2876 \sa makeGenericScriptElement
2877 */
2879QQmlDomAstCreatorBase::makeUnaryExpression(AST::Node *expression, QQmlJS::SourceLocation operatorToken,
2880 bool hasExpression, UnaryExpressionKind kind)
2881{
2882 const DomType type = [&kind]() {
2883 switch (kind) {
2884 case Prefix:
2886 case Postfix:
2888 }
2889 Q_UNREACHABLE_RETURN(DomType::ScriptUnaryExpression);
2890 }();
2891
2892 auto current = makeGenericScriptElement(expression, type);
2893 current->addLocation(FileLocationRegion::OperatorTokenRegion, operatorToken);
2894
2895 if (hasExpression) {
2898 return {};
2899 }
2900 current->insertChild(Fields::expression, currentScriptNodeEl().takeVariant());
2901 removeCurrentScriptNode({});
2902 }
2903
2904 return current;
2905}
2906
2907bool QQmlDomAstCreatorBase::visit(AST::UnaryMinusExpression *)
2908{
2909 return m_enableScriptExpressions;
2910}
2911
2912void QQmlDomAstCreatorBase::endVisit(AST::UnaryMinusExpression *statement)
2913{
2914 if (!m_enableScriptExpressions)
2915 return;
2916
2917 auto current =
2918 makeUnaryExpression(statement, statement->minusToken, statement->expression, Prefix);
2919 if (!current)
2920 return;
2921
2922 pushScriptElement(current);
2923}
2924
2925bool QQmlDomAstCreatorBase::visit(AST::UnaryPlusExpression *)
2926{
2927 return m_enableScriptExpressions;
2928}
2929
2930void QQmlDomAstCreatorBase::endVisit(AST::UnaryPlusExpression *statement)
2931{
2932 if (!m_enableScriptExpressions)
2933 return;
2934
2935 auto current =
2936 makeUnaryExpression(statement, statement->plusToken, statement->expression, Prefix);
2937 if (!current)
2938 return;
2939
2940 pushScriptElement(current);
2941}
2942
2943bool QQmlDomAstCreatorBase::visit(AST::TildeExpression *)
2944{
2945 return m_enableScriptExpressions;
2946}
2947
2948void QQmlDomAstCreatorBase::endVisit(AST::TildeExpression *statement)
2949{
2950 if (!m_enableScriptExpressions)
2951 return;
2952
2953 auto current =
2954 makeUnaryExpression(statement, statement->tildeToken, statement->expression, Prefix);
2955 if (!current)
2956 return;
2957
2958 pushScriptElement(current);
2959}
2960
2961bool QQmlDomAstCreatorBase::visit(AST::NotExpression *)
2962{
2963 return m_enableScriptExpressions;
2964}
2965
2966void QQmlDomAstCreatorBase::endVisit(AST::NotExpression *statement)
2967{
2968 if (!m_enableScriptExpressions)
2969 return;
2970
2971 auto current =
2972 makeUnaryExpression(statement, statement->notToken, statement->expression, Prefix);
2973 if (!current)
2974 return;
2975
2976 pushScriptElement(current);
2977}
2978
2979bool QQmlDomAstCreatorBase::visit(AST::TypeOfExpression *)
2980{
2981 return m_enableScriptExpressions;
2982}
2983
2984void QQmlDomAstCreatorBase::endVisit(AST::TypeOfExpression *statement)
2985{
2986 if (!m_enableScriptExpressions)
2987 return;
2988
2989 auto current =
2990 makeUnaryExpression(statement, statement->typeofToken, statement->expression, Prefix);
2991 if (!current)
2992 return;
2993
2994 pushScriptElement(current);
2995}
2996
2997bool QQmlDomAstCreatorBase::visit(AST::DeleteExpression *)
2998{
2999 return m_enableScriptExpressions;
3000}
3001
3002void QQmlDomAstCreatorBase::endVisit(AST::DeleteExpression *statement)
3003{
3004 if (!m_enableScriptExpressions)
3005 return;
3006
3007 auto current =
3008 makeUnaryExpression(statement, statement->deleteToken, statement->expression, Prefix);
3009 if (!current)
3010 return;
3011
3012 pushScriptElement(current);
3013}
3014
3015bool QQmlDomAstCreatorBase::visit(AST::VoidExpression *)
3016{
3017 return m_enableScriptExpressions;
3018}
3019
3020void QQmlDomAstCreatorBase::endVisit(AST::VoidExpression *statement)
3021{
3022 if (!m_enableScriptExpressions)
3023 return;
3024
3025 auto current =
3026 makeUnaryExpression(statement, statement->voidToken, statement->expression, Prefix);
3027 if (!current)
3028 return;
3029
3030 pushScriptElement(current);
3031}
3032
3033bool QQmlDomAstCreatorBase::visit(AST::PostDecrementExpression *)
3034{
3035 return m_enableScriptExpressions;
3036}
3037
3038void QQmlDomAstCreatorBase::endVisit(AST::PostDecrementExpression *statement)
3039{
3040 if (!m_enableScriptExpressions)
3041 return;
3042
3043 auto current =
3044 makeUnaryExpression(statement, statement->decrementToken, statement->base, Postfix);
3045 if (!current)
3046 return;
3047
3048 pushScriptElement(current);
3049}
3050
3051bool QQmlDomAstCreatorBase::visit(AST::PostIncrementExpression *)
3052{
3053 return m_enableScriptExpressions;
3054}
3055
3056void QQmlDomAstCreatorBase::endVisit(AST::PostIncrementExpression *statement)
3057{
3058 if (!m_enableScriptExpressions)
3059 return;
3060
3061 auto current =
3062 makeUnaryExpression(statement, statement->incrementToken, statement->base, Postfix);
3063 if (!current)
3064 return;
3065
3066 pushScriptElement(current);
3067}
3068
3069bool QQmlDomAstCreatorBase::visit(AST::PreIncrementExpression *)
3070{
3071 return m_enableScriptExpressions;
3072}
3073
3074void QQmlDomAstCreatorBase::endVisit(AST::PreIncrementExpression *statement)
3075{
3076 if (!m_enableScriptExpressions)
3077 return;
3078
3079 auto current = makeUnaryExpression(statement, statement->incrementToken, statement->expression,
3080 Prefix);
3081 if (!current)
3082 return;
3083
3084 pushScriptElement(current);
3085}
3086
3087bool QQmlDomAstCreatorBase::visit(AST::EmptyStatement *)
3088{
3089 return m_enableScriptExpressions;
3090}
3091
3092void QQmlDomAstCreatorBase::endVisit(AST::EmptyStatement *statement)
3093{
3094 if (!m_enableScriptExpressions)
3095 return;
3096
3097 auto current = makeGenericScriptElement(statement, DomType::ScriptEmptyStatement);
3098 current->addLocation(FileLocationRegion::SemicolonTokenRegion, statement->semicolonToken);
3099 pushScriptElement(current);
3100}
3101
3102bool QQmlDomAstCreatorBase::visit(AST::NestedExpression *)
3103{
3104 return m_enableScriptExpressions;
3105}
3106
3107void QQmlDomAstCreatorBase::endVisit(AST::NestedExpression *expression)
3108{
3109 if (!m_enableScriptExpressions)
3110 return;
3111
3112 auto current = makeGenericScriptElement(expression, DomType::ScriptParenthesizedExpression);
3113 current->addLocation(FileLocationRegion::LeftParenthesisRegion, expression->lparenToken);
3114 current->addLocation(FileLocationRegion::RightParenthesisRegion, expression->rparenToken);
3115
3116 if (expression->expression) {
3118 current->insertChild(Fields::expression, currentScriptNodeEl().takeVariant());
3119 removeCurrentScriptNode({});
3120 }
3121
3122 pushScriptElement(current);
3123}
3124
3125bool QQmlDomAstCreatorBase::visit(AST::NewExpression *)
3126{
3127 return m_enableScriptExpressions;
3128}
3129
3130void QQmlDomAstCreatorBase::endVisit(AST::NewExpression *expression)
3131{
3132 if (!m_enableScriptExpressions)
3133 return;
3134
3135 auto current = makeGenericScriptElement(expression, DomType::ScriptNewExpression);
3136 current->addLocation(FileLocationRegion::NewKeywordRegion, expression->newToken);
3137
3138 if (expression->expression) {
3140 current->insertChild(Fields::expression, currentScriptNodeEl().takeVariant());
3141 removeCurrentScriptNode({});
3142 }
3143
3144 pushScriptElement(current);
3145}
3146
3147bool QQmlDomAstCreatorBase::visit(AST::NewMemberExpression *)
3148{
3149 return m_enableScriptExpressions;
3150}
3151
3152void QQmlDomAstCreatorBase::endVisit(AST::NewMemberExpression *expression)
3153{
3154 if (!m_enableScriptExpressions)
3155 return;
3156
3157 auto current = makeGenericScriptElement(expression, DomType::ScriptNewMemberExpression);
3158 current->addLocation(FileLocationRegion::NewKeywordRegion, expression->newToken);
3159 current->addLocation(FileLocationRegion::LeftParenthesisRegion, expression->lparenToken);
3160 current->addLocation(FileLocationRegion::RightParenthesisRegion, expression->rparenToken);
3161
3162 if (expression->arguments) {
3164 current->insertChild(Fields::arguments, scriptNodeStack.takeLast().takeList());
3165 }
3166 if (expression->base) {
3168 current->insertChild(Fields::base, scriptNodeStack.takeLast().takeVariant());
3169 }
3170
3171 pushScriptElement(current);
3172}
3173
3174void QQmlDomAstCreatorBase::endVisit(AST::WithStatement *ast)
3175{
3176 if (!m_enableScriptExpressions)
3177 return;
3178
3179 auto current = makeGenericScriptElement(ast, DomType::ScriptWithStatement);
3180
3181 if (ast->statement) {
3183 current->insertChild(Fields::statement, scriptNodeStack.takeLast().takeVariant());
3184 }
3185 if (ast->expression) {
3187 current->insertChild(Fields::expression, scriptNodeStack.takeLast().takeVariant());
3188 }
3189
3190 pushScriptElement(current);
3191}
3192
3193bool QQmlDomAstCreatorBase::visit(AST::PreDecrementExpression *)
3194{
3195 return m_enableScriptExpressions;
3196}
3197
3198void QQmlDomAstCreatorBase::endVisit(AST::PreDecrementExpression *statement)
3199{
3200 if (!m_enableScriptExpressions)
3201 return;
3202
3203 auto current = makeUnaryExpression(statement, statement->decrementToken, statement->expression,
3204 Prefix);
3205 if (!current)
3206 return;
3207
3208 pushScriptElement(current);
3209}
3210
3212 QQmlJSLogger *logger,
3213 QQmlJSImporter *importer)
3214 : m_logger(logger),
3220{
3221}
3222
3223#define X(name)
3224 bool QQmlDomAstCreatorWithQQmlJSScope::visit(name *node)
3225 {
3226 return visitT(node);
3227 }
3228 void QQmlDomAstCreatorWithQQmlJSScope::endVisit(name *node)
3229 {
3230 endVisitT(node);
3231 }
3232QQmlJSASTClassListToVisit
3233#undef X
3234
3235void QQmlDomAstCreatorWithQQmlJSScope::setScopeInDomAfterEndvisit()
3236{
3237 const QQmlJSScope::ConstPtr scope = m_scopeCreator.m_currentScope;
3238 if (!m_domCreator.scriptNodeStack.isEmpty()) {
3239 auto topOfStack = m_domCreator.currentScriptNodeEl();
3240 switch (topOfStack.kind) {
3242 // A ScriptIdentifierExpression in a QML scope is an actual ID.
3243 if (scope->scopeType() == QQmlJSScope::ScopeType::QMLScope)
3244 m_domCreator.currentScriptNodeEl().setSemanticScope(scope);
3245 break;
3246 }
3247 case DomType::ScriptBlockStatement:
3248 case DomType::ScriptForStatement:
3249 case DomType::ScriptForEachStatement:
3250 case DomType::ScriptDoWhileStatement:
3251 case DomType::ScriptWhileStatement:
3252 case DomType::List:
3253 m_domCreator.currentScriptNodeEl().setSemanticScope(scope);
3254 break;
3256 // Put the body's scope into the function expression: function expressions will contain
3257 // their parents scope instead of their own without this
3258 auto element = m_domCreator.currentScriptNodeEl().value;
3259 auto scriptElementVariant = std::get_if<ScriptElementVariant>(&element);
3260 if (!scriptElementVariant || !scriptElementVariant->data())
3261 break;
3262 scriptElementVariant->visit([](auto &&e) {
3263 using U = std::remove_cv_t<std::remove_reference_t<decltype(e)>>;
3264 if (e->kind() != DomType::ScriptFunctionExpression)
3265 return;
3266
3267 if constexpr (std::is_same_v<U,
3268 ScriptElement::PointerType<
3269 ScriptElements::GenericScriptElement>>) {
3270 if (auto bodyPtr = e->elementChild(Fields::body)) {
3271 const auto bodyScope = bodyPtr.base()->semanticScope();
3272 e->setSemanticScope(bodyScope);
3273 }
3274 }
3275 });
3276 break;
3277 }
3278
3279 // TODO: find which script elements also have a scope and implement them here
3280 default:
3281 break;
3282 };
3283 } else if (!m_domCreator.nodeStack.isEmpty()) {
3284 std::visit(
3285 [&scope](auto &&e) {
3286 using U = std::remove_cv_t<std::remove_reference_t<decltype(e)>>;
3287 // TODO: find which dom elements also have a scope and implement them here
3288 if constexpr (std::is_same_v<U, QmlObject>) {
3289 e.setSemanticScope(scope);
3290 } else if constexpr (std::is_same_v<U, QmlComponent>) {
3291 e.setSemanticScope(scope);
3292 } else if constexpr (std::is_same_v<U, MethodInfo>) {
3293 if (e.body) {
3294 if (auto scriptElement = e.body->scriptElement()) {
3295 scriptElement.base()->setSemanticScope(scope);
3296 }
3297 }
3298 e.setSemanticScope(scope);
3299 }
3300 },
3301 m_domCreator.currentNodeEl().item.value);
3302 }
3303}
3304
3305void QQmlDomAstCreatorWithQQmlJSScope::setScopeInDomBeforeEndvisit()
3306{
3307 const QQmlJSScope::ConstPtr scope = m_scopeCreator.m_currentScope;
3308
3309 // depending whether the property definition has a binding, the property definition might be
3310 // either at the last position in the stack or at the position before the last position.
3311 if (m_domCreator.nodeStack.size() > 1
3312 && m_domCreator.nodeStack.last().item.kind == DomType::Binding) {
3313 std::visit(
3314 [&scope](auto &&e) {
3315 using U = std::remove_cv_t<std::remove_reference_t<decltype(e)>>;
3316 if constexpr (std::is_same_v<U, PropertyDefinition>) {
3317 // Make sure to use the property definition scope instead of the binding
3318 // scope. If the current scope is a binding scope (this happens when the
3319 // property definition has a binding, like `property int i: 45` for
3320 // example), then the property definition scope is the parent of the current
3321 // scope.
3322 const bool usePropertyDefinitionScopeInsteadOfTheBindingScope =
3323 QQmlSA::isFunctionScope(scope->scopeType())
3324 && scope->parentScope()
3325 && scope->parentScope()->scopeType() == QQmlSA::ScopeType::QMLScope;
3326 e.setSemanticScope(usePropertyDefinitionScopeInsteadOfTheBindingScope
3327 ? scope->parentScope()
3328 : scope);
3329 }
3330 },
3331 m_domCreator.currentNodeEl(1).item.value);
3332 }
3333 if (m_domCreator.nodeStack.size() > 0) {
3334 std::visit(
3335 [&scope](auto &&e) {
3336 using U = std::remove_cv_t<std::remove_reference_t<decltype(e)>>;
3337 if constexpr (std::is_same_v<U, PropertyDefinition>) {
3338 e.setSemanticScope(scope);
3339 Q_ASSERT(e.semanticScope());
3340 } else if constexpr (std::is_same_v<U, MethodInfo>) {
3341 if (e.methodType == MethodInfo::Signal) {
3342 e.setSemanticScope(scope);
3343 }
3344 }
3345 },
3346 m_domCreator.currentNodeEl().item.value);
3347 }
3348}
3349
3351{
3352}
3353
3354void QQmlDomAstCreatorWithQQmlJSScope::loadQmlDependenciesInDom()
3355{
3356 const auto types = m_scopeCreator.imports().types();
3357 auto environment = m_domCreator.currentEnvironment();
3358 for (auto it = types.begin(), end = types.end(); it != end; ++it) {
3359 auto scope = it->scope;
3360 if (!scope)
3361 continue;
3362 auto factory = scope.factory();
3363 if (!factory && !scope->isComposite())
3364 continue;
3365 const QString filePath = QQmlJSUtils::qmlSourcePathFromBuildPath(
3366 m_importer->resourceFileMapper(),
3367 factory ? factory->filePath() : scope->filePath());
3368 if (!environment->hasFile(filePath))
3369 environment->loadFile(FileToLoad::fromFileSystem(environment, filePath), { });
3370 }
3371}
3372
3373#define X(name)
3374 bool QQmlDomAstCreator::visit(AST::name *ast)
3375 {
3376 return QQmlDomAstCreatorBase::visit(ast) && visitWithCustomListIteration(ast, this);
3377 }
3379#undef X
3380
3381} // end namespace Dom
3382} // end namespace QQmlJS
3383
3384#undef Q_SCRIPTELEMENT_DISABLE
3385#undef Q_SCRIPTELEMENT_EXIT_IF
3386
3387QT_END_NAMESPACE
Binding & operator=(const Binding &)
void setBindingIdentifiers(const ScriptElementVariant &bindingIdentifiers)
std::shared_ptr< ScriptExpression > scriptExpressionValue()
Path addValue(const EnumItem &value)
Represents a set of tags grouping a set of related error messages.
TypeAnnotationStyle typeAnnotationStyle
Represents an immutable JsonPath like path in the Qml code model (from a DomItem to another DomItem).
static Path fromField(FieldName name)
Path operator[](int i) const
Path withField(FieldName name) const
Path mid(int offset, int length) const
Path last() const
std::optional< FieldName > headField() const
void setNameIdentifiers(const ScriptElementVariant &name)
QQmlDomAstCreatorBase(const MutableDomItem &qmlFile)
void endVisit(AST::UiProgram *) override
void throwRecursionDepthError() override
void endVisitHelper(AST::PatternElement *pe, const std::shared_ptr< ScriptElements::GenericScriptElement > &element)
bool visit(AST::UiProgram *program) override
virtual QQmlJSASTClassListToVisit void throwRecursionDepthError() override
QQmlDomAstCreatorWithQQmlJSScope(MutableDomItem &qmlFile, QQmlJSLogger *logger, QQmlJSImporter *importer)
void setNameIdentifiers(const ScriptElementVariant &name)
Path addId(const Id &id, AddOption option=AddOption::Overwrite, Id **idPtr=nullptr)
void setNameIdentifiers(const ScriptElementVariant &name)
void updatePathFromOwner(const Path &newPath) override
Path addPrototypePath(const Path &prototypePath)
QList< std::pair< SourceLocation, DomItem > > Attributes
Use this to contain any script element.
void replaceKindForGenericChildren(DomType oldType, DomType newType)
Provides entities to maintain mappings between elements and their location in a file.
void addRegion(const Tree &fLoc, FileLocationRegion region, SourceLocation loc)
Tree ensure(const Tree &base, const Path &basePath)
bool operator==(const Path &lhs, const Path &rhs)
QT_BEGIN_NAMESPACE Q_STATIC_LOGGING_CATEGORY(lcSynthesizedIterableAccess, "qt.iterable.synthesized", QtWarningMsg)
#define Q_SCRIPTELEMENT_EXIT_IF(check)
#define Q_SCRIPTELEMENT_DISABLE()
#define NewErrorGroup(name)