15#include <QtQml/private/qqmljsast_p.h>
16#include <QtQmlCompiler/private/qqmljsutils_p.h>
19#include <QtCore/QFileInfo>
20#include <QtCore/QScopeGuard>
21#include <QtCore/QLoggingCategory>
32
33
34
35#define Q_SCRIPTELEMENT_DISABLE()
37 qCDebug(creatorLog) << "Could not construct the JS DOM at" << __FILE__ << ":" << __LINE__
38 << ", skipping JS elements...";
39 disableScriptElements();
42#define Q_SCRIPTELEMENT_EXIT_IF(check)
44 if (m_enableScriptExpressions && (check)) {
45 Q_SCRIPTELEMENT_DISABLE();
56template<
typename K,
typename V>
57V *valueFromMultimap(QMultiMap<K, V> &mmap,
const K &key, index_type idx)
61 auto it = mmap.find(key);
62 auto end = mmap.end();
67 while (it2 != end && it2.key() == key) {
73 for (index_type i = idx + 1; i < nEl; ++i)
85static QString toString(
const UiQualifiedId *qualifiedId, QChar delimiter = QLatin1Char(
'.'))
89 for (
const UiQualifiedId *iter = qualifiedId; iter; iter = iter->next) {
90 if (iter != qualifiedId)
99static QString typeToString(AST::Type *t)
102 QString res = toString(t->typeId);
104 if (UiQualifiedId *arg = t->typeArgument)
105 res += u'<' + toString(arg) + u'>';
110SourceLocation combineLocations(SourceLocation s1, SourceLocation s2)
112 return combine(s1, s2);
115SourceLocation combineLocations(Node *n)
117 return combineLocations(n->firstSourceLocation(), n->lastSourceLocation());
121 const SourceLocation &dotToken,
124 SourceLocation s1, s2;
125 left.visitConst([&s1](
auto &&el) { s1 = el->mainRegionLocation(); });
126 right.visitConst([&s2](
auto &&el) { s2 = el->mainRegionLocation(); });
129 result->addLocation(OperatorTokenRegion, dotToken);
131 result->setLeft(left);
132 result->setRight(right);
137
138
139
141fieldMemberExpressionForQualifiedId(
const AST::UiQualifiedId *qualifiedId)
145 for (
auto exp = qualifiedId; exp; exp = exp->next) {
146 const SourceLocation identifierLoc = exp->identifierToken;
148 id->setName(exp->name);
154 bindable = wrapIntoFieldMemberExpression(bindable, exp->dotToken,
155 ScriptElementVariant::fromElement(id));
163 Q_ASSERT_X(idx < nodeStack.size() && idx >= 0,
"currentQmlObjectOrComponentEl",
164 "Stack does not contain enough elements!");
165 int i = nodeStack.size() - idx;
167 DomType k = nodeStack.at(i).item.kind;
168 if (k == DomType::QmlObject || k == DomType::QmlComponent)
171 Q_ASSERT_X(
false,
"currentQmlObjectEl",
"No QmlObject or component in stack");
172 return nodeStack.last();
177 Q_ASSERT_X(i < nodeStack.size() && i >= 0,
"currentNode",
"Stack does not contain element!");
178 return nodeStack[nodeStack.size() - i - 1];
183 Q_ASSERT_X(i < scriptNodeStack.size() && i >= 0,
"currentNode",
184 "Stack does not contain element!");
185 return scriptNodeStack[scriptNodeStack.size() - i - 1];
190 Q_ASSERT_X(i < nodeStack.size() && i >= 0,
"currentNode",
191 "Stack does not contain element!");
192 return nodeStack[nodeStack.size() - i - 1].item;
197 Q_ASSERT_X(!nodeStack.isEmpty(), className,
"popCurrentNode() without any node");
199 Q_ASSERT(nodeStack.last().item.kind == *expectedType);
200 nodeStack.removeLast();
206 Q_ASSERT_X(!scriptNodeStack.isEmpty(), className,
207 "popCurrentScriptNode() without any node");
209 Q_ASSERT(scriptNodeStack.last().kind == *expectedType);
210 scriptNodeStack.removeLast();
214
215
216
217
218
219
220
221
222
223
224
229 auto e = element.base();
232 qCDebug(creatorLog) <<
"Finalizing script expression with path:"
233 << FileLocations::canonicalPathForTesting(ownerFileLocations)
234 .append(pathFromOwner.toString());
235 e->updatePathFromOwner(pathFromOwner);
236 e->createFileLocations(ownerFileLocations);
254 switch (currentNode().kind) {
263 qCWarning(domLog) <<
"unexpected type" << domTypeToString(currentNode().kind);
266 base = currentNodeEl().fileLocations;
272 || *fn ==
Fields::annotations))
277 qCWarning(domLog) <<
"unexpected path to QmlObject in createMap" << p;
281 qCWarning(domLog) <<
"unexpected path to QmlObject in createMap" << p;
287 base = currentNodeEl().fileLocations;
300 base = currentEl<
QmlObject>().fileLocations;
308 qCWarning(domLog) <<
"Unexpected type in createMap:" << domTypeToString(k);
312 return createMap(base, relative, n);
324 QFileInfo fInfo(qmlFile.canonicalFilePath());
325 QString componentName = fInfo.baseName();
327 Path p = qmlFilePtr->addComponent(QmlComponent(componentName), AddOption::KeepExisting,
330 Q_ASSERT_X(newC
.item(), className,
"could not recover component added with addComponent");
334 pushEl(p, *cPtr, program);
336 auto envPtr = qmlFile.environment().ownerAs<DomEnvironment>();
337 const bool loadDependencies =
339 if (m_loadFileLazily && loadDependencies) {
340 envPtr->loadPendingDependencies();
341 envPtr->commitToBase(qmlFile.environment().item());
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);
357 *newC.mutableAs<QmlComponent>() = comp;
359 Q_ASSERT_X(nodeStack.isEmpty(), className,
"ui program did not finish node stack");
364 QStringList valueList;
365 for (
auto t = el->values; t; t = t->next)
366 valueList << t->value.toString();
368 auto fileLocation = createMap(
369 DomType::Pragma, qmlFilePtr->addPragma(Pragma(el->name.toString(), valueList)), el);
372 if (el->colonToken.isValid()) {
376 for (
auto t = el->values; t; t = t->next) {
377 auto subMap = createMap(fileLocation, Path().withField(Fields::values).withIndex(i), t);
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();
393 auto envPtr = qmlFile.environment().ownerAs<DomEnvironment>();
394 const bool loadDependencies =
397 if (el->importUri !=
nullptr) {
399 Import::fromUriString(toString(el->importUri), v, el->importId.toString());
400 fileLocation = createMap(DomType::Import, qmlFilePtr->addImport(import), el);
405 Import::fromFileString(el->fileName.toString(), el->importId.toString());
406 fileLocation = createMap(DomType::Import, qmlFilePtr->addImport(import), el);
410 if (m_loadFileLazily && loadDependencies) {
411 envPtr->loadPendingDependencies();
412 envPtr->commitToBase(qmlFile.environment().item());
415 if (el->importToken.isValid())
418 if (el->asToken.isValid())
421 if (el->importIdToken.isValid())
434 case AST::UiPublicMember::Signal: {
436 m.name = el->name.toString();
437 m.typeName = toString(el->memberType);
438 m.isReadonly = el->isReadonly();
440 m.methodType = MethodInfo::Signal;
441 m.isList = el->typeModifier == QLatin1String(
"list");
444 pushEl(p, *mPtr, el);
446 const auto fileLocations = nodeStack.last().fileLocations;
449 if (el->lparenToken.isValid())
451 if (el->rparenToken.isValid())
455 AST::UiParameterList *args = el->parameters;
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);
469 if (args->colonToken.isValid())
477 case AST::UiPublicMember::Property: {
479 p.name = el->name.toString();
480 p.typeName = toString(el->memberType);
481 p.isReadonly = el->isReadonly();
484 p.isList = el->typeModifier == QLatin1String(
"list");
488 if (!el->typeModifier.isEmpty())
489 p.typeName = el->typeModifier.toString() + QChar(u'<') + p.typeName + QChar(u'>');
491 Path pPathFromOwner =
493 if (m_enableScriptExpressions) {
495 qmlObjectType->insertChild(
Fields::typeName,
496 fieldMemberExpressionForQualifiedId(el->memberType));
502 m_skipBindingIdentifiers = el->binding;
504 pushEl(pPathFromOwner, *pPtr, el);
506 el->propertyToken());
508 el->identifierToken);
512 if (el->typeModifierToken.isValid())
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)));
529 el->overrideToken());
537 el->requiredToken());
541 el->readonlyToken());
544 ++m_nestedFunctionDepth;
546 SourceLocation loc = combineLocations(el->statement);
547 QStringView code = qmlFilePtr->code();
550 code.mid(loc.offset, loc.length), qmlFilePtr->engine(), el->statement,
551 qmlFilePtr->astComments(), ScriptExpression::ExpressionType::BindingExpression,
556 FileLocations::
Tree bLoc = createMap(DomType::Binding, bPathFromOwner, el->statement);
558 FileLocations::
Tree valueLoc = FileLocations::ensure(bLoc, Path::fromField(Fields::value));
562 nodeStack.append({ std::move(bPathFromOwner), *bPtr, std::move(bLoc) });
573 --m_nestedFunctionDepth;
575 if (m_enableScriptExpressions
576 && (scriptNodeStack.size() != 1 || scriptNodeStack.last().isList())) {
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({});
589 valueFromMultimap(containingObject.m_bindings, b.name(), currentIndex());
591 removeCurrentNode({});
593 Node::accept(el->parameters,
this);
595 if ((el->binding || el->statement)
596 && nodeStack.last().item.kind == DomType::PropertyDefinition) {
598 if (!pDef.annotations.isEmpty()) {
600 duplicate.setName(QLatin1String(
"duplicate"));
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)
609 .withIndex(obj.m_bindings.values(pDef.name).size() - 1),
616 QmlStackElement &sEl = nodeStack.last();
617 switch (sEl.item.kind) {
621 valueFromMultimap(obj.m_propertyDefs, pDef.name, *sEl.path.last().headIndex());
623 *pDefPtr =
std::move(pDef);
627 MethodInfo *mPtr = valueFromMultimap(obj.m_methods, m.name, *sEl.path.last().headIndex());
629 *mPtr =
std::move(m);
634 removeCurrentNode({});
639 endVisitForLists(list);
644 ++m_nestedFunctionDepth;
645 if (!m_enableScriptExpressions)
653 Q_ASSERT(!scriptNodeStack.isEmpty() || !fExpression->body);
655 if (fExpression->body) {
656 if (currentScriptNodeEl().isList()) {
660 combineLocations(fExpression->lbraceToken, fExpression->rbraceToken));
661 body->setStatements(currentScriptNodeEl().takeList());
662 if (
auto semanticScope = body->statements().semanticScope())
663 body->setSemanticScope(semanticScope);
665 removeCurrentScriptNode({});
668 auto result = currentScriptNodeEl().takeVariant();
669 removeCurrentScriptNode({});
672 Q_UNREACHABLE_RETURN({});
677 combineLocations(fExpression->lbraceToken, fExpression->rbraceToken));
683 --m_nestedFunctionDepth;
684 if (!m_enableScriptExpressions)
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));
708 current->insertChild(
Fields::body, prepareBodyForFunction(fExpression));
710 if (fExpression->typeAnnotation) {
712 current->insertChild(
Fields::returnType, currentScriptNodeEl().takeVariant());
713 scriptNodeStack.removeLast();
715 if (fExpression->formals) {
717 current->insertChild(
Fields::parameters, currentScriptNodeEl().takeList());
718 scriptNodeStack.removeLast();
721 if (!fExpression->name.isEmpty())
722 current->insertValue(
Fields::name, fExpression->name);
724 pushScriptElement(current);
730 if (m_nestedFunctionDepth > 0) {
731 return visit(
static_cast<FunctionExpression *>(fDef));
733 ++m_nestedFunctionDepth;
734 const QStringView code(qmlFilePtr->code());
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);
742 m.methodType = MethodInfo::Method;
745 SourceLocation bodyLoc = fDef->body ? combineLocations(fDef->body)
746 : combineLocations(fDef->lbraceToken, fDef->rbraceToken);
748 code.mid(bodyLoc.offset, bodyLoc.length), qmlFilePtr->engine(), fDef->body,
749 qmlFilePtr->astComments(), ScriptExpression::ExpressionType::FunctionBody, bodyLoc);
751 if (fDef->typeAnnotation) {
752 SourceLocation typeLoc = combineLocations(fDef->typeAnnotation);
754 code.mid(typeLoc.offset, typeLoc.length), qmlFilePtr->engine(),
755 fDef->typeAnnotation, qmlFilePtr->astComments(),
756 ScriptExpression::ExpressionType::ReturnType, typeLoc);
761 pushEl(mPathFromOwner, *mPtr,
764 if (fDef->identifierToken.isValid())
768 if (fDef->functionToken.isValid())
770 if (fDef->starToken.isValid())
772 if (fDef->lparenToken.length != 0)
774 if (fDef->rparenToken.length != 0)
776 if (fDef->lbraceToken.length != 0)
778 if (fDef->rbraceToken.length != 0)
780 if (fDef->typeAnnotation)
783 AST::FormalParameterList *args = fDef->formals;
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);
791 if (args->element->initializer) {
792 SourceLocation loc = combineLocations(args->element->initializer);
794 code.mid(loc.offset, loc.length), qmlFilePtr->engine(),
795 args->element->initializer, qmlFilePtr->astComments(),
796 ScriptExpression::ExpressionType::ArgInitializer, loc);
798 if (args->element->type == AST::PatternElement::SpreadElement)
800 SourceLocation parameterLoc = combineLocations(args->element);
802 code.mid(parameterLoc.offset, parameterLoc.length), qmlFilePtr->engine(),
803 args->element, qmlFilePtr->astComments(),
804 ScriptExpression::ExpressionType::ArgumentStructure, parameterLoc);
806 index_type idx = index_type(mInfo.parameters.size());
807 mInfo.parameters.append(param);
811 if (args->element->identifierToken.isValid())
813 if (args->element->typeAnnotation)
822 if (AST::cast<VariableStatement *>(el->sourceElement)) {
823 qmlFile.addError(astParseErrors().warning(
824 "JavaScript declarations are not allowed in QML elements"_L1));
832 if (
auto data = variant.data()) {
833 if (
auto genericElement =
834 std::get_if<std::shared_ptr<ScriptElements::GenericScriptElement>>(&*data)) {
843 if (m_nestedFunctionDepth > 1) {
844 endVisit(
static_cast<FunctionExpression *>(fDef));
847 --m_nestedFunctionDepth;
850 FileLocations::ensure(currentNodeEl().fileLocations, Path().withField(Fields::body));
853 if (!m_enableScriptExpressions)
857 m.body->setScriptElement(
858 finalizeScriptExpression(prepareBodyForFunction(fDef), bodyPath, bodyTree));
860 if (fDef->typeAnnotation) {
867 finalizeScriptExpression(variant, pathToReturnType, argLoc);
868 m.returnType->setScriptElement(variant);
869 removeCurrentScriptNode({});
873 const auto parameterList = scriptNodeStack.takeLast().takeList();
874 const auto ¶meterQList = parameterList.qList();
875 size_t size = (size_t)parameterQList.size();
876 for (size_t idx = size - 1; idx < size; --idx) {
878 nodeStack.last().fileLocations,
883 setFormalParameterKind(variant);
884 finalizeScriptExpression(variant, pathToArgument, argLoc);
885 m.parameters[idx].value->setScriptElement(variant);
890 if (m_enableScriptExpressions && !scriptNodeStack.empty()) {
897 if (AST::cast<VariableStatement *>(el->sourceElement))
903 valueFromMultimap(obj.m_methods, m.name, *nodeStack.last().path.last().headIndex());
912 scope.setName(toString(el->qualifiedTypeNameId));
916 if (!arrayBindingLevels.isEmpty() && nodeStack.size() == arrayBindingLevels.last()) {
918 QList<QmlObject> *vals =
std::get<
Binding>(currentNode().value).arrayValue();
920 int idx = vals->size();
922 sPathFromOwner = currentNodeEl().path.withField(
Fields::value).withIndex(idx);
923 sPtr = &((*vals)[idx]);
926 Q_ASSERT_X(
false, className,
927 "expected an array binding with a valid QList<QmlScope> as value");
930 Q_ASSERT_X(
false, className,
"expected an array binding as last node on the stack");
933 DomValue &containingObject = currentQmlObjectOrComponentEl().item;
934 switch (containingObject.kind) {
936 sPathFromOwner =
std::get<QmlComponent>(containingObject.value).addObject(scope, &sPtr);
939 sPathFromOwner =
std::get<
QmlObject>(containingObject.value).addChild(scope, &sPtr);
944 Path pathFromContainingObject = sPathFromOwner.mid(currentNodeEl().path.length());
946 FileLocations::ensure(currentNodeEl().fileLocations, pathFromContainingObject);
948 el->qualifiedTypeNameId->identifierToken);
950 Q_ASSERT_X(sPtr, className,
"could not recover new scope");
952 if (m_enableScriptExpressions) {
953 auto qmlObjectType = makeGenericScriptElement(el->qualifiedTypeNameId,
DomType::ScriptType);
954 qmlObjectType->insertChild(
Fields::typeName,
955 fieldMemberExpressionForQualifiedId(el->qualifiedTypeNameId));
960 pushEl(sPathFromOwner, *sPtr, el);
962 if (el->initializer) {
964 el->initializer->lbraceToken);
966 el->initializer->rbraceToken);
975 int idx = currentIndex();
976 if (!arrayBindingLevels.isEmpty() && nodeStack.size() == arrayBindingLevels.last() + 1) {
979 QList<QmlObject> *vals = b.arrayValue();
980 Q_ASSERT_X(vals, className,
981 "expected an array binding with a valid QList<QmlScope> as value");
984 Q_ASSERT_X(
false, className,
"expected an array binding as last node on the stack");
987 DomValue &containingObject = currentNodeEl(1).item;
988 Path p = currentNodeEl().path;
989 switch (containingObject.kind) {
992 std::get<QmlComponent>(containingObject.value).m_objects[idx] = obj;
998 std::get<
QmlObject>(containingObject.value).m_children[idx] = obj;
1010 const UiQualifiedId *identifiers,
Binding *bindingPtr)
1012 const bool skipBindingIdentifiers =
std::exchange(m_skipBindingIdentifiers,
false);
1013 if (!m_enableScriptExpressions || skipBindingIdentifiers)
1025 value.setName(toString(el->qualifiedTypeNameId));
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);
1037 pushEl(bPathFromOwner, *bPtr, el);
1043 loadAnnotations(el);
1045 Q_ASSERT_X(objValue, className,
"could not recover objectValue");
1046 objValue->setName(toString(el->qualifiedTypeNameId));
1048 if (m_enableScriptExpressions) {
1049 auto qmlObjectType = makeGenericScriptElement(el->qualifiedTypeNameId,
DomType::ScriptType);
1050 qmlObjectType->insertChild(
Fields::typeName,
1051 fieldMemberExpressionForQualifiedId(el->qualifiedTypeNameId));
1058 pushEl(bPathFromOwner.withField(Fields::value), *objValue, el->initializer);
1059 if (m_enableScriptExpressions && el->initializer) {
1061 el->initializer->lbraceToken);
1063 el->initializer->rbraceToken);
1076 index_type idx = *currentNodeEl(1).path.last().headIndex();
1077 Binding *bPtr = valueFromMultimap(containingObj.m_bindings, b.name(), idx);
1086 ++m_nestedFunctionDepth;
1087 QStringView code = qmlFilePtr->code();
1088 SourceLocation loc = combineLocations(el->statement);
1090 code.mid(loc.offset, loc.length), qmlFilePtr->engine(), el->statement,
1091 qmlFilePtr->astComments(), ScriptExpression::ExpressionType::BindingExpression, loc);
1093 Binding *bindingPtr =
nullptr;
1094 Id *idPtr =
nullptr;
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>();
1103 QString idName = iExp->name.toString();
1104 Id idVal(idName, qmlFile.canonicalPath().withPath(containingObject.pathFromOwner()));
1105 idVal.value = script;
1106 containingObject.setIdStr(idName);
1108 combineLocations(el->qualifiedId));
1112 iExp->identifierToken);
1113 QmlComponent &comp = current<QmlComponent>();
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)));
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(
1133 .warning(tr(m).arg(script->code(), script->astRelocatableDump()))
1134 .withPath(pathFromOwner)));
1139 QmlStackElement &containingObjectEl = currentEl<
QmlObject>();
1141 Path pathFromContainingObject = pathFromOwner.mid(containingObjectEl.path.length());
1142 auto bindingFileLocation =
1145 el->qualifiedId->identifierToken);
1148 setBindingIdentifiers(pathFromOwner, el->qualifiedId, bindingPtr);
1150 Q_ASSERT_X(bindingPtr, className,
"binding could not be retrieved");
1153 pushEl(pathFromOwner, *bindingPtr, el);
1155 pushEl(pathFromOwner, *idPtr, el);
1158 loadAnnotations(el);
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),
1175 removeCurrentScriptNode({});
1181 --m_nestedFunctionDepth;
1182 DomValue &lastEl = currentNode();
1183 index_type idx = currentIndex();
1190 Binding *bPtr = valueFromMultimap(containingObject.m_bindings, b.name(), idx);
1194 Id &id =
std::get<
Id>(lastEl.value);
1196 setScriptExpression(id.value);
1198 QmlComponent &comp = current<QmlComponent>();
1199 Id *idPtr = valueFromMultimap(comp.m_ids, id.name, idx);
1206 if (m_enableScriptExpressions && !scriptNodeStack.empty()) {
1209 removeCurrentNode({});
1214 QList<QmlObject> value;
1217 Path bindingPathFromOwner =
1219 if (bindingV.name() == u"id")
1220 qmlFile.addError(std::move(
1222 .error(tr(
"id attributes should have only simple strings as values"))
1223 .withPath(bindingPathFromOwner)));
1225 setBindingIdentifiers(bindingPathFromOwner, el->qualifiedId, bindingPtr);
1227 pushEl(bindingPathFromOwner, *bindingPtr, el);
1229 loadAnnotations(el);
1231 createMap(currentNodeEl().fileLocations, Path::fromField(Fields::value),
nullptr);
1234 arrayBindingLevels.append(nodeStack.size());
1240 index_type idx = currentIndex();
1242 Binding *bPtr = valueFromMultimap(current<
QmlObject>().m_bindings, b.name(), idx);
1244 arrayBindingLevels.removeLast();
1250 endVisitForLists(list);
1260 endVisitForLists<AST::PatternElementList>(list, [](AST::PatternElementList *current) {
1262 toCollect +=
bool(current->elision);
1263 toCollect +=
bool(current->element);
1270 endVisitForLists(list);
1274
1275
1276
1277
1278
1282 expression->firstSourceLocation(), expression->lastSourceLocation());
1283 id->setName(expression->toString());
1290 if (!m_enableScriptExpressions)
1299 eDecl.setName(el->name.toString());
1301 Path enumPathFromOwner =
1303 pushEl(enumPathFromOwner, *ePtr, el);
1308 loadAnnotations(el);
1314 EnumDecl &e =
std::get<EnumDecl>(currentNode().value);
1316 valueFromMultimap(current<QmlComponent>().m_enumerations, e.name(), currentIndex());
1324 EnumItem it(el->member.toString(), el->value,
1327 EnumDecl &eDecl =
std::get<EnumDecl>(currentNode().value);
1329 const auto map = createMap(DomType::EnumItem, itPathFromDecl,
nullptr);
1330 if (el->commaToken.isValid())
1332 if (el->memberToken.isValid())
1334 if (el->equalToken.isValid())
1336 if (el->valueToken.isValid())
1339 map, MainRegion, combine(combine(el->memberToken, el->commaToken), el->valueToken));
1345 Node::accept(el->next,
this);
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);
1356 if (m_enableScriptExpressions) {
1357 auto inlineComponentType =
1361 typeName->setName(el->name);
1362 inlineComponentType->insertChild(
Fields::typeName,
1369 pushEl(p, *compPtr, el);
1371 el->componentToken);
1373 loadAnnotations(el);
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());
1391 pDef.name = el->name.toString();
1394 Path pathFromOwner =
1396 createMap(DomType::PropertyDefinition, pathFromOwner, el);
1403 a.setName(QStringLiteral(u"@") + toString(el->qualifiedTypeNameId));
1405 DomValue &containingElement = currentNode();
1408 switch (containingElement.kind) {
1410 pathFromOwner =
std::get<
QmlObject>(containingElement.value).addAnnotation(a, &aPtr);
1413 pathFromOwner =
std::get<
Binding>(containingElement.value)
1414 .addAnnotation(currentNodeEl().path, a, &aPtr);
1418 std::get<
Id>(containingElement.value).addAnnotation(currentNodeEl().path, a, &aPtr);
1422 .addAnnotation(currentNodeEl().path, a, &aPtr);
1425 pathFromOwner =
std::get<
MethodInfo>(containingElement.value)
1426 .addAnnotation(currentNodeEl().path, a, &aPtr);
1429 qCWarning(domLog) <<
"Unexpected container object for annotation:"
1430 << domTypeToString(containingElement.kind);
1433 pushEl(pathFromOwner, *aPtr, el);
1439 DomValue &containingElement = currentNode(1);
1442 switch (containingElement.kind) {
1443 case DomType::QmlObject:
1444 std::get<QmlObject>(containingElement.value).m_annotations[currentIndex()] = a;
1446 case DomType::Binding:
1447 std::get<Binding>(containingElement.value).m_annotations[currentIndex()] = a;
1450 std::get<Id>(containingElement.value).annotations[currentIndex()] = a;
1452 case DomType::PropertyDefinition:
1453 std::get<PropertyDefinition>(containingElement.value).annotations[currentIndex()] = a;
1455 case DomType::MethodInfo:
1456 std::get<MethodInfo>(containingElement.value).annotations[currentIndex()] = a;
1466 qmlFile.addError(astParseErrors().error(
1467 tr(
"Maximum statement or expression depth exceeded in QmlDomAstCreator")));
1472 endVisitForLists(list);
1477 if (!m_enableScriptExpressions)
1485 if (!m_enableScriptExpressions)
1489 current->addLocation(OperatorTokenRegion, exp->operatorToken);
1491 current->setRight(currentScriptNodeEl().takeVariant());
1492 removeCurrentScriptNode({});
1494 current->setLeft(currentScriptNodeEl().takeVariant());
1495 removeCurrentScriptNode({});
1497 pushScriptElement(current);
1502 if (!m_enableScriptExpressions)
1510 if (!m_enableScriptExpressions)
1515 if (block->statements) {
1517 current->setStatements(currentScriptNodeEl().takeList());
1521 pushScriptElement(current);
1526 if (!m_enableScriptExpressions)
1534 if (!m_enableScriptExpressions)
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);
1546 if (forStatement->statement) {
1548 current->setBody(currentScriptNodeEl().takeVariant());
1549 removeCurrentScriptNode(
std::nullopt);
1552 if (forStatement->expression) {
1554 current->setExpression(currentScriptNodeEl().takeVariant());
1555 removeCurrentScriptNode(
std::nullopt);
1558 if (forStatement->condition) {
1560 current->setCondition(currentScriptNodeEl().takeVariant());
1561 removeCurrentScriptNode(
std::nullopt);
1564 if (forStatement->declarations) {
1566 auto variableDeclaration = makeGenericScriptElement(forStatement->declarations,
1572 variableDeclaration->insertChild(
Fields::declarations,
std::move(list));
1573 removeCurrentScriptNode({});
1577 if (
auto pe = forStatement->declarations->declaration;
1578 pe && pe->declarationKindToken.isValid()) {
1579 current->addLocation(FileLocationRegion::TypeIdentifierRegion,
1580 pe->declarationKindToken);
1584 if (forStatement->initialiser) {
1586 current->setInitializer(currentScriptNodeEl().takeVariant());
1587 removeCurrentScriptNode(
std::nullopt);
1589 pushScriptElement(current);
1594 if (!m_enableScriptExpressions)
1598 current->setName(expression->name);
1599 pushScriptElement(current);
1605 if (!m_enableScriptExpressions)
1609 current->setLiteralValue(expression->value);
1610 pushScriptElement(current);
1616 if (!m_enableScriptExpressions)
1619 pushScriptElement(makeStringLiteral(expression->value, expression));
1625 if (!m_enableScriptExpressions)
1629 current->setLiteralValue(
nullptr);
1630 pushScriptElement(current);
1636 if (!m_enableScriptExpressions)
1640 current->setLiteralValue(
true);
1641 pushScriptElement(current);
1647 if (!m_enableScriptExpressions)
1651 current->setLiteralValue(
false);
1652 pushScriptElement(current);
1658 if (!m_enableScriptExpressions)
1662 current->setName(expression->id);
1663 pushScriptElement(current);
1669 if (!m_enableScriptExpressions)
1672 pushScriptElement(makeStringLiteral(expression->id, expression));
1678 if (!m_enableScriptExpressions)
1687 if (!m_enableScriptExpressions)
1691 current->insertValue(
Fields::regExpPattern, literal->pattern);
1692 current->insertValue(
Fields::regExpFlags, literal->flags);
1693 pushScriptElement(current);
1700 if (!m_enableScriptExpressions)
1704 if (expression->thisToken.isValid())
1705 current->addLocation(ThisKeywordRegion, expression->thisToken);
1706 pushScriptElement(current);
1712 if (!m_enableScriptExpressions)
1716 if (expression->superToken.isValid())
1717 current->addLocation(SuperKeywordRegion, expression->superToken);
1718 pushScriptElement(current);
1724 if (!m_enableScriptExpressions)
1728 current->setLiteralValue(expression->id);
1729 pushScriptElement(current);
1735 if (!m_enableScriptExpressions)
1744 const std::function<
int(T *)> &scriptElementsPerEntry)
1746 if (!m_enableScriptExpressions)
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) {
1754 auto last = scriptNodeStack.takeLast();
1756 current.append(last.takeList());
1758 current.append(last.takeVariant());
1763 pushScriptElement(current);
1768 endVisitForLists(list);
1773 if (!m_enableScriptExpressions)
1776 auto currentList = makeScriptList(list);
1778 for (
auto it = list; it; it = it->next) {
1782 pushScriptElement(currentList);
1790 if (!m_enableScriptExpressions)
1797
1798
1799
1800
1802 AST::PatternElement *pe,
1805 if (pe->equalToken.isValid())
1806 current->addLocation(FileLocationRegion::EqualTokenRegion, pe->equalToken);
1808 if (pe->identifierToken.isValid() && !pe->bindingIdentifier.isEmpty()) {
1811 identifier->setName(pe->bindingIdentifier);
1812 current->insertChild(Fields::identifier, ScriptElementVariant::fromElement(identifier));
1814 if (pe->initializer) {
1816 current->insertChild(Fields::initializer, scriptNodeStack.last().takeVariant());
1817 scriptNodeStack.removeLast();
1819 if (pe->typeAnnotation) {
1821 current->insertChild(Fields::type, scriptNodeStack.last().takeVariant());
1822 scriptNodeStack.removeLast();
1824 if (pe->bindingTarget) {
1826 current->insertChild(Fields::bindingElement, scriptNodeStack.last().takeVariant());
1827 scriptNodeStack.removeLast();
1833 if (!m_enableScriptExpressions)
1837 endVisitHelper(pe, element);
1839 if (!m_enableScriptExpressions)
1842 pushScriptElement(element);
1847 if (!m_enableScriptExpressions)
1855 if (!m_enableScriptExpressions)
1859 current->addLocation(LeftParenthesisRegion, ifStatement->lparenToken);
1860 current->addLocation(RightParenthesisRegion, ifStatement->rparenToken);
1861 current->addLocation(ElseKeywordRegion, ifStatement->elseToken);
1862 current->addLocation(IfKeywordRegion, ifStatement->ifToken);
1864 if (ifStatement->ko) {
1866 current->setAlternative(scriptNodeStack.last().takeVariant());
1867 scriptNodeStack.removeLast();
1870 if (ifStatement->ok) {
1872 current->setConsequence(scriptNodeStack.last().takeVariant());
1873 scriptNodeStack.removeLast();
1875 if (ifStatement->expression) {
1877 current->setCondition(scriptNodeStack.last().takeVariant());
1878 scriptNodeStack.removeLast();
1881 pushScriptElement(current);
1886 if (!m_enableScriptExpressions)
1894 if (!m_enableScriptExpressions)
1898 current->addLocation(ReturnKeywordRegion, returnStatement->returnToken);
1900 if (returnStatement->expression) {
1902 current->setExpression(currentScriptNodeEl().takeVariant());
1903 removeCurrentScriptNode({});
1906 pushScriptElement(current);
1911 if (!m_enableScriptExpressions)
1919 if (!m_enableScriptExpressions)
1923 current->addLocation(YieldKeywordRegion, yExpression->yieldToken);
1925 if (yExpression->expression) {
1927 current->insertChild(
Fields::expression, currentScriptNodeEl().takeVariant());
1928 removeCurrentScriptNode({});
1931 pushScriptElement(current);
1936 if (!m_enableScriptExpressions)
1944 if (!m_enableScriptExpressions)
1949 current->addLocation(FileLocationRegion::OperatorTokenRegion, expression->dotToken);
1951 if (expression->base) {
1953 current->setLeft(currentScriptNodeEl().takeVariant());
1954 removeCurrentScriptNode({});
1957 auto scriptIdentifier =
1959 scriptIdentifier->setName(expression->name);
1962 pushScriptElement(current);
1967 if (!m_enableScriptExpressions)
1975 if (!m_enableScriptExpressions)
1980 current->addLocation(FileLocationRegion::OperatorTokenRegion, expression->lbracketToken);
1982 if (expression->expression) {
1986 current->setRight(currentScriptNodeEl().takeVariant());
1987 removeCurrentScriptNode({});
1990 if (expression->base) {
1992 current->setLeft(currentScriptNodeEl().takeVariant());
1993 removeCurrentScriptNode({});
1996 pushScriptElement(current);
2001 if (!m_enableScriptExpressions)
2009 if (!m_enableScriptExpressions)
2013 current->addLocation(LeftParenthesisRegion, exp->lparenToken);
2014 current->addLocation(RightParenthesisRegion, exp->rparenToken);
2016 if (exp->arguments) {
2018 current->insertChild(
Fields::arguments, currentScriptNodeEl().takeList());
2019 removeCurrentScriptNode({});
2022 current->insertChild(
Fields::arguments,
2028 current->insertChild(
Fields::callee, currentScriptNodeEl().takeVariant());
2029 removeCurrentScriptNode({});
2032 pushScriptElement(current);
2037 if (!m_enableScriptExpressions)
2045 if (!m_enableScriptExpressions)
2050 if (exp->elements) {
2054 current->insertChild(
Fields::elements,
std::move(list));
2056 removeCurrentScriptNode({});
2059 current->insertChild(
Fields::elements,
2063 pushScriptElement(current);
2068 if (!m_enableScriptExpressions)
2076 if (!m_enableScriptExpressions)
2081 if (exp->properties) {
2083 current->insertChild(
Fields::properties, currentScriptNodeEl().takeList());
2084 removeCurrentScriptNode({});
2087 current->insertChild(
Fields::properties,
2091 pushScriptElement(current);
2096 if (!m_enableScriptExpressions)
2104 if (!m_enableScriptExpressions)
2110 endVisitHelper(
static_cast<PatternElement *>(exp), current);
2113 if (!m_enableScriptExpressions)
2118 current->insertChild(
Fields::name, currentScriptNodeEl().takeVariant());
2119 removeCurrentScriptNode({});
2122 pushScriptElement(current);
2127 if (!m_enableScriptExpressions)
2135 if (!m_enableScriptExpressions)
2139 current->addLocation(FileLocationRegion::TypeIdentifierRegion, statement->declarationKindToken);
2141 if (statement->declarations) {
2147 current->insertChild(
Fields::declarations,
std::move(list));
2149 removeCurrentScriptNode({});
2152 pushScriptElement(current);
2157 if (!m_enableScriptExpressions)
2165 if (!m_enableScriptExpressions)
2170 if (exp->typeArgument) {
2171 current->insertChild(
Fields::typeArgumentName,
2172 fieldMemberExpressionForQualifiedId(exp->typeArgument));
2173 current->addLocation(FileLocationRegion::IdentifierRegion, combineLocations(exp->typeArgument));
2177 current->insertChild(
Fields::typeName, fieldMemberExpressionForQualifiedId(exp->typeId));
2178 current->addLocation(FileLocationRegion::TypeIdentifierRegion, combineLocations(exp->typeId));
2181 pushScriptElement(current);
2186 if (!m_enableScriptExpressions)
2194 if (!m_enableScriptExpressions)
2198 current->addLocation(DefaultKeywordRegion, exp->defaultToken);
2199 current->addLocation(ColonTokenRegion, exp->colonToken);
2201 if (exp->statements) {
2203 current->insertChild(
Fields::statements, currentScriptNodeEl().takeList());
2204 removeCurrentScriptNode({});
2207 pushScriptElement(current);
2212 if (!m_enableScriptExpressions)
2220 if (!m_enableScriptExpressions)
2224 current->addLocation(FileLocationRegion::CaseKeywordRegion, exp->caseToken);
2225 current->addLocation(FileLocationRegion::ColonTokenRegion, exp->colonToken);
2227 if (exp->statements) {
2229 current->insertChild(
Fields::statements, currentScriptNodeEl().takeList());
2230 removeCurrentScriptNode({});
2233 if (exp->expression) {
2235 current->insertChild(
Fields::expression, currentScriptNodeEl().takeVariant());
2236 removeCurrentScriptNode({});
2239 pushScriptElement(current);
2244 if (!m_enableScriptExpressions)
2252 if (!m_enableScriptExpressions)
2255 auto current = makeScriptList(list);
2257 for (
auto it = list; it; it = it->next) {
2259 current.append(scriptNodeStack.takeLast().takeVariant());
2263 pushScriptElement(current);
2268 if (!m_enableScriptExpressions)
2276 if (!m_enableScriptExpressions)
2280 current->addLocation(FileLocationRegion::LeftBraceRegion, exp->lbraceToken);
2281 current->addLocation(FileLocationRegion::RightBraceRegion, exp->rbraceToken);
2283 if (exp->moreClauses) {
2285 current->insertChild(
Fields::moreCaseClauses, currentScriptNodeEl().takeList());
2286 removeCurrentScriptNode({});
2289 if (exp->defaultClause) {
2291 current->insertChild(
Fields::defaultClause, currentScriptNodeEl().takeVariant());
2292 removeCurrentScriptNode({});
2297 current->insertChild(
Fields::caseClauses, currentScriptNodeEl().takeList());
2298 removeCurrentScriptNode({});
2300 pushScriptElement(current);
2305 if (!m_enableScriptExpressions)
2313 if (!m_enableScriptExpressions)
2317 current->addLocation(FileLocationRegion::SwitchKeywordRegion, exp->switchToken);
2318 current->addLocation(FileLocationRegion::LeftParenthesisRegion, exp->lparenToken);
2319 current->addLocation(FileLocationRegion::RightParenthesisRegion, exp->rparenToken);
2323 current->insertChild(
Fields::caseBlock, currentScriptNodeEl().takeVariant());
2324 removeCurrentScriptNode({});
2326 if (exp->expression) {
2328 current->insertChild(
Fields::expression, currentScriptNodeEl().takeVariant());
2329 removeCurrentScriptNode({});
2332 pushScriptElement(current);
2337 if (!m_enableScriptExpressions)
2345 if (!m_enableScriptExpressions)
2349 current->addLocation(FileLocationRegion::WhileKeywordRegion, exp->whileToken);
2350 current->addLocation(FileLocationRegion::LeftParenthesisRegion, exp->lparenToken);
2351 current->addLocation(FileLocationRegion::RightParenthesisRegion, exp->rparenToken);
2353 if (exp->statement) {
2355 current->insertChild(
Fields::body, currentScriptNodeEl().takeVariant());
2356 removeCurrentScriptNode({});
2359 if (exp->expression) {
2361 current->insertChild(
Fields::expression, currentScriptNodeEl().takeVariant());
2362 removeCurrentScriptNode({});
2365 pushScriptElement(current);
2370 if (!m_enableScriptExpressions)
2378 if (!m_enableScriptExpressions)
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);
2387 if (exp->expression) {
2389 current->insertChild(
Fields::expression, currentScriptNodeEl().takeVariant());
2390 removeCurrentScriptNode({});
2393 if (exp->statement) {
2395 current->insertChild(
Fields::body, currentScriptNodeEl().takeVariant());
2396 removeCurrentScriptNode({});
2399 pushScriptElement(current);
2404 if (!m_enableScriptExpressions)
2412 if (!m_enableScriptExpressions)
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);
2421 if (exp->statement) {
2423 current->insertChild(
Fields::body, currentScriptNodeEl().takeVariant());
2424 removeCurrentScriptNode({});
2426 if (exp->expression) {
2428 current->insertChild(
Fields::expression, currentScriptNodeEl().takeVariant());
2429 removeCurrentScriptNode({});
2434 current->insertChild(
Fields::bindingElement, currentScriptNodeEl().takeVariant());
2435 removeCurrentScriptNode({});
2437 if (
auto pe = AST::cast<PatternElement *>(exp->lhs);
2438 pe && pe->declarationKindToken.isValid()) {
2439 current->addLocation(FileLocationRegion::TypeIdentifierRegion,
2440 pe->declarationKindToken);
2444 pushScriptElement(current);
2452 if (m_enableScriptExpressions)
2463 if (!m_enableScriptExpressions)
2467 current->insertChild(
Fields::templateLiteral, scriptNodeStack.takeLast().takeVariant());
2469 current->insertChild(
Fields::callee, scriptNodeStack.takeLast().takeVariant());
2470 pushScriptElement(current);
2474
2475
2476
2477
2478
2479enum TemplatePartPosition : quint8 {
2485Q_DECLARE_FLAGS(TemplatePartPositions, TemplatePartPosition)
2488
2489
2490
2491
2492static void extractDollarBraceSourceLocationInto(
2494 const SourceLocation &toBeSplit, QStringView code,
2495 TemplatePartPositions templatePartLocation)
2497 if (templatePartLocation & AtEnd || !currentExpression)
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 });
2509
2510
2511
2512static void extractRightBacktickSourceLocationInto(
2514 const SourceLocation &toBeSplit, QStringView code,
2515 TemplatePartPositions templatePartLocation)
2517 if (!(templatePartLocation & AtEnd))
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 });
2528
2529
2530
2531static void extractLeftBacktickSourceLocationInto(
2533 const SourceLocation &toBeSplit, TemplatePartPositions templatePartLocation)
2535 if (!(templatePartLocation & AtBeginning))
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);
2545
2546
2547
2548
2549static SourceLocation extractRightBraceSourceLocation(
const SourceLocation &toBeSplit,
2550 TemplatePartPositions templatePartLocation)
2552 if (templatePartLocation & AtBeginning)
2553 return SourceLocation{};
2556 return SourceLocation{ toBeSplit.offset, 1, toBeSplit.startLine, toBeSplit.startColumn };
2560
2561
2562
2563
2564static SourceLocation extractStringLocation(
const SourceLocation &toBeSplit, QStringView code,
2565 TemplatePartPositions 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 };
2577 if (!m_enableScriptExpressions)
2582 auto currentList = makeScriptList(literal);
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);
2593 SourceLocation rightBrace;
2594 for (
auto it = children.crbegin(); it != children.crend(); ++it) {
2596 const QQmlJS::SourceLocation toBeSplit = (*it)->literalToken;
2599 if ((*it)->expression) {
2601 currentExpression = makeGenericScriptElement((*it)->expression,
2604 currentExpression->insertChild(
Fields::expression,
2605 scriptNodeStack.takeLast().takeVariant());
2606 if (rightBrace.isValid()) {
2607 currentExpression->addLocation(FileLocationRegion::RightBraceRegion,
2608 std::exchange(rightBrace, SourceLocation{}));
2613 if (!toBeSplit.isValid())
2616 const TemplatePartPositions location = [&it, &children]() {
2617 TemplatePartPositions result;
2618 if (it == children.crbegin())
2620 if (it ==
std::prev(children.crend()))
2621 result |= AtBeginning;
2625 extractRightBacktickSourceLocationInto(currentTemplate, toBeSplit, qmlFilePtr->code(),
2627 extractLeftBacktickSourceLocationInto(currentTemplate, toBeSplit, location);
2629 extractDollarBraceSourceLocationInto(currentExpression, toBeSplit, qmlFilePtr->code(),
2631 rightBrace = extractRightBraceSourceLocation(toBeSplit, location);
2633 if ((*it)->rawValue.isEmpty())
2636 const SourceLocation stringLocation =
2637 extractStringLocation(toBeSplit, qmlFilePtr->code(), location);
2638 auto currentString =
2640 currentString->insertValue(
Fields::value, (*it)->rawValue);
2644 currentList.reverse();
2646 currentTemplate->insertChild(
Fields::components, currentList);
2647 pushScriptElement(currentTemplate);
2652 return m_enableScriptExpressions;
2657 if (!m_enableScriptExpressions)
2661 current->addLocation(FileLocationRegion::TryKeywordRegion, statement->tryToken);
2663 if (
auto exp = statement->finallyExpression) {
2664 current->addLocation(FileLocationRegion::FinallyKeywordRegion, exp->finallyToken);
2667 current->insertChild(
Fields::finallyBlock, currentScriptNodeEl().takeVariant());
2668 removeCurrentScriptNode({});
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);
2677 current->insertChild(
Fields::catchBlock, currentScriptNodeEl().takeVariant());
2678 removeCurrentScriptNode({});
2680 current->insertChild(
Fields::catchParameter, currentScriptNodeEl().takeVariant());
2681 removeCurrentScriptNode({});
2684 if (statement->statement) {
2686 current->insertChild(
Fields::block, currentScriptNodeEl().takeVariant());
2687 removeCurrentScriptNode({});
2690 pushScriptElement(current);
2696 return m_enableScriptExpressions;
2707 return m_enableScriptExpressions;
2717 return m_enableScriptExpressions;
2722 if (!m_enableScriptExpressions)
2726 current->addLocation(FileLocationRegion::ThrowKeywordRegion, statement->throwToken);
2728 if (statement->expression) {
2730 current->insertChild(
Fields::expression, currentScriptNodeEl().takeVariant());
2731 removeCurrentScriptNode({});
2734 pushScriptElement(current);
2739 return m_enableScriptExpressions;
2744 if (!m_enableScriptExpressions)
2748 current->addLocation(FileLocationRegion::ColonTokenRegion, statement->colonToken);
2751 label->setName(statement->label);
2755 if (statement->statement) {
2757 current->insertChild(
Fields::statement, currentScriptNodeEl().takeVariant());
2758 removeCurrentScriptNode({});
2761 pushScriptElement(current);
2766 return m_enableScriptExpressions;
2771 if (!m_enableScriptExpressions)
2775 current->addLocation(FileLocationRegion::BreakKeywordRegion, statement->breakToken);
2777 if (!statement->label.isEmpty()) {
2780 label->setName(statement->label);
2784 pushScriptElement(current);
2789 return m_enableScriptExpressions;
2794 if (!m_enableScriptExpressions)
2798 current->addLocation(OperatorTokenRegion, commaExpression->commaToken);
2800 if (commaExpression->right) {
2802 current->setRight(currentScriptNodeEl().takeVariant());
2803 removeCurrentScriptNode({});
2806 if (commaExpression->left) {
2808 current->setLeft(currentScriptNodeEl().takeVariant());
2809 removeCurrentScriptNode({});
2812 pushScriptElement(current);
2817 return m_enableScriptExpressions;
2822 if (!m_enableScriptExpressions)
2826 current->addLocation(FileLocationRegion::QuestionMarkTokenRegion, expression->questionToken);
2827 current->addLocation(FileLocationRegion::ColonTokenRegion, expression->colonToken);
2829 if (expression->ko) {
2831 current->insertChild(
Fields::alternative, currentScriptNodeEl().takeVariant());
2832 removeCurrentScriptNode({});
2835 if (expression->ok) {
2837 current->insertChild(
Fields::consequence, currentScriptNodeEl().takeVariant());
2838 removeCurrentScriptNode({});
2841 if (expression->expression) {
2843 current->insertChild(
Fields::condition, currentScriptNodeEl().takeVariant());
2844 removeCurrentScriptNode({});
2847 pushScriptElement(current);
2852 return m_enableScriptExpressions;
2857 if (!m_enableScriptExpressions)
2861 current->addLocation(FileLocationRegion::ContinueKeywordRegion, statement->continueToken);
2863 if (!statement->label.isEmpty()) {
2866 label->setName(statement->label);
2870 pushScriptElement(current);
2874
2875
2876
2877
2879QQmlDomAstCreatorBase::makeUnaryExpression(AST::Node *expression, QQmlJS::SourceLocation operatorToken,
2880 bool hasExpression, UnaryExpressionKind kind)
2882 const DomType type = [&kind]() {
2892 auto current = makeGenericScriptElement(expression, type);
2893 current->addLocation(FileLocationRegion::OperatorTokenRegion, operatorToken);
2895 if (hasExpression) {
2900 current->insertChild(
Fields::expression, currentScriptNodeEl().takeVariant());
2901 removeCurrentScriptNode({});
2909 return m_enableScriptExpressions;
2914 if (!m_enableScriptExpressions)
2918 makeUnaryExpression(statement, statement->minusToken, statement->expression, Prefix);
2922 pushScriptElement(current);
2927 return m_enableScriptExpressions;
2932 if (!m_enableScriptExpressions)
2936 makeUnaryExpression(statement, statement->plusToken, statement->expression, Prefix);
2940 pushScriptElement(current);
2945 return m_enableScriptExpressions;
2950 if (!m_enableScriptExpressions)
2954 makeUnaryExpression(statement, statement->tildeToken, statement->expression, Prefix);
2958 pushScriptElement(current);
2963 return m_enableScriptExpressions;
2968 if (!m_enableScriptExpressions)
2972 makeUnaryExpression(statement, statement->notToken, statement->expression, Prefix);
2976 pushScriptElement(current);
2981 return m_enableScriptExpressions;
2986 if (!m_enableScriptExpressions)
2990 makeUnaryExpression(statement, statement->typeofToken, statement->expression, Prefix);
2994 pushScriptElement(current);
2999 return m_enableScriptExpressions;
3004 if (!m_enableScriptExpressions)
3008 makeUnaryExpression(statement, statement->deleteToken, statement->expression, Prefix);
3012 pushScriptElement(current);
3017 return m_enableScriptExpressions;
3022 if (!m_enableScriptExpressions)
3026 makeUnaryExpression(statement, statement->voidToken, statement->expression, Prefix);
3030 pushScriptElement(current);
3035 return m_enableScriptExpressions;
3040 if (!m_enableScriptExpressions)
3044 makeUnaryExpression(statement, statement->decrementToken, statement->base, Postfix);
3048 pushScriptElement(current);
3053 return m_enableScriptExpressions;
3058 if (!m_enableScriptExpressions)
3062 makeUnaryExpression(statement, statement->incrementToken, statement->base, Postfix);
3066 pushScriptElement(current);
3071 return m_enableScriptExpressions;
3076 if (!m_enableScriptExpressions)
3079 auto current = makeUnaryExpression(statement, statement->incrementToken, statement->expression,
3084 pushScriptElement(current);
3089 return m_enableScriptExpressions;
3094 if (!m_enableScriptExpressions)
3098 current->addLocation(FileLocationRegion::SemicolonTokenRegion, statement->semicolonToken);
3099 pushScriptElement(current);
3104 return m_enableScriptExpressions;
3109 if (!m_enableScriptExpressions)
3113 current->addLocation(FileLocationRegion::LeftParenthesisRegion, expression->lparenToken);
3114 current->addLocation(FileLocationRegion::RightParenthesisRegion, expression->rparenToken);
3116 if (expression->expression) {
3118 current->insertChild(
Fields::expression, currentScriptNodeEl().takeVariant());
3119 removeCurrentScriptNode({});
3122 pushScriptElement(current);
3127 return m_enableScriptExpressions;
3132 if (!m_enableScriptExpressions)
3136 current->addLocation(FileLocationRegion::NewKeywordRegion, expression->newToken);
3138 if (expression->expression) {
3140 current->insertChild(
Fields::expression, currentScriptNodeEl().takeVariant());
3141 removeCurrentScriptNode({});
3144 pushScriptElement(current);
3149 return m_enableScriptExpressions;
3154 if (!m_enableScriptExpressions)
3158 current->addLocation(FileLocationRegion::NewKeywordRegion, expression->newToken);
3159 current->addLocation(FileLocationRegion::LeftParenthesisRegion, expression->lparenToken);
3160 current->addLocation(FileLocationRegion::RightParenthesisRegion, expression->rparenToken);
3162 if (expression->arguments) {
3164 current->insertChild(
Fields::arguments, scriptNodeStack.takeLast().takeList());
3166 if (expression->base) {
3168 current->insertChild(
Fields::base, scriptNodeStack.takeLast().takeVariant());
3171 pushScriptElement(current);
3176 if (!m_enableScriptExpressions)
3181 if (ast->statement) {
3183 current->insertChild(
Fields::statement, scriptNodeStack.takeLast().takeVariant());
3185 if (ast->expression) {
3187 current->insertChild(
Fields::expression, scriptNodeStack.takeLast().takeVariant());
3190 pushScriptElement(current);
3195 return m_enableScriptExpressions;
3200 if (!m_enableScriptExpressions)
3203 auto current = makeUnaryExpression(statement, statement->decrementToken, statement->expression,
3208 pushScriptElement(current);
3212 QQmlJSLogger *logger,
3213 QQmlJSImporter *importer)
3224 bool QQmlDomAstCreatorWithQQmlJSScope::visit(name *node)
3226 return visitT(node);
3228 void QQmlDomAstCreatorWithQQmlJSScope::endVisit(name *node)
3232QQmlJSASTClassListToVisit
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) {
3243 if (scope->scopeType() == QQmlJSScope::ScopeType::QMLScope)
3244 m_domCreator.currentScriptNodeEl().setSemanticScope(scope);
3247 case DomType::ScriptBlockStatement:
3248 case DomType::ScriptForStatement:
3249 case DomType::ScriptForEachStatement:
3250 case DomType::ScriptDoWhileStatement:
3251 case DomType::ScriptWhileStatement:
3253 m_domCreator.currentScriptNodeEl().setSemanticScope(scope);
3258 auto element = m_domCreator.currentScriptNodeEl().value;
3260 if (!scriptElementVariant || !scriptElementVariant->data())
3262 scriptElementVariant->visit([](
auto &&e) {
3263 using U = std::remove_cv_t<std::remove_reference_t<
decltype(e)>>;
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);
3283 }
else if (!m_domCreator.nodeStack.isEmpty()) {
3285 [&scope](
auto &&e) {
3286 using U = std::remove_cv_t<std::remove_reference_t<
decltype(e)>>;
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>) {
3294 if (
auto scriptElement = e.body->scriptElement()) {
3295 scriptElement.base()->setSemanticScope(scope);
3298 e.setSemanticScope(scope);
3301 m_domCreator.currentNodeEl().item.value);
3307 const QQmlJSScope::ConstPtr scope = m_scopeCreator.m_currentScope;
3311 if (m_domCreator.nodeStack.size() > 1
3312 && m_domCreator.nodeStack.last().item.kind == DomType::Binding) {
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>) {
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()
3331 m_domCreator.currentNodeEl(1).item.value);
3333 if (m_domCreator.nodeStack.size() > 0) {
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);
3346 m_domCreator.currentNodeEl().item.value);
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;
3362 auto factory = scope.factory();
3363 if (!factory && !scope->isComposite())
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), { });
3374 bool QQmlDomAstCreator::visit(AST::name *ast)
3376 return QQmlDomAstCreatorBase::visit(ast) && visitWithCustomListIteration(ast, this);
3384#undef Q_SCRIPTELEMENT_DISABLE
3385#undef Q_SCRIPTELEMENT_EXIT_IF
Binding & operator=(const Binding &)
void setBindingIdentifiers(const ScriptElementVariant &bindingIdentifiers)
QmlObject * objectValue()
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
std::optional< FieldName > headField() const
void setNameIdentifiers(const ScriptElementVariant &name)
QQmlDomAstCreatorBase(const MutableDomItem &qmlFile)
void endVisit(AST::UiProgram *) override
bool stackHasScriptList() const
void throwRecursionDepthError() override
void endVisitHelper(AST::PatternElement *pe, const std::shared_ptr< ScriptElements::GenericScriptElement > &element)
bool visit(AST::UiProgram *program) override
bool stackHasScriptVariant() const
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)
std::shared_ptr< Node > Tree
@ ScriptVariableDeclarationEntry
@ ScriptContinueStatement
@ ScriptLabelledStatement
@ ScriptTemplateExpressionPart
@ ScriptParenthesizedExpression
@ ScriptNewMemberExpression
@ ScriptConditionalExpression
@ ScriptIdentifierExpression
@ ScriptTryCatchStatement
@ ScriptFunctionExpression
@ ScriptVariableDeclaration
@ ScriptTemplateStringPart
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)