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
qqmldomitem.cpp
Go to the documentation of this file.
1// Copyright (C) 2020 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
7#include "qqmldomtop_p.h"
19#include <qqmldomlinewriterfactory_p.h>
20
21#include <QtQml/private/qqmljslexer_p.h>
22#include <QtQml/private/qqmljsparser_p.h>
23#include <QtQml/private/qqmljsengine_p.h>
24#include <QtQml/private/qqmljsastvisitor_p.h>
25#include <QtQml/private/qqmljsast_p.h>
26
27#include <QtCore/QCborArray>
28#include <QtCore/QCborMap>
29#include <QtCore/QDebug>
30#include <QtCore/QDir>
31#include <QtCore/QFile>
32#include <QtCore/QFileInfo>
33#include <QtCore/QJsonDocument>
34#include <QtCore/QJsonValue>
35#include <QtCore/QMutexLocker>
36#include <QtCore/QRegularExpression>
37#include <QtCore/QScopeGuard>
38#include <QtCore/QtGlobal>
39#include <QtCore/QTimeZone>
40#include <optional>
41#include <type_traits>
42#include <utility>
43
45
46Q_LOGGING_CATEGORY(writeOutLog, "qt.qmldom.writeOut", QtWarningMsg);
47Q_STATIC_LOGGING_CATEGORY(refLog, "qt.qmldom.ref", QtWarningMsg);
48
49namespace QQmlJS {
50namespace Dom {
51
52template<class... TypeList>
54
55template<class... Ts>
56struct CheckDomElementT<std::variant<Ts...>> : std::conjunction<IsInlineDom<Ts>...>
57{
58};
59
60/*!
61 \internal
62 \class QQmljs::Dom::ElementT
63
64 \brief A variant that contains all the Dom elements that an DomItem can contain.
65
66 Types in this variant are divided in two categories: normal Dom elements and internal Dom
67 elements.
68 The first ones are inheriting directly or indirectly from DomBase, and are the usual elements
69 that a DomItem can wrap around, like a QmlFile or an QmlObject. They should all appear in
70 ElementT as pointers, e.g. QmlFile*.
71 The internal Dom elements are a little bit special. They appear in ElementT without pointer, do
72 not inherit from DomBase \b{but} should behave like a smart DomBase-pointer. That is, they should
73 dereference as if they were a DomBase* pointing to a normal DomElement by implementing
74 operator->() and operator*().
75 Adding types here that are neither inheriting from DomBase nor implementing a smartpointer to
76 DomBase will throw compilation errors in the std::visit()-calls on this type.
77*/
78static_assert(CheckDomElementT<ElementT>::value,
79 "Types in ElementT must either be a pointer to a class inheriting "
80 "from DomBase or (for internal Dom structures) implement a smart "
81 "pointer pointing to a class inheriting from DomBase");
82
83using std::shared_ptr;
84/*!
85\internal
86\class QQmljs::Dom::DomBase
87
88\brief Abstract class common to all elements of the Qml code model
89
90DomBase represents the base class common to all objects exposed by the Dom Model
91through a DomItem.
92Single inheritence is mandatory for the inline items (Empty, Map, List, ConstantData, Reference),
93so that the base pointer of the object can be used a base pointer of the superclass directly.
94
95The subclass *must* have a
96\code
97 constexpr static Kind kindValue
98\endcode
99entry with its kind to enable casting usng the DomItem::as DomItem::ownerAs templates.
100
101The minimal overload set to be usable consists of following methods:
102\list
103\li \c{kind()} returns the kind of the current element:
104\code
105 Kind kind() const override { return kindValue; }
106\endcode
107
108\li \c{pathFromOwner()} returns the path from the owner to the current element
109\code
110 Path pathFromOwner() const override;
111\endcode
112
113\li \c{canonicalPath()} returns the path
114\code
115 Path canonicalPath(const DomItem &self) const override;
116\endcode
117
118\li \c{iterateDirectSubpaths} iterates the *direct* subpaths/children and returns false if a quick
119end was requested:
120\code
121bool iterateDirectSubpaths(const DomItem &self, function_ref<bool(Path, DomItem)>) const = 0;
122\endcode
123
124\endlist
125
126But you probably want to subclass either \c DomElement or \c OwningItem for your element. \c
127DomElement stores its \c pathFromOwner, and computes the \c canonicalPath from it and its owner. \c
128OwningItem is the unit for updates to the Dom model, exposed changes always change at least one \c
129OwningItem. They have their lifetime handled with \c shared_ptr and own (i.e. are responsible of
130freeing) other items in them.
131
132\sa QQml::Dom::DomItem, QQml::Dom::DomElement, QQml::Dom::OwningItem
133*/
134
136{
137 static QMap<DomType,QString> map = [](){
138 QMetaEnum metaEnum = QMetaEnum::fromType<DomType>();
139 QMap<DomType,QString> res;
140 for (int i = 0; i < metaEnum.keyCount(); ++ i) {
141 res[DomType(metaEnum.value(i))] = QString::fromUtf8(metaEnum.key(i));
142 }
143 return res;
144 }();
145 return map;
146}
147
149{
150 QString res = domTypeToStringMap().value(k);
151 if (res.isEmpty())
152 return QString::number(int(k));
153 else
154 return res;
155}
156
158{
159 static QMap<DomKind, QString> map = []() {
160 QMetaEnum metaEnum = QMetaEnum::fromType<DomKind>();
161 QMap<DomKind, QString> res;
162 for (int i = 0; i < metaEnum.keyCount(); ++i) {
163 res[DomKind(metaEnum.value(i))] = QString::fromUtf8(metaEnum.key(i));
164 }
165 return res;
166 }();
167 return map;
168}
169
171{
172 return domKindToStringMap().value(k, QString::number(int(k)));
173}
174
176{
177 switch (k) {
178 case DomType::JsFile:
179 case DomType::QmlFile:
180 return true;
181 default:
182 return false;
183 }
184}
185
187{
188 switch (k) {
191 return true;
192 default:
193 return false;
194 }
195
196}
197
199{
200 switch (k) {
201 case DomType::Map:
202 case DomType::List:
203 case DomType::ListP:
204 return true;
205 default:
206 return false;
207 }
208}
209
211{
212 switch (k) {
213 case DomType::QmlObject: // prop, methods,...
214 case DomType::ScriptExpression: // Js lexical scope
215 case DomType::QmlComponent: // (ids, enums -> qmlObj)
216 case DomType::QmlFile: // (components ->importScope)
217 case DomType::MethodInfo: // method arguments
218 case DomType::GlobalComponent: // global scope (enums -> qmlObj)
219 case DomType::JsResource: // js resurce (enums -> qmlObj)
220 return true;
221 default:
222 return false;
223 }
224}
225
227{
228 auto parent = containingObject(self);
229 if (parent)
230 return parent.canonicalFilePath();
231 return QString();
232}
233
234void DomBase::writeOut(const DomItem &self, OutWriter &) const
235{
236 qCWarning(writeOutLog) << "Ignoring unsupported writeOut for " << domTypeToString(kind()) << ":"
237 << self.canonicalPath();
238}
239
240ConstantData::ConstantData(const Path &pathFromOwner, const QCborValue &value)
241 : DomElement(pathFromOwner), m_value(value)
242{}
243
244bool ConstantData::iterateDirectSubpaths(const DomItem &self, DirectVisitor visitor) const
245{
246 if (m_value.isMap()) {
247 QCborMap map = m_value.toMap();
248 auto it = map.cbegin();
249 auto end = map.cend();
250 while (it != end) {
251 QString key = it.key().toString();
252 // CBOR map keys are runtime strings, not symbolic field identifiers,
253 // so they are addressed as Key components, not Fields.
254 PathEls::PathComponent comp = PathEls::Key(key);
255 auto val = it.value();
256 if (!self.invokeVisitorOnValue(visitor, comp, val))
257 return false;
258 ++it;
259 }
260 return true;
261 } else if (m_value.isArray()){
262 QCborArray array = m_value.toArray();
263 auto it = array.cbegin();
264 auto end = array.cend();
265 index_type i = 0;
266 while (it != end) {
267 if (!self.invokeVisitorOnValue(visitor, PathEls::Index(i++), *it++))
268 return false;
269 }
270 return true;
271 } else {
272 return true;
273 }
274}
275
276quintptr ConstantData::id() const
277{
278 return quintptr(0);
279}
280
281DomKind ConstantData::domKind() const
282{
283 if (m_value.isMap())
284 return DomKind::Map;
285 if (m_value.isArray())
286 return DomKind::List;
287 return DomKind::Value;
288}
289/*!
290\internal
291\class QQmlJS::Dom::DomItem
293\brief A value type that references any element of the Dom.
294
295This class is the central element in the Dom, it is how any element can be identfied in a uniform
296way, and provides the API to explore the Dom, and Path based operations.
297
298The DomItem (unless it is Empty) keeps a pointer to the element, and a shared pointer to its owner
299and to the DomEnvironment or DomUniverse that contains them. This means that:
300\list
301\li A DomItem always has some context: you can get the canonicalPath(), go up along it with
302 containingObject() and container().
303\li the indexing operator [], or the path(), field(), key() and index() methods (along with their
304 fields(), keys(), and indexes() contreparts) let one visit the contents of the current element.
305\li visitTree can be used to visit all subEments, if preferred on the top of it a visitor
306 pattern can also be used.
307\li If element specific attributes are wanted the two template casting as and ownerAs allow safe
308casting of the DomItem to a specific concrete type (cast to superclasses is not supported). \li
309Multithreading does not create issues, because even if an update replacing an OwningItem takes place
310the DomItem keeps a shared_ptr to the current owner as long as you use it \li Some elements (Empty,
311List, Map, ConstantData, Reference) might be inline, meaning that they are generated on the fly,
312wrapping data of the original object. \endlist
313
314One of the goals of the DomItem is to allow one to use real typed objects, as one is used to in C++,
315and also let one use modern C++ patterns, meaning container that contain the actual object (without
316pointer indirection).
317Exposed OwningItems are basically immutable, but during construction, objects can be modified.
318This will typically happen from a single thread, so there aren't locking issues, but pointers to
319inner elements might become invalid.
320In this case the use of the MutableDomItem is required.
321It does not keep any pointers to internal elements, but rather the path to them, and it resolves
322it every time it needs.
323*/
324
325FileToLoad::FileToLoad(const std::weak_ptr<DomEnvironment> &environment,
326 const QString &canonicalPath, const QString &logicalPath,
327 const std::optional<InMemoryContents> &content)
332{
333}
334
335FileToLoad FileToLoad::fromMemory(const std::weak_ptr<DomEnvironment> &environment,
336 const QString &path, const QString &code)
337{
338 const QString canonicalPath = QFileInfo(path).canonicalFilePath();
339 return {
340 environment,
341 // we can't lazy load files from an empty path, but non-existent paths where canonicalPath
342 // is empty are OK
343 canonicalPath.isEmpty() ? path : canonicalPath,
344 path,
345 InMemoryContents{ code },
346 };
347}
348
349FileToLoad FileToLoad::fromFileSystem(const std::weak_ptr<DomEnvironment> &environment,
350 const QString &path)
351{
352 // make the path canonical so the file content can be loaded from it later
353 const QString canonicalPath = QFileInfo(path).canonicalFilePath();
354 return {
355 environment,
356 canonicalPath,
357 path,
358 std::nullopt,
359 };
360}
361
364
366{
367 static ErrorGroups res = {{domErrorGroup}};
368 return res;
369}
370
372{
373 static ErrorGroups res = {{domErrorGroup, NewErrorGroup("Resolve")}};
374 return res;
375}
376
378{
379 Path res = visitEl([this](auto &&el) { return el->canonicalPath(*this); });
380 if (!(!res || res.headKind() == Path::Kind::Root)) {
381 qCWarning(domLog) << "non anchored canonical path:" << res.toString();
382 Q_ASSERT(false);
383 }
384 return res;
385
386}
387
389{
390 return visitEl([this](auto &&el) { return el->containingObject(*this); });
391}
392
393/*!
394 \internal
395 \brief Returns the QmlObject that this belongs to.
396
397 qmlObject() might also return the object of a component if GoTo:MostLikely is used.
398 */
399DomItem DomItem::qmlObject(GoTo options, FilterUpOptions filterOptions) const
400{
401 if (DomItem res = filterUp([](DomType k, const DomItem &) { return k == DomType::QmlObject; },
402 filterOptions))
403 return res;
404 if (options == GoTo::MostLikely) {
405 if (DomItem comp = component(options))
406 return comp.field(Fields::objects).index(0);
407 }
408 return DomItem();
409}
410
411DomItem DomItem::fileObject(GoTo options) const
412{
413 DomItem res = *this;
415 if (k == DomType::List || k == DomType::Map) {
416 res = res.containingObject();
417 k = res.internalKind();
418 }
419 if (k == DomType::ExternalItemInfo || (options == GoTo::MostLikely && k == DomType::ExternalItemPair))
420 return field(Fields::currentItem);
421 res = owner();
422 k = res.internalKind();
423 while (k != DomType::Empty) {
424 if (k == DomType::QmlFile || k == DomType::JsFile)
425 break;
426 res = res.containingObject();
427 res = res.owner();
428 k = res.internalKind();
429 }
430 return res;
431}
432
433DomItem DomItem::rootQmlObject(GoTo options) const
434{
435 return qmlObject(options, FilterUpOptions::ReturnInner);
436}
437
439{
440 Path path = pathFromOwner();
441 if (!path)
442 path = canonicalPath();
443 Source s = path.split();
444 if (s.pathFromSource.length() > 1)
445 return containingObject().path(s.pathFromSource.dropTail());
446 return containingObject();
447}
448
449/*!
450 \internal
451 \brief The owner of an element, for an qmlObject this is the containing qml file.
452 */
454{
455 if (domTypeIsOwningItem(m_kind) || m_kind == DomType::Empty)
456 return *this;
457 return std::visit([this](auto &&el) {
458 if constexpr (std::is_same_v<std::decay_t<decltype(el)>, std::monostate>)
459 return DomItem();
460 else
461 return DomItem(this->m_top, el, this->m_ownerPath, el.get());
462 }, m_owner);
463}
464
466{
467 if (domTypeIsTopItem(m_kind) || m_kind == DomType::Empty)
468 return *this;
469 return std::visit([](auto &&el) {
470 if constexpr (std::is_same_v<std::decay_t<decltype(el)>, std::monostate>)
471 return DomItem();
472 else
473 return DomItem(el, el, Path(), el.get());
474 }, m_top);
475}
476
478{
479 DomItem res = top();
481 return res;
482 return DomItem(); // we are in the universe, and cannot go back to the environment...
483}
484
485std::shared_ptr<QQmlJSResourceFileMapper> DomItem::resourceFileMapper() const
486{
487 const std::shared_ptr<DomEnvironment> environmentPtr = environment().ownerAs<DomEnvironment>();
488 if (!environmentPtr || environmentPtr->domCreationOption() != DomCreationOption::Extended)
489 return {};
490 return environmentPtr->semanticAnalysis().m_mapper;
491}
492
494{
495 DomItem res = top();
497 return res;
499 return res.field(Fields::universe);
500 return DomItem(); // we should be in an empty DomItem already...
501}
502
503/*!
504 \internal
505 Shorthand to obtain the ScriptExpression DomItem, in which this DomItem is defined.
506 Returns an empty DomItem if the item is not defined inside a ScriptExpression.
507 \sa goToFile()
508 */
510{
511 if (DomItem res = filterUp([](DomType k, const DomItem &) { return k == DomType::ScriptExpression; },
512 FilterUpOptions::ReturnOuter))
513 return res;
514 return DomItem();
515}
516
517/*!
518 \internal
519 Shorthand to obtain the QmlFile DomItem, in which this DomItem is defined.
520 Returns an empty DomItem if the item is not defined in a QML file.
521 \sa goToFile()
522 */
524{
525 if (DomItem res = filterUp([](DomType k, const DomItem &) { return k == DomType::QmlFile; },
526 FilterUpOptions::ReturnOuter))
527 return res;
528 return DomItem();
529}
530
531/*!
532 \internal
533 Shorthand to obtain the QmlFile DomItem from a canonicalPath.
534 \sa containingFile()
535 */
536DomItem DomItem::goToFile(const QString &canonicalPath) const
537{
538 Q_UNUSED(canonicalPath);
539 DomItem file =
540 top().field(Fields::qmlFileWithPath).key(canonicalPath).field(Fields::currentItem);
541 return file;
542}
543
544/*!
545 \internal
546 In the DomItem hierarchy, go \c n levels up.
547 */
548DomItem DomItem::goUp(int n) const
549{
550 Path path = canonicalPath();
551 // first entry of path is usually top(), and you cannot go up from top().
552 if (path.length() < n + 1)
553 return DomItem();
554
555 DomItem parent = top().path(path.dropTail(n));
556 return parent;
557}
558
559/*!
560 \internal
561 In the DomItem hierarchy, go 1 level up to get the direct parent.
562 */
564{
565 return goUp(1);
566}
567
568/*!
569\internal
570Finds the first element in the DomItem hierarchy that satisfies filter.
571Use options to set the search direction, see also \l{FilterUpOptions}.
572*/
573DomItem DomItem::filterUp(function_ref<bool(DomType k, const DomItem &)> filter, FilterUpOptions options) const
574{
575 if (options == FilterUpOptions::ReturnOuter && filter(internalKind(), *this)) {
576 return *this;
577 }
578
579 switch (options) {
582 for (DomItem current = *this, previous = DomItem(); current;
583 previous = current, current = current.directParent()) {
584 if (filter(current.internalKind(), current)) {
585 if (options != FilterUpOptions::ReturnOuterNoSelf || current != *this)
586 return current;
587 }
588 }
589 break;
590 }
592 DomItem current = top();
593 for (const Path &currentPath : canonicalPath()) {
594 current = current.path(currentPath);
595 if (filter(current.internalKind(), current))
596 return current;
597 }
598 break;
599 }
600
601 return DomItem();
602}
603
605{
606 DomItem res = filterUp([](DomType, const DomItem &el) { return el.isScope(); }, options);
607 return res;
608}
609
611{
612 QQmlJSScope::ConstPtr scope;
613 visitUp([&scope](const DomItem &item) {
614 scope = item.semanticScope();
615 return !scope; // stop when scope was true
616 });
617 return scope;
618}
619
621{
622 QQmlJSScope::ConstPtr scope = std::visit(
623 [](auto &&e) -> QQmlJSScope::ConstPtr {
624 using T = std::remove_cv_t<std::remove_reference_t<decltype(e)>>;
625 if constexpr (std::is_same_v<T, const QmlObject *>) {
626 return e->semanticScope();
627 } else if constexpr (std::is_same_v<T, const QmlComponent *>) {
628 return e->semanticScope();
629 } else if constexpr (std::is_same_v<T, SimpleObjectWrap>) {
630 if (const MethodInfo *mi = e->template as<MethodInfo>()) {
631 return mi->semanticScope();
632 }
633 if (const auto *propertyDefinition = e->template as<PropertyDefinition>()) {
634 return propertyDefinition->semanticScope();
635 }
636 } else if constexpr (std::is_same_v<T, ScriptElementDomWrapper>) {
637 return e.element().base()->semanticScope();
638 }
639 return {};
640 },
641 m_element);
642 return scope;
643}
644
645DomItem DomItem::get(const ErrorHandler &h, QList<Path> *visitedRefs) const
646{
647 if (const Reference *refPtr = as<Reference>())
648 return refPtr->get(*this, h, visitedRefs);
649 return DomItem();
650}
651
652QList<DomItem> DomItem::getAll(const ErrorHandler &h, QList<Path> *visitedRefs) const
653{
654 if (const Reference *refPtr = as<Reference>())
655 return refPtr->getAll(*this, h, visitedRefs);
656 return {};
657}
658
659PropertyInfo DomItem::propertyInfoWithName(const QString &name) const
660{
661 PropertyInfo pInfo;
662 visitPrototypeChain([&pInfo, name](const DomItem &obj) {
663 return obj.visitLocalSymbolsNamed(name, [&pInfo, name](const DomItem &el) {
664 switch (el.internalKind()) {
665 case DomType::Binding:
666 pInfo.bindings.append(el);
667 break;
668 case DomType::PropertyDefinition:
669 pInfo.propertyDefs.append(el);
670 break;
671 default:
672 break;
673 }
674 return true;
675 });
676 });
677 return pInfo;
678}
679
681{
682 QSet<QString> res;
683 visitPrototypeChain([&res](const DomItem &obj) {
684 res += obj.propertyDefs().keys();
685 res += obj.bindings().keys();
686 return true;
687 });
688 return res;
689}
690
691DomItem DomItem::component(GoTo options) const
692{
693 if (DomItem res = filterUp(
694 [](DomType kind, const DomItem &) {
695 return kind == DomType::QmlComponent || kind == DomType::GlobalComponent;
696 },
697 FilterUpOptions::ReturnInner))
698 return res;
699 if (options == GoTo::MostLikely) {
700 DomItem item = *this;
701 DomType kind = item.internalKind();
702 if (kind == DomType::List || kind == DomType::Map) {
703 item = item.containingObject();
704 kind = item.internalKind();
705 }
706 switch (kind) {
709 item = fileObject(options);
710 Q_FALLTHROUGH();
711 case DomType::QmlFile:
712 return item.field(Fields::components).key(QString()).index(0);
713 default:
714 break;
715 }
716 }
717 return DomItem();
718}
719
724
726{
727 static auto map = []() {
728 QMetaEnum metaEnum = QMetaEnum::fromType<LookupType>();
729 QMap<QString, LookupType> res;
730 for (int i = 0; i < metaEnum.keyCount(); ++i) {
731 res[QString::fromUtf8(metaEnum.key(i)).toLower()] = LookupType(metaEnum.value(i));
732 }
733 return res;
734 }();
735 return map;
736}
737
738static DomItem rootFromContext(const DomItem &root, PathRoot contextId)
739{
740 switch (contextId) {
742 return root.environment().field(Fields::moduleIndexWithUri);
743 case PathRoot::Libs:
744 return root.environment()[Fields::plugins];
745 case PathRoot::Top:
746 return root.top();
747 case PathRoot::Env:
748 return root.environment();
750 return root.environment()[u"universe"];
751 default:
752 return DomItem{};
753 }
754}
755
756/*!
757 \internal
758 Is used to resolve the "get" field of QQmlJS::Dom::Reference. Reference contains a link to a type,
759 and its "get" field does return the DomItem for the linked type. For example, a type has a link to
760 its base type.
761*/
762static DomItem resolveReference(const DomItem &it, const Path &refRef, QList<Path> *visitedRefs,
763 const ErrorHandler &errorHandler, const ErrorGroups &errorGroup)
764{
765 if (visitedRefs->contains(refRef)) {
766 errorGroup
767 .error([visitedRefs, refRef](const Sink &sink) {
768 const QString msg = DomItem::tr("Circular reference:") + QLatin1Char('\n');
769 sink(QStringView{ msg });
770 for (const Path &vPath : *visitedRefs) {
771 sink(u" ");
772 vPath.dump(sink);
773 sink(u" >\n");
774 }
775 refRef.dump(sink);
776 })
777 .handle(errorHandler);
778 return {};
779 }
780
781 const Reference *ref = it.as<Reference>();
782 Q_ASSERT(ref);
783 visitedRefs->append(refRef);
784 DomItem resolveRes;
785 it.resolve(
786 ref->referredObjectPath,
787 [&resolveRes](Path, const DomItem &r) {
788 resolveRes = r;
789 return false;
790 },
791 errorHandler, ref->referredObjectPath, visitedRefs);
792 return resolveRes;
793}
794
795static LookupOptions resolveLookupOptions(const PathCurrent &current, const DomItem &it)
796{
797 LookupOptions opt = LookupOption::Normal;
798 if (current == PathCurrent::LookupStrict)
799 return opt | LookupOption::Strict;
800
801 if (current == PathCurrent::Lookup) {
802 DomItem comp = it.component();
803 // These are runtime configuration flags attached via extra owning items
804 // (now Key-keyed), not structural Fields.
805 DomItem strict = comp[u"~strictLookup~"];
806 if (!strict) {
807 DomItem env = it.environment();
808 strict = env[u"defaultStrictLookup"];
809 }
810 if (strict && strict.value().toBool())
811 opt = opt | LookupOption::Strict;
812 }
813 return opt;
814}
815
816static std::optional<LookupType> lookupTypeFromString(const QString &expectedType)
817{
818 const auto &map = stringToLookupTypeMap();
819 auto it = map.find(expectedType.toLower());
820 if (it == map.end())
821 return {};
822 return *it;
823}
824
825bool DomItem::resolve(const Path &path, DomItem::Visitor visitor, const ErrorHandler &errorHandler,
826 const Path &fullPath, QList<Path> *visitedRefs) const
827{
828 QList<Path> vRefs;
829 Path fPath = fullPath;
830 if (fullPath.length() == 0)
831 fPath = path;
832 if (path.length()==0)
833 return visitor(fPath, *this);
834 QList<QSet<quintptr>> visited(path.length() + 1);
835 const PathIterator components = path.begin();
836 QList<ResolveToDo> toDos(1); // invariant: always increase pathIndex to guarantee end even with only partial visited match
837 if (path.headKind() == Path::Kind::Root) {
838 // headKind() guarantees the head is a Root, so headRoot() has a value.
839 DomItem root = rootFromContext(*this, *path.headRoot());
840 if (!root) {
842 .error(tr("Root context %1 is not known").arg(path.headName()))
843 .handle(errorHandler);
844 return false;
845 }
846 toDos[0] = {std::move(root), 1};
847 } else {
848 toDos[0] = {*this, 0};
849 }
850 while (!toDos.isEmpty()) {
851 const ResolveToDo toDo = toDos.takeLast();
852 {
853 auto idNow = toDo.item.id();
854 if (idNow == quintptr(0) && toDo.item == *this)
855 idNow = quintptr(this);
856 if (idNow != quintptr(0) && visited[0].contains(idNow))
857 continue;
858 }
859 int iPath = toDo.pathIndex;
860 DomItem it = toDo.item;
861 bool branchExhausted = false;
862 while (iPath < path.length() && it && !branchExhausted) {
863 auto idNow = it.id();
864 if (idNow == quintptr() && toDo.item == *this)
865 idNow = quintptr(this);
866 if (idNow != quintptr(0)) {
867 auto vPair = std::make_pair(idNow, iPath);
868 if (visited[vPair.second].contains(vPair.first))
869 break;
870 visited[vPair.second].insert(vPair.first);
871 }
872 auto cNow = components[iPath++];
873 switch (cNow.headKind()) {
874 case Path::Kind::Key:
875 it = it.key(cNow.headName());
876 break;
878 if (cNow.headField() == Fields::get && it.internalKind() == DomType::Reference) {
879 it = resolveReference(it, it.canonicalPath(),
880 visitedRefs == nullptr ? &vRefs : visitedRefs,
881 errorHandler, myResolveErrors());
882 } else if (auto fn = cNow.headField()) {
883 it = it.field(*fn);
884 } else {
885 it = DomItem();
886 }
887 break;
889 // headKind() guarantees the head is an Index, so headIndex() has a value.
890 it = it.index(*cNow.headIndex());
891 break;
894 .error(tr("Empty is not supported inside paths"))
895 .handle(errorHandler);
896 return false;
897 case Path::Kind::Root:
898 myResolveErrors().error(tr("Root path is supported only at the beginning, and only once, found %1 at %2 in %3")
899 .arg(cNow.toString()).arg(iPath -1).arg(path.toString())).handle(errorHandler);
900 return false;
902 {
903 // headKind() guarantees the head is a Current, so headCurrent() has a value.
904 PathCurrent current = *cNow.headCurrent();
905 switch (current) {
906 case PathCurrent::Obj:
907 if (domKind() != DomKind::Object)
908 it = it.containingObject();
909 break;
911 it = it.component();
912 break;
914 case PathCurrent::Ids:
915 it = it.component().ids();
916 break;
918 it = it.component()[Fields::exports];
919 break;
922 case PathCurrent::Lookup: {
923 const LookupOptions opt = resolveLookupOptions(current, it);
926 .error(tr("Javascript lookups not yet implemented"))
927 .handle(errorHandler);
928 return false;
929 }
930 // enter lookup
931 auto idNow = it.id();
932 if (idNow == quintptr(0) && toDo.item == *this)
933 idNow = quintptr(this);
934 if (idNow != quintptr(0)) {
935 auto vPair = std::make_pair(idNow, iPath);
936 if (visited[vPair.second].contains(vPair.first))
937 break;
938 visited[vPair.second].insert(vPair.first);
939 }
940 if (iPath + 1 >= path.length()) {
942 .error(tr("Premature end of path, expected a field specifying the "
943 "type, and a key specifying the name to search after a "
944 "lookup directive in %2")
945 .arg(path.toString()))
946 .handle(errorHandler);
947 return false;
948 }
949 Path cNow = components[iPath++];
950 if (cNow.headKind() != Path::Kind::Field) {
952 .error(tr("Expected a key path specifying the type to search after "
953 "a lookup directive, not %1 at component %2 of %3")
954 .arg(cNow.toString())
955 .arg(iPath)
956 .arg(path.toString()))
957 .handle(errorHandler);
958 return false;
959 }
960 QString expectedType = cNow.headName();
961 auto lookupType = lookupTypeFromString(expectedType);
962 if (!lookupType) {
964 .error(tr("Type for lookup was expected to be one of '%1', not "
965 "%2")
966 .arg(stringToLookupTypeMap().keys().join(", "_L1),
967 expectedType))
968 .handle(errorHandler);
969 return false;
970 }
971 cNow = components[iPath++];
972 if (cNow.headKind() != Path::Kind::Key) {
974 .error(tr("Expected a key specifying the path to search after the "
975 "@lookup directive and type, not %1 at component %2 of "
976 "%3")
977 .arg(cNow.toString())
978 .arg(iPath)
979 .arg(path.toString()))
980 .handle(errorHandler);
981 return false;
982 }
983 QString target = cNow.headName();
984 if (target.isEmpty()) {
986 .warning(tr("Path with empty lookup at component %1 of %2 will "
987 "match nothing in %3.")
988 .arg(iPath)
989 .arg(path.toString())
990 .arg(it.canonicalPath().toString()))
991 .handle(errorHandler);
992 return true;
993 }
994 it.visitLookup(
995 target,
996 [&toDos, iPath](const DomItem &subEl) {
997 toDos.append({ subEl, iPath });
998 return true;
999 },
1000 *(std::move(lookupType)), opt, errorHandler, &(visited[iPath]),
1001 visitedRefs);
1002 branchExhausted = true;
1003 break;
1004 }
1005 }
1006 break;
1007 }
1008 }
1009 }
1010 // visit the resolved path
1011 if (!branchExhausted && iPath == path.length() && !visitor(fPath, it))
1012 return false;
1013 }
1014 return true;
1015}
1016
1017DomItem DomItem::path(const Path &p, const ErrorHandler &errorHandler) const
1018{
1019 if (!p)
1020 return *this;
1021 DomItem res;
1022 resolve(p, [&res](const Path &, const DomItem &it) {
1023 res = it;
1024 return false;
1025 }, errorHandler);
1026 return res;
1027}
1028
1030{
1031 return visitEl([this](auto &&el) { return el->fields(*this); });
1032}
1033
1035{
1036 return visitEl([this, name](auto &&el) { return el->field(*this, name); });
1037}
1038
1040{
1041 return visitEl([this](auto &&el) { return el->indexes(*this); });
1042}
1043
1044DomItem DomItem::index(index_type i) const
1045{
1046 return visitEl([this, i](auto &&el) { return el->index(*this, i); });
1047}
1048
1049bool DomItem::visitIndexes(function_ref<bool(const DomItem &)> visitor) const
1050{
1051 // use iterateDirectSubpaths instead?
1052 int nIndexes = indexes();
1053 for (int i = 0; i < nIndexes; ++i) {
1054 DomItem v = index(i);
1055 if (!visitor(v))
1056 return false;
1057 }
1058 return true;
1059}
1060
1062{
1063 return visitEl([this](auto &&el) { return el->keys(*this); });
1064}
1065
1067{
1068 QSet<QString> ks = keys();
1069 QStringList sortedKs(ks.begin(), ks.end());
1070 std::sort(sortedKs.begin(), sortedKs.end());
1071 return sortedKs;
1072}
1073
1074DomItem DomItem::key(const QString &name) const
1075{
1076 return visitEl([this, name](auto &&el) { return el->key(*this, name); });
1077}
1078
1079bool DomItem::visitKeys(function_ref<bool(const QString &, const DomItem &)> visitor) const
1080{
1081 // use iterateDirectSubpaths instead?
1082 const QStringList keys = sortedKeys();
1083 for (const QString &k : keys) {
1084 DomItem v = key(k);
1085 if (!visitor(k, v))
1086 return false;
1087 }
1088 return true;
1089}
1090
1092{
1093 QList<DomItem> res;
1094 iterateDirectSubpaths([&res](const PathEls::PathComponent &, function_ref<DomItem()> item) {
1095 res.append(item());
1096 return true;
1097 });
1098 return res;
1099}
1100
1101void DomItem::writeOutPre(OutWriter &ow) const
1102{
1103 if (hasAnnotations()) {
1104 DomItem anns = field(Fields::annotations);
1105 for (const auto &ann : anns.values()) {
1106 if (ann.annotations().indexes() == 0) {
1107 ow.ensureNewline();
1108 ann.writeOut(ow);
1109 ow.ensureNewline();
1110 } else {
1111 DomItem annAnn = ann.annotations();
1112 Q_ASSERT_X(annAnn.indexes() == 1 && annAnn.index(0).name() == u"duplicate",
1113 "DomItem::writeOutPre", "Unexpected annotation of annotation");
1114 }
1115 }
1116 }
1117 ow.itemStart(*this);
1118}
1119
1120void DomItem::writeOut(OutWriter &ow) const
1121{
1122 writeOutPre(ow);
1123 visitEl([this, &ow](auto &&el) { el->writeOut(*this, ow); });
1125}
1126
1127void DomItem::writeOutPost(OutWriter &ow) const
1128{
1129 ow.itemEnd();
1130}
1131
1132DomItem::WriteOutCheckResult DomItem::performWriteOutChecks(const DomItem &reformatted,
1133 OutWriter &ow,
1134 WriteOutChecks extraChecks) const
1135{
1136 auto compare = [this](const DomItem &obj1, const DomItem &obj2, QStringView obj2Name,
1137 const FieldFilter &filter) {
1138 const auto diffList = domCompareStrList(obj1, obj2, filter, DomCompareStrList::AllDiffs);
1139 if (!diffList.isEmpty()) {
1140 qCWarning(writeOutLog).noquote().nospace()
1141 << obj2Name << " writeOut of " << this->canonicalFilePath() << " has changes:\n"
1142 << diffList.join(QString());
1143 return false;
1144 }
1145 return true;
1146 };
1147 auto checkStability = [&ow, this](const QString &expected, const DomItem &obj,
1148 QStringView objName) {
1149 LineWriter lw2([](QStringView) {}, ow.lineWriter.fileName(), ow.lineWriter.options());
1150 OutWriter ow2(lw2);
1151 ow2.indentNextlines = true;
1152 obj.writeOut(ow2);
1153 ow2.eof();
1154 if (ow2.writtenStr != expected) {
1155 qCWarning(writeOutLog).noquote().nospace()
1156 << objName << " non stable writeOut of " << this->canonicalFilePath() << ":"
1157 << lineDiff(expected, ow2.writtenStr, 2);
1158 return false;
1159 }
1160 return true;
1161 };
1162
1163 if (extraChecks
1166 std::shared_ptr<DomEnvironment> newEnvPtr = newEnv.ownerAs<DomEnvironment>();
1167 if (!newEnvPtr)
1168 return WriteOutCheckResult::Failed;
1169
1170 auto newFilePtr = std::make_shared<QmlFile>(canonicalFilePath(), ow.writtenStr);
1171 newEnvPtr->addQmlFile(newFilePtr, AddOption::Overwrite);
1172
1173 DomItem newFile = newEnv.copy(newFilePtr, Path());
1174 if (newFilePtr->isValid()) {
1176 newEnvPtr->populateFromQmlFile(newFile);
1177 if ((extraChecks & WriteOutCheck::ReparseCompare)
1178 && !compare(reformatted, newFile, u"reparsed",
1180 return WriteOutCheckResult::Failed;
1181 if ((extraChecks & WriteOutCheck::ReparseStable))
1182 checkStability(ow.writtenStr, newFile, u"reparsed");
1183 }
1184 } else {
1185 const auto iterateErrors = [&newFile](const Sink &s) {
1186 newFile.iterateErrors(
1187 [s](const DomItem &, const ErrorMessage &msg) {
1188 s(u"\n ");
1189 msg.dump(s);
1190 return true;
1191 },
1192 true);
1193 s(u"\n"); // extra empty line at the end...
1194 };
1195 qCWarning(writeOutLog).noquote().nospace()
1196 << "writeOut of " << canonicalFilePath()
1197 << " created invalid code:\n----------\n"
1198 << ow.writtenStr << "\n----------" << iterateErrors;
1199 return WriteOutCheckResult::Failed;
1200 }
1201 }
1202 return WriteOutCheckResult::Success;
1203}
1204
1205/*!
1206 \internal
1207 Performes WriteOut of the FileItem and verifies the consistency of the DOM structure.
1208
1209 OutWriter is essentially a visitor traversing the DOM structure, starting from
1210 the current item representing a FileItem.
1211 While traversing it might be saving some intermediate information, used later for restoring
1212 written out item. Restoration is needed to validate that the DOM structure of the written item
1213 has not changed.
1214*/
1215bool DomItem::writeOutForFile(OutWriter &ow, WriteOutChecks extraChecks) const
1216{
1217 ow.indentNextlines = true;
1218 auto currentFileItem = fileObject();
1219 writeOut(ow);
1220 ow.eof();
1221 WriteOutCheckResult result = WriteOutCheckResult::Success;
1222 if (extraChecks)
1223 result = performWriteOutChecks(currentFileItem, ow, extraChecks);
1224 return result == WriteOutCheckResult::Success ? bool(currentFileItem) : false;
1225}
1226
1227bool DomItem::writeOut(const QString &path, const LineWriterOptions &options, FileWriter *fw,
1228 WriteOutChecks extraChecks) const
1229{
1230 FileWriter localFw;
1231 if (!fw)
1232 fw = &localFw;
1233 auto status = fw->write(path, [this, path, &options, extraChecks](QTextStream &ts) {
1234 auto lw = createLineWriter([&ts](QStringView s) { ts << s; }, path, options);
1235 OutWriter ow(getFileItemOwner(fileObject()), *lw);
1236 return writeOutForFile(ow, extraChecks);
1237 });
1238 switch (status) {
1239 case FileWriter::Status::DidWrite:
1240 case FileWriter::Status::SkippedEqual:
1241 return true;
1242 case FileWriter::Status::ShouldWrite:
1243 case FileWriter::Status::SkippedDueToFailure:
1244 qCWarning(writeOutLog) << "failure reformatting " << path;
1245 return false;
1246 default:
1247 qCWarning(writeOutLog) << "Unknown FileWriter::Status ";
1248 Q_ASSERT(false);
1249 return false;
1250 }
1251}
1252
1253bool DomItem::isCanonicalChild(const DomItem &item) const
1254{
1255 bool isChild = false;
1256 if (item.isOwningItem()) {
1258 } else {
1259 DomItem itemOw = item.owner();
1260 DomItem selfOw = owner();
1261 isChild = itemOw == selfOw && item.pathFromOwner().dropTail() == pathFromOwner();
1262 }
1263 return isChild;
1264}
1265
1267{
1268 bool hasAnnotations = false;
1269 DomType iKind = internalKind();
1270 switch (iKind) {
1271 case DomType::Id:
1272 if (const Id *myPtr = as<Id>())
1273 hasAnnotations = !myPtr->annotations.isEmpty();
1274 break;
1276 if (const PropertyDefinition *myPtr = as<PropertyDefinition>())
1277 hasAnnotations = !myPtr->annotations.isEmpty();
1278 break;
1280 if (const MethodInfo *myPtr = as<MethodInfo>())
1281 hasAnnotations = !myPtr->annotations.isEmpty();
1282 break;
1283 case DomType::QmlObject:
1284 if (const QmlObject *myPtr = as<QmlObject>())
1285 hasAnnotations = !myPtr->annotations().isEmpty();
1286 break;
1287 case DomType::Binding:
1288 if (const Binding *myPtr = as<Binding>())
1289 hasAnnotations = !myPtr->annotations().isEmpty();
1290 break;
1291 default:
1292 break;
1293 }
1294 return hasAnnotations;
1295}
1296
1297/*!
1298 \internal
1299 \brief Visits recursively all the children of this item using the given visitors.
1300
1301 First, the visitor is called and can continue or exit the visit by returning true or false.
1302
1303 Second, the openingVisitor is called and controls if the children of the current item needs to
1304 be visited or not by returning true or false. In either case, the visitation of all the other
1305 siblings is not affected. If both visitor and openingVisitor returned true, then the childrens of
1306 the current item will be recursively visited.
1307
1308 Finally, after all the children were visited by visitor and openingVisitor, the closingVisitor
1309 is called. Its return value is currently ignored.
1310
1311 Compared to the AST::Visitor*, openingVisitor and closingVisitor are called in the same order as
1312 the visit() and endVisit()-calls.
1313
1314 Filtering allows to not visit certain part of the trees, and is checked before(!) the lazy child
1315 is instantiated via its lambda. For example, visiting propertyInfos or defaultPropertyname takes
1316 a lot of time because it resolves and collects all properties inherited from base types, and
1317 might not even be relevant for the visitors.
1318 */
1319bool DomItem::visitTree(const Path &basePath, DomItem::ChildrenVisitor visitor,
1320 VisitOptions options, DomItem::ChildrenVisitor openingVisitor,
1321 DomItem::ChildrenVisitor closingVisitor, const FieldFilter &filter) const
1322{
1323 if (!*this)
1324 return true;
1325 if (options & VisitOption::VisitSelf && !visitor(basePath, *this, true))
1326 return false;
1327 if (options & VisitOption::VisitSelf && !openingVisitor(basePath, *this, true))
1328 return true;
1329 auto atEnd = qScopeGuard([closingVisitor, basePath, this, options]() {
1330 if (options & VisitOption::VisitSelf) {
1331 closingVisitor(basePath, *this, true);
1332 }
1333 });
1334 return iterateDirectSubpaths(
1335 [this, basePath, visitor, openingVisitor, closingVisitor, options,
1336 &filter](const PathEls::PathComponent &c, function_ref<DomItem()> itemF) {
1337 Path pNow;
1338 if (!(options & VisitOption::NoPath)) {
1339 pNow = basePath;
1340 pNow = pNow.withComponent(c);
1341 }
1342 if (!filter(*this, c, DomItem{}))
1343 return true;
1344 DomItem item = itemF();
1345 bool directChild = isCanonicalChild(item);
1346 if (!directChild && !(options & VisitOption::VisitAdopted))
1347 return true;
1348 if (!directChild || !(options & VisitOption::Recurse)) {
1349 if (!visitor(pNow, item, directChild))
1350 return false;
1351 // give an option to avoid calling open/close when not recursing?
1352 // calling it always allows close to do the reverse looping (children before
1353 // parent)
1354 if (!openingVisitor(pNow, item, directChild))
1355 return true;
1356 closingVisitor(pNow, item, directChild);
1357 } else {
1358 return item.visitTree(pNow, visitor, options | VisitOption::VisitSelf,
1359 openingVisitor, closingVisitor, filter);
1360 }
1361 return true;
1362 });
1363}
1364static bool visitPrototypeIndex(QList<DomItem> &toDo, const DomItem &current,
1365 const DomItem &derivedFromPrototype, const ErrorHandler &h,
1366 QList<Path> *visitedRefs, VisitPrototypesOptions options,
1367 const DomItem &prototype)
1368{
1369 Path elId = prototype.canonicalPath();
1370 if (visitedRefs->contains(elId))
1371 return true;
1372 else
1373 visitedRefs->append(elId);
1374 QList<DomItem> protos = prototype.getAll(h, visitedRefs);
1375 if (protos.isEmpty()) {
1376 if (std::shared_ptr<DomEnvironment> envPtr =
1377 derivedFromPrototype.environment().ownerAs<DomEnvironment>())
1378 if (!(envPtr->options() & DomEnvironment::Option::NoDependencies))
1379 derivedFromPrototype.myErrors()
1380 .warning(derivedFromPrototype.tr("could not resolve prototype %1 (%2)")
1381 .arg(current.canonicalPath().toString(),
1382 prototype.field(Fields::referredObjectPath)
1383 .value()
1384 .toString()))
1385 .withItem(derivedFromPrototype)
1386 .handle(h);
1387 } else {
1388 if (protos.size() > 1) {
1389 QStringList protoPaths;
1390 for (const DomItem &p : protos)
1391 protoPaths.append(p.canonicalPath().toString());
1392 derivedFromPrototype.myErrors()
1393 .warning(derivedFromPrototype
1394 .tr("Multiple definitions found, using first only, resolving "
1395 "prototype %1 (%2): %3")
1396 .arg(current.canonicalPath().toString(),
1397 prototype.field(Fields::referredObjectPath)
1398 .value()
1399 .toString(),
1400 protoPaths.join(QLatin1String(", "))))
1401 .withItem(derivedFromPrototype)
1402 .handle(h);
1403 }
1404 int nProtos = 1; // change to protos.length() to use all prototypes
1405 // (sloppier)
1406 for (int i = nProtos; i != 0;) {
1407 DomItem proto = protos.at(--i);
1408 if (proto.internalKind() == DomType::Export) {
1410 proto = proto.proceedToScope(h, visitedRefs);
1411 toDo.append(proto);
1412 } else if (proto.internalKind() == DomType::QmlObject
1414 toDo.append(proto);
1415 } else {
1416 derivedFromPrototype.myErrors()
1417 .warning(derivedFromPrototype.tr("Unexpected prototype type %1 (%2)")
1418 .arg(current.canonicalPath().toString(),
1419 prototype.field(Fields::referredObjectPath)
1420 .value()
1421 .toString()))
1422 .withItem(derivedFromPrototype)
1423 .handle(h);
1424 }
1425 }
1426 }
1427 return true;
1428}
1429
1430bool DomItem::visitPrototypeChain(function_ref<bool(const DomItem &)> visitor,
1431 VisitPrototypesOptions options, const ErrorHandler &h,
1432 QSet<quintptr> *visited, QList<Path> *visitedRefs) const
1433{
1434 QSet<quintptr> visitedLocal;
1435 if (!visited)
1436 visited = &visitedLocal;
1437 QList<Path> refsLocal;
1438 if (!visitedRefs)
1439 visitedRefs = &refsLocal;
1440 bool shouldVisit = !(options & VisitPrototypesOption::SkipFirst);
1441 DomItem current = qmlObject();
1442 if (!current) {
1443 myErrors().warning(tr("Prototype chain called outside object")).withItem(*this).handle(h);
1444 return true;
1445 }
1446 QList<DomItem> toDo({ current });
1447 while (!toDo.isEmpty()) {
1448 current = toDo.takeLast();
1449 current = current.proceedToScope(h, visitedRefs);
1450 if (visited->contains(current.id())) {
1451 // to warn about circular dependencies a purely local visited trace is required
1452 // as common ancestors of unrelated objects are valid and should be skipped
1453 // so we do not to warn unless requested
1456 .warning(tr("Detected multiple visit of %1 visiting prototypes of %2")
1457 .arg(current.canonicalPath().toString(),
1458 canonicalPath().toString()))
1459 .withItem(*this)
1460 .handle(h);
1461 continue;
1462 }
1463 visited->insert(current.id());
1464 if (shouldVisit && !visitor(current))
1465 return false;
1466 shouldVisit = true;
1467 current.field(Fields::prototypes)
1468 .visitIndexes([&toDo, &current, this, &h, visitedRefs, options](const DomItem &el) {
1469 return visitPrototypeIndex(toDo, current, *this, h, visitedRefs, options, el);
1470 });
1471 }
1472 return true;
1473}
1474
1476 function_ref<bool(const DomItem &)> visitor, VisitPrototypesOptions options,
1477 const ErrorHandler &h, QSet<quintptr> *visited, QList<Path> *visitedRefs) const
1478{
1479 // these are the scopes one can access with the . operator from the current location
1480 // but currently not the attached types, which we should
1482 if (k == DomType::QmlObject)
1483 return visitPrototypeChain(visitor, options, h, visited, visitedRefs);
1484 if (visited && id() != 0) {
1485 if (visited->contains(id()))
1486 return true;
1487 visited->insert(id());
1488 }
1489 if (k == DomType::Id || k == DomType::Reference || k == DomType::Export) {
1490 // we go to the scope if it is clearly defined
1491 DomItem v = proceedToScope(h, visitedRefs);
1493 return v.visitPrototypeChain(visitor, options, h, visited, visitedRefs);
1494 }
1495 if (k == DomType::Binding) {
1496 // from a binding we can get to its value if it is a object
1497 DomItem v = field(Fields::value);
1499 return v.visitPrototypeChain(visitor, options, h, visited, visitedRefs);
1500 }
1501 if (k == DomType::PropertyDefinition) {
1502 // from a property definition we go to the type stored in it
1503 DomItem t = field(Fields::type).proceedToScope(h, visitedRefs);
1505 return t.visitPrototypeChain(visitor, options, h, visited, visitedRefs);
1506 }
1507 if (!(options & VisitPrototypesOption::SkipFirst) && isScope() && !visitor(*this))
1508 return false;
1509 return true;
1510}
1511
1512/*!
1513 * \brief DomItem::visitStaticTypePrototypeChains
1514 * \param visitor
1515 * \param visitFirst
1516 * \param visited
1517 * \return
1518 *
1519 * visit the values JS reaches accessing a type directly: the values if it is a singleton or the
1520 * attached type
1521 */
1523 function_ref<bool(const DomItem &)> visitor, VisitPrototypesOptions options,
1524 const ErrorHandler &h, QSet<quintptr> *visited, QList<Path> *visitedRefs) const
1525{
1526 QSet<quintptr> visitedLocal;
1527 if (!visited)
1528 visited = &visitedLocal;
1529 DomItem current = qmlObject();
1530 DomItem comp = current.component();
1531 if (comp.field(Fields::isSingleton).value().toBool(false)
1532 && !current.visitPrototypeChain(visitor, options, h, visited, visitedRefs))
1533 return false;
1534 if (DomItem attachedT = current.component().field(Fields::attachedType).field(Fields::get))
1535 if (!attachedT.visitPrototypeChain(
1536 visitor, options & ~VisitPrototypesOptions(VisitPrototypesOption::SkipFirst), h,
1537 visited, visitedRefs))
1538 return false;
1539 return true;
1540}
1541
1542/*!
1543 \brief Let the visitor visit the Dom Tree hierarchy of this DomItem.
1544 */
1545bool DomItem::visitUp(function_ref<bool(const DomItem &)> visitor) const
1546{
1548 while (p.length() > 0) {
1549 DomItem current = top().path(p);
1550 if (!visitor(current))
1551 return false;
1552 p = p.dropTail();
1553 }
1554 return true;
1555}
1556
1557/*!
1558 \brief Let the visitor visit the QML scope hierarchy of this DomItem.
1559 */
1561 function_ref<bool(const DomItem &)> visitor, LookupOptions options, const ErrorHandler &h,
1562 QSet<quintptr> *visited, QList<Path> *visitedRefs) const
1563{
1564 QSet<quintptr> visitedLocal;
1565 if (!visited)
1566 visited = &visitedLocal;
1567 QList<Path> visitedRefsLocal;
1568 if (!visitedRefs)
1569 visitedRefs = &visitedRefsLocal;
1570 DomItem current = scope();
1571 if (!current) {
1572 myResolveErrors().warning(tr("Called visitScopeChain outside scopes")).handle(h);
1573 return true;
1574 }
1575 QList<DomItem> toDo { current };
1576 bool visitFirst = !(options & LookupOption::SkipFirstScope);
1577 bool visitCurrent = visitFirst;
1578 bool first = true;
1579 QSet<quintptr> alreadyAddedComponentMaps;
1580 while (!toDo.isEmpty()) {
1581 DomItem current = toDo.takeLast();
1582 if (visited->contains(current.id()))
1583 continue;
1584 visited->insert(current.id());
1585 if (visitCurrent && !visitor(current))
1586 return false;
1587 visitCurrent = true;
1588 switch (current.internalKind()) {
1589 case DomType::QmlObject: {
1590 if (!current.visitPrototypeChain(visitor, VisitPrototypesOption::SkipFirst, h, visited,
1591 visitedRefs))
1592 return false;
1593 DomItem root = current.rootQmlObject();
1594 if (root && root != current) {
1595 first = false;
1596 toDo.append(root);
1597 } else if (DomItem next = current.scope(
1598 FilterUpOptions::ReturnOuterNoSelf)) { // should be the component
1599 toDo.append(next);
1600 }
1601 } break;
1602 case DomType::ScriptExpression: // Js lexical scope
1603 first = false;
1605 toDo.append(next);
1606 break;
1607 case DomType::QmlComponent: { // ids/attached type
1608 if ((options & LookupOption::Strict) == 0) {
1609 if (DomItem comp = current.field(Fields::nextComponent))
1610 toDo.append(comp);
1611 }
1612 if (first && visitFirst && (options & LookupOption::VisitTopClassType)
1613 && *this == current) { // visit attached type if it is the top of the chain
1614 if (DomItem attachedT = current.field(Fields::attachedType).field(Fields::get))
1615 toDo.append(attachedT);
1616 }
1618 toDo.append(next);
1619
1620 DomItem owner = current.owner();
1621 Path pathToComponentMap = current.pathFromOwner().dropTail(2);
1622 DomItem componentMap = owner.path(pathToComponentMap);
1623 if (alreadyAddedComponentMaps.contains(componentMap.id()))
1624 break;
1625 alreadyAddedComponentMaps.insert(componentMap.id());
1626 const auto keys = componentMap.keys();
1627 for (const QString &x : keys) {
1628 DomItem componentList = componentMap.key(x);
1629 for (int i = 0; i < componentList.indexes(); ++i) {
1630 DomItem component = componentList.index(i);
1631 if (component != current && !visited->contains(component.id()))
1632 toDo.append(component);
1633 }
1634 }
1635 first = false;
1636 break;
1637 }
1638 case DomType::QmlFile: // subComponents, imported types
1639 if (DomItem iScope =
1640 current.field(Fields::importScope)) // treat file as a separate scope?
1641 toDo.append(iScope);
1642 first = false;
1643 break;
1644 case DomType::MethodInfo: // method arguments
1645 first = false;
1647 toDo.append(next);
1648 break;
1651 first = false;
1652 if (DomItem next = current.field(Fields::objects).index(0))
1653 toDo.append(next);
1654 break;
1655 default:
1656 first = false;
1658 .error(tr("Unexpected non scope object %1 (%2) reached in visitScopeChain")
1659 .arg(domTypeToString(current.internalKind()),
1660 current.canonicalPath().toString()))
1661 .handle(h);
1662 Q_ASSERT(false);
1663 break;
1664 }
1665 }
1666 return true;
1667}
1668
1670 const QString &symbolName, function_ref<bool(const DomItem &)> visitor, LookupOptions opts,
1671 const ErrorHandler &h, QSet<quintptr> *visited, QList<Path> *visitedRefs) const
1672{
1673 return visitScopeChain(
1674 [symbolName, visitor](const DomItem &obj) {
1675 return obj.visitLocalSymbolsNamed(symbolName,
1676 [visitor](const DomItem &el) { return visitor(el); });
1677 },
1678 opts, h, visited, visitedRefs);
1679}
1680
1682{
1684public:
1685 CppTypeInfo() = default;
1686
1687 static CppTypeInfo fromString(QStringView target, const ErrorHandler &h = nullptr)
1688 {
1689 CppTypeInfo res;
1690 QRegularExpression reTarget = QRegularExpression(QRegularExpression::anchoredPattern(
1691 uR"(QList<(?<list>[a-zA-Z_0-9:]+) *(?<listPtr>\*?)>|QMap< *(?<mapKey>[a-zA-Z_0-9:]+) *, *(?<mapValue>[a-zA-Z_0-9:]+) *(?<mapPtr>\*?)>|(?<baseType>[a-zA-Z_0-9:]+) *(?<ptr>\*?))"));
1692
1693 QRegularExpressionMatch m = reTarget.matchView(target);
1694 if (!m.hasMatch()) {
1696 .error(tr("Unexpected complex CppType %1").arg(target))
1697 .handle(h);
1698 }
1699 res.baseType = m.captured(u"baseType");
1700 res.isPointer = !m.captured(u"ptr").isEmpty();
1701 if (!m.captured(u"list").isEmpty()) {
1702 res.isList = true;
1703 res.baseType = m.captured(u"list");
1704 res.isPointer = !m.captured(u"listPtr").isEmpty();
1705 }
1706 if (!m.captured(u"mapValue").isEmpty()) {
1707 res.isMap = true;
1708 if (m.captured(u"mapKey") != u"QString") {
1710 .error(tr("Unexpected complex CppType %1 (map with non QString key)")
1711 .arg(target))
1712 .handle(h);
1713 }
1714 res.baseType = m.captured(u"mapValue");
1715 res.isPointer = !m.captured(u"mapPtr").isEmpty();
1716 }
1717 return res;
1718 }
1719
1721 bool isPointer = false;
1722 bool isMap = false;
1723 bool isList = false;
1724};
1725
1726static bool visitForLookupType(const DomItem &el, LookupType lookupType,
1727 function_ref<bool(const DomItem &)> visitor)
1728{
1729 bool correctType = false;
1730 DomType iType = el.internalKind();
1731 switch (lookupType) {
1732 case LookupType::Binding:
1733 correctType = (iType == DomType::Binding);
1734 break;
1735 case LookupType::Method:
1736 correctType = (iType == DomType::MethodInfo);
1737 break;
1738 case LookupType::Property:
1739 correctType = (iType == DomType::PropertyDefinition || iType == DomType::Binding);
1740 break;
1741 case LookupType::PropertyDef:
1742 correctType = (iType == DomType::PropertyDefinition);
1743 break;
1744 case LookupType::Type:
1745 correctType = (iType == DomType::Export); // accept direct QmlObject ref?
1746 break;
1747 default:
1748 Q_ASSERT(false);
1749 break;
1750 }
1751 if (correctType)
1752 return visitor(el);
1753 return true;
1754}
1755
1757 const DomItem &newIt, const QStringList &subpath,
1758 function_ref<bool(const DomItem &)> visitor, LookupType lookupType,
1759 const ErrorHandler &errorHandler, QList<Path> *visitedRefs)
1760{
1761 QList<ResolveToDo> lookupToDos(
1762 { ResolveToDo{ newIt, 1 } }); // invariant: always increase pathIndex to guarantee
1763 // end even with only partial visited match
1764 QList<QSet<quintptr>> lookupVisited(subpath.size() + 1);
1765 while (!lookupToDos.isEmpty()) {
1766 ResolveToDo tNow = lookupToDos.takeFirst();
1767 auto vNow = std::make_pair(tNow.item.id(), tNow.pathIndex);
1768 DomItem subNow = tNow.item;
1769 int iSubPath = tNow.pathIndex;
1770 Q_ASSERT(iSubPath < subpath.size());
1771 QString subPathNow = subpath[iSubPath++];
1772 DomItem scope = subNow.proceedToScope();
1773 if (iSubPath < subpath.size()) {
1774 if (vNow.first != 0) {
1775 if (lookupVisited[vNow.second].contains(vNow.first))
1776 continue;
1777 else
1778 lookupVisited[vNow.second].insert(vNow.first);
1779 }
1781 scope.visitDirectAccessibleScopes(
1782 [&lookupToDos, &subPathNow, iSubPath](const DomItem &el) {
1783 return el.visitLocalSymbolsNamed(
1784 subPathNow, [&lookupToDos, iSubPath](const DomItem &subEl) {
1785 lookupToDos.append({ subEl, iSubPath });
1786 return true;
1787 });
1788 },
1789 VisitPrototypesOption::Normal, errorHandler, &(lookupVisited[vNow.second]),
1790 visitedRefs);
1791 } else {
1792 bool cont = scope.visitDirectAccessibleScopes(
1793 [&visitor, &subPathNow, lookupType](const DomItem &el) -> bool {
1794 if (lookupType == LookupType::Symbol)
1795 return el.visitLocalSymbolsNamed(subPathNow, visitor);
1796 else
1797 return el.visitLocalSymbolsNamed(
1798 subPathNow, [lookupType, &visitor](const DomItem &el) -> bool {
1799 return visitForLookupType(el, lookupType, visitor);
1800 });
1801 },
1802 VisitPrototypesOption::Normal, errorHandler, &(lookupVisited[vNow.second]),
1803 visitedRefs);
1804 if (!cont)
1805 return false;
1806 }
1807 }
1808 return true;
1809}
1810
1812 const QString &target, function_ref<bool(const DomItem &)> visitor, LookupType lookupType,
1813 LookupOptions opts, const ErrorHandler &errorHandler, QSet<quintptr> *visited,
1814 QList<Path> *visitedRefs) const
1815{
1816 if (target.isEmpty())
1817 return true;
1818 switch (lookupType) {
1819 case LookupType::Binding:
1820 case LookupType::Method:
1821 case LookupType::Property:
1822 case LookupType::PropertyDef:
1823 case LookupType::Symbol:
1824 case LookupType::Type: {
1825 QStringList subpath = target.split(QChar::fromLatin1('.'));
1826 if (subpath.size() == 1) {
1827 return visitLookup1(subpath.first(), visitor, opts, errorHandler, visited, visitedRefs);
1828 } else {
1829 return visitLookup1(
1830 subpath.at(0),
1831 [&subpath, visitor, lookupType, &errorHandler,
1832 visitedRefs](const DomItem &newIt) -> bool {
1833 return visitQualifiedNameLookup(newIt, subpath, visitor, lookupType,
1834 errorHandler, visitedRefs);
1835 },
1836 opts, errorHandler, visited, visitedRefs);
1837 }
1838 break;
1839 }
1840 case LookupType::CppType:
1841 return true;
1842 }
1843 Q_ASSERT(false);
1844 return true;
1845}
1846
1847/*!
1848 \internal
1849 \brief Dereference DomItems pointing to other DomItems.
1850
1851 Dereferences DomItems with internalKind being References, Export and Id.
1852 Also does multiple rounds of resolving for nested DomItems.
1853 Prefer this over \l {DomItem::get}.
1854 */
1855DomItem DomItem::proceedToScope(const ErrorHandler &h, QList<Path> *visitedRefs) const
1856{
1857 // follow references, resolve exports
1858 DomItem current = *this;
1859 while (current) {
1860 switch (current.internalKind()) {
1861 case DomType::Reference: {
1862 Path currentPath = current.canonicalPath();
1863 current = current.get(h, visitedRefs);
1864 break;
1865 }
1866 case DomType::Export:
1867 current = current.field(Fields::type);
1868 break;
1869 case DomType::Id:
1870 current = current.field(Fields::referredObject);
1871 break;
1872 default:
1873 return current.scope();
1874 break;
1875 }
1876 }
1877 return DomItem();
1878}
1879
1880QList<DomItem> DomItem::lookup(const QString &symbolName, LookupType type, LookupOptions opts,
1881 const ErrorHandler &errorHandler) const
1882{
1883 QList<DomItem> res;
1884 visitLookup(
1885 symbolName,
1886 [&res](const DomItem &el) {
1887 res.append(el);
1888 return true;
1889 },
1890 type, opts, errorHandler);
1891 return res;
1892}
1893
1894DomItem DomItem::lookupFirst(const QString &symbolName, LookupType type, LookupOptions opts,
1895 const ErrorHandler &errorHandler) const
1896{
1897 DomItem res;
1898 visitLookup(
1899 symbolName,
1900 [&res](const DomItem &el) {
1901 res = el;
1902 return false;
1903 },
1904 type, opts, errorHandler);
1905 return res;
1906}
1907
1909{
1910 return visitEl([](auto &&b) { return b->id(); });
1911}
1912
1914{
1915 return visitEl([](auto &&e) { return e->pathFromOwner(); });
1916}
1917
1919{
1920 return visitEl([this](auto &&e) { return e->canonicalFilePath(*this); });
1921}
1922
1924{
1925 if (m_kind == DomType::Empty)
1926 return MutableDomItem();
1927 DomItem o = owner();
1928 if (option == CopyOption::EnvDisconnected) {
1929 DomItem newItem = std::visit([this, &o](auto &&el) {
1930 if constexpr (std::is_same_v<std::decay_t<decltype(el)>, std::monostate>) {
1931 return DomItem();
1932 } else {
1933 auto copyPtr = el->makeCopy(o);
1934 return DomItem(m_top, copyPtr, m_ownerPath, copyPtr.get());
1935 }
1936 }, m_owner);
1938 }
1939 DomItem env = environment();
1940 std::shared_ptr<DomEnvironment> newEnvPtr;
1941 if (std::shared_ptr<DomEnvironment> envPtr = env.ownerAs<DomEnvironment>()) {
1942 newEnvPtr = std::make_shared<DomEnvironment>(envPtr, envPtr->loadPaths(), envPtr->options(),
1943 envPtr->domCreationOption());
1944 DomBase *eBase = envPtr.get();
1945 if (std::holds_alternative<const DomEnvironment *>(m_element) && eBase
1946 && std::get<const DomEnvironment *>(m_element) == eBase)
1947 return MutableDomItem(DomItem(newEnvPtr));
1948 } else if (std::shared_ptr<DomUniverse> univPtr = top().ownerAs<DomUniverse>()) {
1949 newEnvPtr = std::make_shared<DomEnvironment>(
1950 QStringList(),
1951 DomEnvironment::Option::SingleThreaded | DomEnvironment::Option::NoDependencies,
1953 } else {
1954 Q_ASSERT(false);
1955 return {};
1956 }
1957 DomItem newItem = std::visit(
1958 [this, newEnvPtr, &o](auto &&el) {
1959 if constexpr (std::is_same_v<std::decay_t<decltype(el)>, std::monostate>) {
1960 return DomItem();
1961 } else {
1962 auto copyPtr = el->makeCopy(o);
1963 return DomItem(newEnvPtr, copyPtr, m_ownerPath, copyPtr.get());
1964 }
1965 },
1966 m_owner);
1967
1968 switch (o.internalKind()) {
1969 case DomType::JsFile:
1970 newEnvPtr->addJsFile(newItem.ownerAs<JsFile>(), AddOption::Overwrite);
1971 break;
1972 case DomType::QmlFile:
1973 newEnvPtr->addQmlFile(newItem.ownerAs<QmlFile>(), AddOption::Overwrite);
1974 break;
1975 case DomType::ScriptExpression:
1976 case DomType::AstComments:
1977 case DomType::LoadInfo:
1978 case DomType::FileLocationsNode:
1979 case DomType::DomEnvironment:
1980 case DomType::DomUniverse:
1981 qCWarning(domLog) << "DomItem::makeCopy " << internalKindStr()
1982 << " does not support binding to environment";
1983 Q_ASSERT(false);
1984 return MutableDomItem();
1985 default:
1986 qCWarning(domLog) << "DomItem::makeCopy(" << internalKindStr()
1987 << ") is not an known OwningItem";
1988 Q_ASSERT(o.isOwningItem());
1989 return MutableDomItem();
1990 }
1991 DomItem newEnv(newEnvPtr);
1992 Q_ASSERT(newEnv.path(o.canonicalPath()).m_owner == newItem.m_owner);
1994}
1995
1996bool DomItem::commitToBase(const std::shared_ptr<DomEnvironment> &validEnvPtr) const
1997{
1998 DomItem env = environment();
1999 if (std::shared_ptr<DomEnvironment> envPtr = env.ownerAs<DomEnvironment>()) {
2000 return envPtr->commitToBase(env, validEnvPtr);
2001 }
2002 return false;
2003}
2004
2005bool DomItem::visitLocalSymbolsNamed(const QString &name, function_ref<bool(const DomItem &)> visitor) const
2006{
2007 if (name.isEmpty()) // no empty symbol
2008 return true;
2009 // we could avoid discriminating by type and just access all the needed stuff in the correct
2010 // sequence, making sure it is empty if not provided, but for now I find it clearer to check the
2011 // type
2012 DomItem f;
2013 DomItem v;
2014 switch (internalKind()) {
2015 case DomType::QmlObject:
2016 f = field(Fields::propertyDefs);
2017 v = f.key(name);
2018 if (!v.visitIndexes(visitor))
2019 return false;
2020 f = field(Fields::bindings);
2021 v = f.key(name);
2022 if (!v.visitIndexes(visitor))
2023 return false;
2024 f = field(Fields::methods);
2025 v = f.key(name);
2026 if (!v.visitIndexes(visitor))
2027 return false;
2028 break;
2030 // to do
2031 break;
2033 f = field(Fields::ids);
2034 v = f.key(name);
2035 if (!v.visitIndexes(visitor))
2036 return false;
2037 Q_FALLTHROUGH();
2040 case DomType::MethodInfo: {
2041 DomItem params = field(Fields::parameters);
2042 if (!params.visitIndexes([name, visitor](const DomItem &p) {
2043 const MethodParameter *pPtr = p.as<MethodParameter>();
2044 if (pPtr->name == name && !visitor(p))
2045 return false;
2046 return true;
2047 }))
2048 return false;
2049 break;
2050 }
2051 case DomType::QmlFile: {
2052 f = field(Fields::components);
2053 v = f.key(name);
2054 if (!v.visitIndexes(visitor))
2055 return false;
2056 break;
2057 }
2058 default:
2059 Q_ASSERT(!isScope());
2060 break;
2061 }
2062 return true;
2063}
2064
2065DomItem DomItem::operator[](const QString &cName) const
2066{
2067 if (internalKind() == DomType::Map)
2068 return key(cName);
2069 if (auto fn = fieldNameFromString(cName))
2070 return field(*fn);
2071 return DomItem();
2072}
2073
2074DomItem DomItem::operator[](QStringView cName) const
2075{
2076 if (internalKind() == DomType::Map)
2077 return key(cName.toString());
2078 if (auto fn = fieldNameFromString(cName))
2079 return field(*fn);
2080 return DomItem();
2081}
2082
2083DomItem DomItem::operator[](const Path &p) const
2084{
2085 return path(p);
2086}
2087
2089{
2090 return base()->value();
2091}
2092
2093void DomItem::dumpPtr(const Sink &sink) const
2094{
2095 sink(u"DomItem{ topPtr:");
2096 sink(QString::number((quintptr)topPtr().get(), 16));
2097 sink(u", ownerPtr:");
2098 sink(QString::number((quintptr)owningItemPtr().get(), 16));
2099 sink(u", ownerPath:");
2100 m_ownerPath.dump(sink);
2101 sink(u", elPtr:");
2102 sink(QString::number((quintptr)base(),16));
2103 sink(u"}");
2104}
2105
2107 const Sink &s, int indent,
2108 function_ref<bool(const DomItem &, const PathEls::PathComponent &, const DomItem &)> filter) const
2109{
2110 visitEl([this, s, indent, filter](auto &&e) { e->dump(*this, s, indent, filter); });
2111}
2112
2114 const QString &path,
2115 function_ref<bool(const DomItem &, const PathEls::PathComponent &, const DomItem &)> filter,
2116 int indent, FileWriter *fw) const
2117{
2118 FileWriter localFw;
2119 if (!fw)
2120 fw = &localFw;
2121 switch (fw->write(path, [this, indent, filter](QTextStream &ts) {
2122 this->dump([&ts](QStringView s) { ts << s; }, indent, filter);
2123 return true;
2124 })) {
2125 case FileWriter::Status::ShouldWrite:
2126 case FileWriter::Status::SkippedDueToFailure:
2127 qWarning() << "Failure dumping " << canonicalPath() << " to " << path;
2128 break;
2129 case FileWriter::Status::DidWrite:
2130 case FileWriter::Status::SkippedEqual:
2131 break;
2132 }
2133 return fw->status;
2134}
2135
2137{
2138 return dumperToString([this](const Sink &s){ dump(s); });
2139}
2140
2142{
2143 return std::visit([](auto &&ow) {
2144 if constexpr (std::is_same_v<std::decay_t<decltype(ow)>, std::monostate>)
2145 return 0;
2146 else
2147 return ow->derivedFrom();
2148 }, m_owner);
2149}
2150
2151int DomItem::revision() const
2152{
2153 return std::visit([](auto &&ow) {
2154 if constexpr (std::is_same_v<std::decay_t<decltype(ow)>, std::monostate>)
2155 return -1;
2156 else
2157 return ow->revision();
2158 }, m_owner);
2159}
2160
2162{
2163 return std::visit([](auto &&ow) {
2164 if constexpr (std::is_same_v<std::decay_t<decltype(ow)>, std::monostate>)
2165 return QDateTime::fromMSecsSinceEpoch(0, QTimeZone::UTC);
2166 else
2167 return ow->createdAt();
2168 }, m_owner);
2169}
2170
2172{
2173 return std::visit([](auto &&ow) {
2174 if constexpr (std::is_same_v<std::decay_t<decltype(ow)>, std::monostate>)
2175 return QDateTime::fromMSecsSinceEpoch(0, QTimeZone::UTC);
2176 else
2177 return ow->frozenAt();
2178 }, m_owner);
2179}
2180
2182{
2183 return std::visit([](auto &&ow) {
2184 if constexpr (std::is_same_v<std::decay_t<decltype(ow)>, std::monostate>)
2185 return QDateTime::fromMSecsSinceEpoch(0, QTimeZone::UTC);
2186 else
2187 return ow->lastDataUpdateAt();
2188 }, m_owner);
2189}
2190
2192{
2193 std::visit([this, &msg](auto &&ow) {
2194 if constexpr (std::is_same_v<std::decay_t<decltype(ow)>, std::monostate>)
2196 else
2197 ow->addError(owner(), std::move(msg.withItem(*this)));
2198 }, m_owner);
2199}
2200
2202{
2203 // We need a copy here. Error handlers may be called when this is gone.
2204 return [self = *this](const ErrorMessage &m) { self.addError(ErrorMessage(m)); };
2205}
2206
2207void DomItem::clearErrors(const ErrorGroups &groups, bool iterate) const
2208{
2209 std::visit([&groups](auto &&ow) {
2210 if constexpr (!std::is_same_v<std::decay_t<decltype(ow)>, std::monostate>)
2211 ow->clearErrors(groups);
2212 }, m_owner);
2213
2214 if (iterate) {
2215 iterateSubOwners([groups](const DomItem &i){
2216 i.clearErrors(groups, true);
2217 return true;
2218 });
2219 }
2220}
2221
2223 function_ref<bool(const DomItem &, const ErrorMessage &)> visitor, bool iterate,
2224 Path inPath) const
2225{
2226 if (!std::visit([this, visitor, inPath](auto &&el) {
2227 if constexpr (std::is_same_v<std::decay_t<decltype(el)>, std::monostate>)
2228 return true;
2229 else
2230 return el->iterateErrors(owner(), visitor, inPath);
2231 }, m_owner)) {
2232 return false;
2233 }
2234
2235 if (iterate && !iterateSubOwners([inPath, visitor](const DomItem &i) {
2236 return i.iterateErrors(visitor, true, inPath);
2237 })) {
2238 return false;
2239 }
2240
2241 return true;
2242}
2243
2244bool DomItem::iterateSubOwners(function_ref<bool(const DomItem &)> visitor) const
2245{
2246 return std::visit([this, visitor](auto &&o) {
2247 if constexpr (std::is_same_v<std::decay_t<decltype(o)>, std::monostate>)
2248 return true;
2249 else
2250 return o->iterateSubOwners(owner(), visitor);
2251 }, m_owner);
2252}
2253
2254bool DomItem::iterateDirectSubpaths(DirectVisitor v) const
2255{
2256 return visitEl(
2257 [this, v](auto &&el) { return el->iterateDirectSubpaths(*this, v); });
2258}
2259
2260DomItem DomItem::subReferencesItem(const PathEls::PathComponent &c, const QList<Path> &paths) const
2261{
2262 return subListItem(
2263 List::fromQList<Path>(pathFromOwner().withComponent(c), paths,
2264 [](const DomItem &list, const PathEls::PathComponent &p, const Path &el) {
2265 return list.subReferenceItem(p, el);
2266 }));
2267}
2268
2269DomItem DomItem::subReferenceItem(const PathEls::PathComponent &c, const Path &referencedObject) const
2270{
2272 return DomItem(m_top, m_owner, m_ownerPath, Reference(referencedObject, Path::fromComponent(c)));
2273 } else {
2274 return DomItem(m_top, m_owner, m_ownerPath,
2275 Reference(referencedObject, pathFromOwner().withComponent(c)));
2276 }
2277}
2278
2279shared_ptr<DomTop> DomItem::topPtr() const
2280{
2281 return std::visit([](auto &&el) -> shared_ptr<DomTop> {
2282 if constexpr (std::is_same_v<std::decay_t<decltype(el)>, std::monostate>)
2283 return {};
2284 else
2285 return el;
2286 }, m_top);
2287}
2288
2290{
2291 return std::visit([](auto &&el) -> shared_ptr<OwningItem> {
2292 if constexpr (std::is_same_v<std::decay_t<decltype(el)>, std::monostate>)
2293 return {};
2294 else
2295 return el;
2296 }, m_owner);
2297}
2298
2299/*!
2300 \internal
2301 Returns a pointer to the virtual base pointer to a DomBase.
2302*/
2303const DomBase *DomItem::base() const
2304{
2305 return visitEl([](auto &&el) -> const DomBase * { return el->domBase(); });
2306}
2307
2308DomItem::DomItem(const std::shared_ptr<DomEnvironment> &envPtr):
2309 DomItem(envPtr, envPtr, Path(), envPtr.get())
2310{
2311}
2312
2313DomItem::DomItem(const std::shared_ptr<DomUniverse> &universePtr):
2314 DomItem(universePtr, universePtr, Path(), universePtr.get())
2315{
2316}
2317
2318/*!
2319\brief Creates a new document with the given code
2320
2321This is mostly useful for testing or loading a single code snippet without any dependency.
2322The fileType should normally be QmlFile, but you might want to load a qmltypes file for
2323example and interpret it as qmltypes file (not plain Qml), or as JsFile. In those case
2324set the file type accordingly.
2325*/
2326DomItem DomItem::fromCode(const QString &code, DomType fileType)
2327{
2328 if (code.isEmpty())
2329 return DomItem();
2330
2331 auto env = DomEnvironment::create({}, DomEnvironment::Option::NoDependencies);
2332 DomItem tFile;
2333 env->loadFile(
2334 FileToLoad::fromMemory(env, QString(), code),
2335 [&tFile](Path, const DomItem &, const DomItem &newIt) { tFile = newIt; },
2336 std::make_optional(fileType));
2337 return tFile.fileObject();
2338}
2339
2340Empty::Empty()
2341{}
2342
2343Path Empty::pathFromOwner() const
2344{
2345 return Path();
2346}
2347
2348Path Empty::canonicalPath(const DomItem &) const
2349{
2350 return Path();
2351}
2352
2354{
2355 return true;
2356}
2357
2358DomItem Empty::containingObject(const DomItem &self) const
2359{
2360 return self;
2361}
2362
2363void Empty::dump(
2364 const DomItem &, const Sink &s, int,
2365 function_ref<bool(const DomItem &, const PathEls::PathComponent &, const DomItem &)>) const
2366{
2367 s(u"null");
2368}
2369
2370Map::Map(const Path &pathFromOwner, const Map::LookupFunction &lookup,
2371 const Keys &keys, const QString &targetType)
2373{}
2374
2376{
2377 return quintptr(0);
2378}
2379
2380bool Map::iterateDirectSubpaths(const DomItem &self, DirectVisitor visitor) const
2381{
2382 QSet<QString> ksSet = keys(self);
2383 QStringList ksList = QStringList(ksSet.begin(), ksSet.end());
2384 std::sort(ksList.begin(), ksList.end());
2385 for (const QString &k : std::as_const(ksList)) {
2386 if (!visitor(PathEls::Key(k), [&self, this, k]() { return key(self, k); }))
2387 return false;
2388 }
2389 return true;
2390}
2391
2392const QSet<QString> Map::keys(const DomItem &self) const
2393{
2394 return m_keys(self);
2395}
2396
2397DomItem Map::key(const DomItem &self, const QString &name) const
2398{
2399 return m_lookup(self, name);
2400}
2401
2403 const DomItem &self, const Sink &sink, int indent,
2404 function_ref<bool(const DomItem &, const PathEls::PathComponent &, const DomItem &)> filter) const
2405{
2406 bool comma = false;
2407 DomKind dK = self.domKind();
2408 switch (dK) {
2409 case DomKind::Object:
2410 sink(u"{ \"~type~\":");
2411 sinkEscaped(sink, typeName());
2412 comma = true;
2413 break;
2414 case DomKind::Value:
2415 {
2416 sink(QString::fromUtf8(value().toJsonValue().toJson()));
2417 break;
2418 }
2419 case DomKind::Empty:
2420 sink(u"null");
2421 break;
2422 case DomKind::List:
2423 sink(u"[");
2424 break;
2425 case DomKind::Map:
2426 sink(u"{");
2427 break;
2428 case DomKind::ScriptElement:
2429 // nothing to print
2430 break;
2431 }
2432 auto closeParens = qScopeGuard(
2433 [dK, sink, indent]{
2434 switch (dK) {
2435 case DomKind::Object:
2436 sinkNewline(sink, indent);
2437 sink(u"}");
2438 break;
2439 case DomKind::Value:
2440 break;
2441 case DomKind::Empty:
2442 break;
2443 case DomKind::List:
2444 sinkNewline(sink, indent);
2445 sink(u"]");
2446 break;
2447 case DomKind::Map:
2448 sinkNewline(sink, indent);
2449 sink(u"}");
2450 break;
2451 case DomKind::ScriptElement:
2452 // nothing to print
2453 break;
2454 }
2455 });
2456 index_type idx = 0;
2457 self.iterateDirectSubpaths(
2458 [&comma, &idx, dK, sink, indent, &self, filter](const PathEls::PathComponent &c,
2459 function_ref<DomItem()> itemF) {
2460 DomItem i = itemF();
2461 if (!filter(self, c, i))
2462 return true;
2463 if (comma)
2464 sink(u",");
2465 else
2466 comma = true;
2467 switch (c.kind()) {
2468 case Path::Kind::Field:
2469 sinkNewline(sink, indent + 2);
2470 if (dK != DomKind::Object)
2471 sink(u"UNEXPECTED ENTRY ERROR:");
2472 sinkEscaped(sink, c.name());
2473 sink(u":");
2474 break;
2475 case Path::Kind::Key:
2476 sinkNewline(sink, indent + 2);
2477 if (dK != DomKind::Map)
2478 sink(u"UNEXPECTED ENTRY ERROR:");
2479 sinkEscaped(sink, c.name());
2480 sink(u":");
2481 break;
2482 case Path::Kind::Index:
2483 sinkNewline(sink, indent + 2);
2484 if (dK != DomKind::List)
2485 sink(u"UNEXPECTED ENTRY ERROR:");
2486 else if (idx++ != c.index())
2487 sink(u"OUT OF ORDER ARRAY:");
2488 break;
2489 default:
2490 sinkNewline(sink, indent + 2);
2491 sink(u"UNEXPECTED PATH KIND ERROR (ignored)");
2492 break;
2493 }
2494 if (self.isCanonicalChild(i)) {
2495 i.dump(sink, indent + 2, filter);
2496 } else {
2497 sink(uR"({ "~type~": "Reference", "immediate": true, "referredObjectPath":")");
2498 i.canonicalPath().dump([sink](QStringView s) {
2499 sinkEscaped(sink, s, EscapeOptions::NoOuterQuotes);
2500 });
2501 sink(u"\"}");
2502 }
2503 return true;
2504 });
2505}
2506
2507List::List(const Path &pathFromOwner, const List::LookupFunction &lookup,
2508 const List::Length &length, const List::IteratorFunction &iterator,
2509 const QString &elType):
2512{}
2513
2515{
2516 return quintptr(0);
2517}
2518
2520 const DomItem &self, const Sink &sink, int indent,
2521 function_ref<bool(const DomItem &, const PathEls::PathComponent &, const DomItem &)> filter) const
2522{
2523 bool first = true;
2524 sink(u"[");
2525 iterateDirectSubpaths(
2526 self,
2527 [&self, indent, &first, sink, filter](const PathEls::PathComponent &c,
2528 function_ref<DomItem()> itemF) {
2529 DomItem item = itemF();
2530 if (!filter(self, c, item))
2531 return true;
2532 if (first)
2533 first = false;
2534 else
2535 sink(u",");
2536 sinkNewline(sink, indent + 2);
2537 item.dump(sink, indent + 2, filter);
2538 return true;
2539 });
2540 sink(u"]");
2541}
2542
2543bool List::iterateDirectSubpaths(const DomItem &self, DirectVisitor visitor) const
2544{
2545 if (m_iterator) {
2546 return m_iterator(self, [visitor](index_type i, function_ref<DomItem()> itemF) {
2547 return visitor(PathEls::Index(i), itemF);
2548 });
2549 }
2550 index_type len = indexes(self);
2551 for (index_type i = 0; i < len; ++i) {
2552 if (!visitor(PathEls::Index(i), [this, &self, i]() { return index(self, i); }))
2553 return false;
2554 }
2555 return true;
2556}
2557
2558index_type List::indexes(const DomItem &self) const
2559{
2560 return m_length(self);
2561}
2562
2563DomItem List::index(const DomItem &self, index_type index) const
2564{
2565 return m_lookup(self, index);
2566}
2567
2568void List::writeOut(const DomItem &self, OutWriter &ow, bool compact) const
2569{
2570 const auto fLoc = FileLocations::treeOf(self);
2571 ow.writeRegion(fLoc, LeftBracketRegion);
2572 bool first = true;
2573 iterateDirectSubpaths(self,
2574 [&ow, &first, &fLoc, compact](const PathEls::PathComponent &,
2575 function_ref<DomItem()> elF) {
2576 if (first)
2577 first = false;
2578 else
2579 ow.writeRegion(fLoc, CommaTokenRegion).ensureSpace();
2580 if (!compact)
2581 ow.ensureNewline(1);
2582 DomItem el = elF();
2583 el.writeOut(ow);
2584 return true;
2585 });
2586 if (!compact && !first)
2587 ow.newline();
2588 ow.writeRegion(fLoc, RightBracketRegion);
2589}
2590
2592
2594{
2595 Q_ASSERT(m_pathFromOwner && "uninitialized DomElement");
2596 return self.owner().canonicalPath().withPath(m_pathFromOwner);
2597}
2598
2600{
2601 Q_ASSERT(m_pathFromOwner && "uninitialized DomElement");
2602 return DomBase::containingObject(self);
2603}
2604
2606{
2607 //if (!domTypeCanBeInline(kind()))
2608 m_pathFromOwner = newPath;
2609}
2610
2612{
2613 for (const Path &p : referredObjectPath) {
2614 switch (p.headKind()) {
2615 case Path::Kind::Current:
2616 // headKind() guarantees the head is a Current, so headCurrent() has a value.
2617 switch (*p.headCurrent()) {
2618 case PathCurrent::Lookup:
2619 case PathCurrent::LookupDynamic:
2620 case PathCurrent::LookupStrict:
2621 return true;
2622 default:
2623 break;
2624 }
2625 break;
2626 case Path::Kind::Empty:
2627 return true;
2628 default:
2629 break;
2630 }
2631 }
2632 return false;
2633}
2634
2635Reference::Reference(const Path &referredObject, const Path &pathFromOwner, const SourceLocation &)
2637{
2638}
2639
2641{
2642 return quintptr(0);
2643}
2644
2645bool Reference::iterateDirectSubpaths(const DomItem &self, DirectVisitor visitor) const
2646{
2647 bool cont = true;
2648 cont = cont && self.invokeVisitorOnLazyField(visitor, Fields::referredObjectPath, [this]() {
2649 return referredObjectPath.toString();
2650 });
2651 cont = cont && visitor(Fields::get, [this, &self]() { return this->get(self); });
2652 return cont;
2653}
2654
2655DomItem Reference::field(const DomItem &self, FieldName name) const
2656{
2657 if (Fields::referredObjectPath == name) {
2658 return self.subDataItem(Fields::referredObjectPath,
2659 referredObjectPath.toString());
2660 }
2661 if (Fields::get == name)
2662 return get(self);
2663 return DomItem();
2664}
2665
2667{
2668 return QList<QString>({fieldNameToQString(Fields::referredObjectPath), fieldNameToQString(Fields::get)});
2669}
2670
2672{
2673 return DomItem();
2674}
2675
2676DomItem Reference::key(const DomItem &, const QString &) const
2677{
2678 return DomItem();
2679}
2680
2681DomItem Reference::get(const DomItem &self, const ErrorHandler &h, QList<Path> *visitedRefs) const
2682{
2683 DomItem res;
2684 if (referredObjectPath) {
2685 DomItem env;
2686 Path selfPath;
2687 Path cachedPath;
2688 if (shouldCache()) {
2689 env = self.environment();
2690 if (env) {
2691 selfPath = self.canonicalPath();
2692 RefCacheEntry cached = RefCacheEntry::forPath(self, selfPath);
2693 switch (cached.cached) {
2694 case RefCacheEntry::Cached::None:
2695 break;
2696 case RefCacheEntry::Cached::First:
2697 case RefCacheEntry::Cached::All:
2698 if (!cached.canonicalPaths.isEmpty())
2699 cachedPath = cached.canonicalPaths.first();
2700 else
2701 return res;
2702 break;
2703 }
2704 if (cachedPath) {
2705 res = env.path(cachedPath);
2706 if (!res)
2707 qCWarning(refLog) << "referenceCache outdated, reference at " << selfPath
2708 << " leads to invalid path " << cachedPath;
2709 else
2710 return res;
2711 }
2712 }
2713 }
2714 QList<Path> visitedRefsLocal;
2715 self.resolve(
2716 referredObjectPath,
2717 [&res](Path, const DomItem &el) {
2718 res = el;
2719 return false;
2720 },
2721 h, referredObjectPath, (visitedRefs ? visitedRefs : &visitedRefsLocal));
2722 if (env)
2724 env, selfPath, RefCacheEntry { RefCacheEntry::Cached::First, { cachedPath } });
2725 }
2726 return res;
2727}
2728
2730 const DomItem &self, const ErrorHandler &h, QList<Path> *visitedRefs) const
2731{
2732 QList<DomItem> res;
2733 if (referredObjectPath) {
2734 DomItem env;
2735 Path selfPath;
2736 QList<Path> cachedPaths;
2737 if (shouldCache()) {
2738 selfPath = canonicalPath(self);
2739 env = self.environment();
2740 RefCacheEntry cached = RefCacheEntry::forPath(env, selfPath);
2741 switch (cached.cached) {
2742 case RefCacheEntry::Cached::None:
2743 case RefCacheEntry::Cached::First:
2744 break;
2745 case RefCacheEntry::Cached::All:
2746 cachedPaths += cached.canonicalPaths;
2747 if (cachedPaths.isEmpty())
2748 return res;
2749 }
2750 }
2751 if (!cachedPaths.isEmpty()) {
2752 bool outdated = false;
2753 for (const Path &p : cachedPaths) {
2754 DomItem newEl = env.path(p);
2755 if (!newEl) {
2756 outdated = true;
2757 qCWarning(refLog) << "referenceCache outdated, reference at " << selfPath
2758 << " leads to invalid path " << p;
2759 break;
2760 } else {
2761 res.append(newEl);
2762 }
2763 }
2764 if (outdated) {
2765 res.clear();
2766 } else {
2767 return res;
2768 }
2769 }
2770 self.resolve(
2771 referredObjectPath,
2772 [&res](Path, const DomItem &el) {
2773 res.append(el);
2774 return true;
2775 },
2776 h, referredObjectPath, visitedRefs);
2777 if (env) {
2778 QList<Path> canonicalPaths;
2779 for (const DomItem &i : res) {
2780 if (i)
2781 canonicalPaths.append(i.canonicalPath());
2782 else
2783 qCWarning(refLog)
2784 << "getAll of reference at " << selfPath << " visits empty items.";
2785 }
2787 env, selfPath,
2788 RefCacheEntry { RefCacheEntry::Cached::All, std::move(canonicalPaths) });
2789 }
2790 }
2791 return res;
2792}
2793
2794/*!
2795\internal
2796\class QQmlJS::Dom::OwningItem
2797
2798\brief A DomItem that owns other DomItems and is managed through a shared pointer
2799
2800This is the unit of update of the Dom model, only OwningItem can be updated after
2801exposed, to update a single element one has to copy its owner, change it, and expose an new one.
2802The non owning contents of an exposed OwiningItem can safely be considered immutable, and pointers
2803to them must remain valid for the whole lifetime of the OwningItem (that is managed with
2804shared_ptr), only the sub OwningItems *might* be change.
2805The OwningItem has a mutex that controls it access (mainly for the errors, observers, and sub
2806OwningItems), Access to the rest is *not* controlled, it should either be by a single thread
2807(during construction), or immutable (after pubblication).
2808
2809*/
2810
2811OwningItem::OwningItem(int derivedFrom)
2812 : m_derivedFrom(derivedFrom),
2813 m_revision(nextRevision()),
2817{}
2818
2819OwningItem::OwningItem(int derivedFrom, const QDateTime &lastDataUpdateAt)
2820 : m_derivedFrom(derivedFrom),
2821 m_revision(nextRevision()),
2825{}
2826
2828 : m_derivedFrom(o.revision()),
2829 m_revision(nextRevision()),
2833{
2834 QMultiMap<Path, ErrorMessage> my_errors;
2835 {
2836 QMutexLocker l1(o.mutex());
2837 my_errors = o.m_errors;
2838
2839 }
2840 {
2841 QMutexLocker l2(mutex());
2842 m_errors = my_errors;
2843 }
2844}
2845
2846
2848{
2849 static QAtomicInt nextRev(0);
2850 return ++nextRev;
2851}
2852
2853bool OwningItem::iterateDirectSubpaths(const DomItem &self, DirectVisitor visitor) const
2854{
2855 bool cont = true;
2856 cont = cont && visitor(Fields::errors, [&self, this]() {
2857 // only for traversal/dumps; keyed by Path::toString() to avoid
2858 // reparsing the path in Map::key()
2859 QMap<QString, ErrorMessage> myErrors;
2860 for (const auto &[path, msg] : localErrors().asKeyValueRange())
2861 myErrors.insert(path.toString(), msg);
2862 return self.subMapItem(Map(
2863 self.pathFromOwner().withField(Fields::errors),
2864 [myErrors](const DomItem &map, const QString &name) {
2865 auto it = myErrors.find(name);
2866 if (it != myErrors.end())
2867 return map.subDataItem(PathEls::Key(name), it->toCbor());
2868 return DomItem();
2869 },
2870 [myErrors](const DomItem &) {
2871 return QSet<QString>(myErrors.keyBegin(), myErrors.keyEnd());
2872 },
2873 QLatin1String("ErrorMessages")));
2874 });
2875 return cont;
2876}
2877
2879{
2881 if (s.pathFromSource) {
2882 if (!s.pathToSource)
2883 return DomItem();
2884 return self.path(s.pathToSource);
2885 }
2886 return DomItem();
2887}
2888
2890{
2891 return m_derivedFrom;
2892}
2893
2895{
2896 return m_revision;
2897}
2898
2899bool OwningItem::frozen() const
2900{
2901 return m_frozenAt > m_createdAt;
2902}
2903
2905{
2906 if (!frozen()) {
2907 m_frozenAt = QDateTime::currentDateTimeUtc();
2908 if (m_frozenAt <= m_createdAt)
2909 m_frozenAt = m_createdAt.addSecs(1);
2910 return true;
2911 }
2912 return false;
2913}
2914
2916{
2917 return m_createdAt;
2918}
2919
2921{
2922 return m_lastDataUpdateAt;
2923}
2924
2926{
2927 return m_frozenAt;
2928}
2929
2930void OwningItem::refreshedDataAt(QDateTime tNew)
2931{
2932 if (m_lastDataUpdateAt < tNew) // remove check?
2933 m_lastDataUpdateAt = tNew;
2934}
2935
2937{
2938 addErrorLocal(std::move(msg));
2939}
2940
2942{
2943 QMutexLocker l(mutex());
2944 quint32 &c = m_errorsCounts[msg];
2945 c += 1;
2946 if (c == 1)
2947 m_errors.insert(msg.path, msg);
2948}
2949
2951{
2952 QMutexLocker l(mutex());
2953 auto it = m_errors.begin();
2954 while (it != m_errors.end()) {
2955 if (it->errorGroups == groups)
2956 it = m_errors.erase(it);
2957 else
2958 ++it;
2959 }
2960}
2961
2963 const DomItem &self, function_ref<bool(const DomItem &, const ErrorMessage &)> visitor,
2964 const Path &inPath)
2965{
2966 QMultiMap<Path, ErrorMessage> myErrors;
2967 {
2968 QMutexLocker l(mutex());
2969 myErrors = m_errors;
2970 }
2971 auto it = myErrors.lowerBound(inPath);
2972 auto end = myErrors.end();
2973 while (it != end && it.key().mid(0, inPath.length()) == inPath) {
2974 if (!visitor(self, *it++))
2975 return false;
2976 }
2977 return true;
2978}
2979
2980bool OwningItem::iterateSubOwners(const DomItem &self, function_ref<bool(const DomItem &owner)> visitor)
2981{
2982 return self.iterateDirectSubpaths(
2983 [&self, visitor](const PathEls::PathComponent &, function_ref<DomItem()> iF) {
2984 DomItem i = iF();
2985 if (i.owningItemPtr() != self.owningItemPtr()) {
2986 DomItem container = i.container();
2987 if (container.id() == self.id())
2988 return visitor(i);
2989 }
2990 return true;
2991 });
2992}
2993
2994bool operator==(const DomItem &o1, const DomItem &o2)
2995{
2996 if (o1.m_kind != o2.m_kind)
2997 return false;
2998 return o1.visitEl([&o1, &o2](auto &&el1) {
2999 auto &&el2 = std::get<std::decay_t<decltype(el1)>>(o2.m_element);
3000 auto id1 = el1->id();
3001 auto id2 = el2->id();
3002 if (id1 != id2)
3003 return false;
3004 if (id1 != quintptr(0))
3005 return true;
3006 if (o1.m_owner != o2.m_owner)
3007 return false;
3008 Path p1 = el1->pathFromOwner();
3009 Path p2 = el2->pathFromOwner();
3010 if (p1 != p2)
3011 return false;
3012 return true;
3013 });
3014}
3015
3017{
3018 MutableDomItem self;
3019 return [&self](const ErrorMessage &m) { self.addError(ErrorMessage(m)); };
3020}
3021
3023 const PropertyDefinition &propertyDef, AddOption option)
3024{
3025 if (QmlObject *el = mutableAs<QmlObject>())
3026 return el->addPropertyDef(*this, propertyDef, option);
3027 else
3028 Q_ASSERT(false && "addPropertyDef on non qml scope");
3029 return MutableDomItem();
3030}
3031
3033{
3034 if (QmlObject *el = mutableAs<QmlObject>())
3035 return el->addBinding(*this, binding, option);
3036 else
3037 Q_ASSERT(false && "addBinding on non qml scope");
3038 return MutableDomItem();
3039}
3040
3042{
3043 if (QmlObject *el = mutableAs<QmlObject>())
3044 return el->addMethod(*this, functionDef, option);
3045 else
3046 Q_ASSERT(false && "addMethod on non qml scope");
3047 return MutableDomItem();
3048}
3049
3051{
3052 if (QmlObject *el = mutableAs<QmlObject>()) {
3053 return el->addChild(*this, child);
3054 } else if (QmlComponent *el = mutableAs<QmlComponent>()) {
3055 Path p = el->addObject(child);
3056 return owner().path(p); // convenience: treat component objects as children
3057 } else {
3058 Q_ASSERT(false && "addChild on non qml scope");
3059 }
3060 return MutableDomItem();
3061}
3062
3063
3064QDebug operator<<(QDebug debug, const DomItem &c)
3065{
3066 dumperToQDebug([&c](const Sink &s) { c.dump(s); }, debug);
3067 return debug;
3068}
3069
3070QDebug operator<<(QDebug debug, const MutableDomItem &c)
3071{
3072 MutableDomItem cc(c);
3073 return debug.noquote().nospace() << "MutableDomItem(" << domTypeToString(cc.internalKind())
3074 << ", " << cc.canonicalPath().toString() << ")";
3075}
3076
3077bool ListPBase::iterateDirectSubpaths(const DomItem &self, DirectVisitor v) const
3078{
3079 index_type len = index_type(m_pList.size());
3080 for (index_type i = 0; i < len; ++i) {
3081 if (!v(PathEls::Index(i), [this, &self, i] { return this->index(self, i); }))
3082 return false;
3083 }
3084 return true;
3085}
3086
3087void ListPBase::writeOut(const DomItem &self, OutWriter &ow, bool compact) const
3088{
3089 const auto fLoc = FileLocations::treeOf(self);
3090 ow.writeRegion(fLoc, LeftBracketRegion);
3091 bool first = true;
3092 index_type len = index_type(m_pList.size());
3093 for (index_type i = 0; i < len; ++i) {
3094 if (first)
3095 first = false;
3096 else
3097 ow.writeRegion(fLoc, CommaTokenRegion).ensureSpace();
3098 if (!compact)
3099 ow.ensureNewline(1);
3100 DomItem el = index(self, i);
3101 el.writeOut(ow);
3102 }
3103 if (!compact && !first)
3104 ow.newline();
3105 ow.writeRegion(fLoc, RightBracketRegion);
3106}
3107
3109{
3110 return m_scope;
3111}
3112void ScriptElement::setSemanticScope(const QQmlJSScope::ConstPtr &scope)
3113{
3114 m_scope = scope;
3115}
3116
3117/*!
3118 \internal
3119 \brief Returns a pointer to the virtual base for virtual method calls.
3120
3121 A helper to call virtual methods without having to call std::visit(...).
3122 */
3124{
3125 if (!m_data)
3126 return nullptr;
3127
3128 return std::visit(
3129 [](auto &&e) {
3130 // std::reinterpret_pointer_cast does not exist on qnx it seems...
3131 return std::shared_ptr<ScriptElement>(
3132 e, static_cast<ScriptElement *>(e.get()));
3133 },
3134 *m_data);
3135}
3136
3137std::shared_ptr<ExternalOwningItem> getFileItemOwner(const DomItem &fileItem)
3138{
3139 switch (fileItem.internalKind()) {
3140 case DomType::JsFile:
3141 return fileItem.ownerAs<JsFile>();
3142 case DomType::QmlFile:
3143 return fileItem.ownerAs<QmlFile>();
3144 default:
3145 Q_UNREACHABLE_RETURN({});
3146 }
3147}
3148
3149} // end namespace Dom
3150} // end namespace QQmlJS
3151
3152QT_END_NAMESPACE
3153
3154#include "moc_qqmldomitem_p.cpp"
Path addObject(const QmlObject &object, QmlObject **oPtr=nullptr)
DomKind domKind() const override
quintptr id() const override
bool iterateDirectSubpaths(const DomItem &self, DirectVisitor) const override
ConstantData(const Path &pathFromOwner, const QCborValue &value)
static CppTypeInfo fromString(QStringView target, const ErrorHandler &h=nullptr)
virtual DomItem containingObject(const DomItem &self) const
virtual void writeOut(const DomItem &self, OutWriter &lw) const
virtual QString canonicalFilePath(const DomItem &self) const
virtual void dump(const DomItem &, const Sink &sink, int indent, FilterT filter) const
virtual void updatePathFromOwner(const Path &newPath)
Path canonicalPath(const DomItem &self) const override
DomElement(const Path &pathFromOwner=Path())
DomItem containingObject(const DomItem &self) const override
A value type that references any element of the Dom.
DomItem top() const
DomItem goUp(int) const
QDateTime createdAt() const
std::shared_ptr< OwningItem > owningItemPtr() const
DomItem operator[](const QString &component) const
QString toString() const
void writeOutPost(OutWriter &lw) const
bool visitTree(const Path &basePath, ChildrenVisitor visitor, VisitOptions options=VisitOption::Default, ChildrenVisitor openingVisitor=emptyChildrenVisitor, ChildrenVisitor closingVisitor=emptyChildrenVisitor, const FieldFilter &filter=FieldFilter::noFilter()) const
Visits recursively all the children of this item using the given visitors.
bool resolve(const Path &path, Visitor visitor, const ErrorHandler &errorHandler, const Path &fullPath=Path(), QList< Path > *visitedRefs=nullptr) const
DomItem path(const Path &p, const ErrorHandler &h=&defaultErrorHandler) const
DomItem containingFile() const
DomItem filterUp(function_ref< bool(DomType k, const DomItem &)> filter, FilterUpOptions options) const
DomItem scope(FilterUpOptions options=FilterUpOptions::ReturnOuter) const
bool visitLookup1(const QString &symbolName, function_ref< bool(const DomItem &)> visitor, LookupOptions=LookupOption::Normal, const ErrorHandler &h=nullptr, QSet< quintptr > *visited=nullptr, QList< Path > *visitedRefs=nullptr) const
DomItem get(const ErrorHandler &h=nullptr, QList< Path > *visitedRefs=nullptr) const
static ErrorGroups myErrors()
DomItem operator[](const char16_t *component) const
bool visitUp(function_ref< bool(const DomItem &)> visitor) const
Let the visitor visit the Dom Tree hierarchy of this DomItem.
index_type indexes() const
bool hasAnnotations() const
bool iterateSubOwners(function_ref< bool(const DomItem &owner)> visitor) const
MutableDomItem makeCopy(CopyOption option=CopyOption::EnvConnected) const
bool iterateErrors(function_ref< bool(const DomItem &, const ErrorMessage &)> visitor, bool iterate, Path inPath=Path()) const
DomItem proceedToScope(const ErrorHandler &h=nullptr, QList< Path > *visitedRefs=nullptr) const
Dereference DomItems pointing to other DomItems.
QList< DomItem > values() const
DomItem universe() const
bool iterateDirectSubpaths(DirectVisitor v) const
DomItem container() const
void clearErrors(const ErrorGroups &groups=ErrorGroups({}), bool iterate=true) const
quintptr id() const
QList< QString > fields() const
bool writeOut(const QString &path, const LineWriterOptions &opt=LineWriterOptions(), FileWriter *fw=nullptr, WriteOutChecks extraChecks=WriteOutCheck::Default) const
DomItem(const std::shared_ptr< DomEnvironment > &)
FileWriter::Status dump(const QString &path, function_ref< bool(const DomItem &, const PathEls::PathComponent &, const DomItem &)> filter=noFilter, int indent=0, FileWriter *fw=nullptr) const
bool visitScopeChain(function_ref< bool(const DomItem &)> visitor, LookupOptions=LookupOption::Normal, const ErrorHandler &h=nullptr, QSet< quintptr > *visited=nullptr, QList< Path > *visitedRefs=nullptr) const
Let the visitor visit the QML scope hierarchy of this DomItem.
std::shared_ptr< DomTop > topPtr() const
QCborValue value() const
QDateTime frozenAt() const
DomItem subListItem(const List &list) const
DomItem component(GoTo option=GoTo::Strict) const
bool visitLookup(const QString &symbolName, function_ref< bool(const DomItem &)> visitor, LookupType type=LookupType::Symbol, LookupOptions=LookupOption::Normal, const ErrorHandler &errorHandler=nullptr, QSet< quintptr > *visited=nullptr, QList< Path > *visitedRefs=nullptr) const
void writeOutPre(OutWriter &lw) const
DomItem lookupFirst(const QString &symbolName, LookupType type=LookupType::Symbol, LookupOptions=LookupOption::Normal, const ErrorHandler &errorHandler=nullptr) const
bool visitIndexes(function_ref< bool(const DomItem &)> visitor) const
DomItem fileObject(GoTo option=GoTo::Strict) const
bool visitKeys(function_ref< bool(const QString &, const DomItem &)> visitor) const
bool visitStaticTypePrototypeChains(function_ref< bool(const DomItem &)> visitor, VisitPrototypesOptions options=VisitPrototypesOption::Normal, const ErrorHandler &h=nullptr, QSet< quintptr > *visited=nullptr, QList< Path > *visitedRefs=nullptr) const
DomItem::visitStaticTypePrototypeChains.
QQmlJSScope::ConstPtr semanticScope() const
bool writeOutForFile(OutWriter &ow, WriteOutChecks extraChecks) const
bool commitToBase(const std::shared_ptr< DomEnvironment > &validPtr=nullptr) const
DomItem operator[](FieldName name) const
DomItem field(FieldName name) const
QList< DomItem > lookup(const QString &symbolName, LookupType type=LookupType::Symbol, LookupOptions=LookupOption::Normal, const ErrorHandler &errorHandler=nullptr) const
void dump(const Sink &, int indent=0, function_ref< bool(const DomItem &, const PathEls::PathComponent &, const DomItem &)> filter=noFilter) const
friend QMLDOM_EXPORT bool operator==(const DomItem &, const DomItem &)
QSet< QString > propertyInfoNames() const
static ErrorGroups myResolveErrors()
bool visitDirectAccessibleScopes(function_ref< bool(const DomItem &)> visitor, VisitPrototypesOptions options=VisitPrototypesOption::Normal, const ErrorHandler &h=nullptr, QSet< quintptr > *visited=nullptr, QList< Path > *visitedRefs=nullptr) const
DomItem environment() const
bool isCanonicalChild(const DomItem &child) const
DomItem operator[](QStringView component) const
DomItem rootQmlObject(GoTo option=GoTo::Strict) const
DomItem directParent() const
Path canonicalPath() const
QStringList sortedKeys() const
void addError(ErrorMessage &&msg) const
DomItem containingObject() const
DomItem containingScriptExpression() const
QList< DomItem > getAll(const ErrorHandler &h=nullptr, QList< Path > *visitedRefs=nullptr) const
bool visitPrototypeChain(function_ref< bool(const DomItem &)> visitor, VisitPrototypesOptions options=VisitPrototypesOption::Normal, const ErrorHandler &h=nullptr, QSet< quintptr > *visited=nullptr, QList< Path > *visitedRefs=nullptr) const
DomItem index(index_type) const
DomItem subReferencesItem(const PathEls::PathComponent &c, const QList< Path > &paths) const
bool visitLocalSymbolsNamed(const QString &name, function_ref< bool(const DomItem &)> visitor) const
DomItem subReferenceItem(const PathEls::PathComponent &c, const Path &referencedObject) const
void dumpPtr(const Sink &sink) const
InternalKind internalKind() const
bool isOwningItem() const
DomItem owner() const
The owner of an element, for an qmlObject this is the containing qml file.
ErrorHandler errorHandler() const
DomItem operator[](const Path &path) const
static DomItem empty
QQmlJSScope::ConstPtr nearestSemanticScope() const
QString canonicalFilePath() const
void writeOut(OutWriter &lw) const
Path pathFromOwner() const
DomItem qmlObject(GoTo option=GoTo::Strict, FilterUpOptions options=FilterUpOptions::ReturnOuter) const
Returns the QmlObject that this belongs to.
DomItem key(const QString &name) const
PropertyInfo propertyInfoWithName(const QString &name) const
QSet< QString > keys() const
std::shared_ptr< QQmlJSResourceFileMapper > resourceFileMapper() const
DomItem goToFile(const QString &filePath) const
QDateTime lastDataUpdateAt() const
DomItem(const std::shared_ptr< DomUniverse > &)
static ErrorGroup domErrorGroup
void dump(const DomItem &, const Sink &s, int indent, function_ref< bool(const DomItem &, const PathEls::PathComponent &, const DomItem &)> filter) const override
bool iterateDirectSubpaths(const DomItem &self, DirectVisitor) const override
Path pathFromOwner() const override
Path canonicalPath(const DomItem &self) const override
DomItem containingObject(const DomItem &self) const override
convenience macro creating a new ErrorGroup and registering its groupId as translatable string
Represents a set of tags grouping a set of related error messages.
ErrorMessage warning(const Dumper &message) const
ErrorMessage error(const Dumper &message) const
Represents an error message connected to the dom.
ErrorMessage handle(const ErrorHandler &errorHandler=nullptr)
ErrorMessage & withItem(const DomItem &)
static FieldFilter compareNoCommentsFilter()
FileToLoad(const std::weak_ptr< DomEnvironment > &environment, const QString &canonicalPath, const QString &logicalPath, const std::optional< InMemoryContents > &content)
const LineWriterOptions & options() const
bool iterateDirectSubpaths(const DomItem &self, DirectVisitor v) const override
void writeOut(const DomItem &self, OutWriter &ow, bool compact) const
void writeOut(const DomItem &self, OutWriter &ow, bool compact) const
std::function< bool(const DomItem &, function_ref< bool(index_type, function_ref< DomItem()>)>)> IteratorFunction
List(const Path &pathFromOwner, const LookupFunction &lookup, const Length &length, const IteratorFunction &iterator, const QString &elType)
bool iterateDirectSubpaths(const DomItem &self, DirectVisitor) const override
void dump(const DomItem &, const Sink &s, int indent, function_ref< bool(const DomItem &, const PathEls::PathComponent &, const DomItem &)>) const override
std::function< DomItem(const DomItem &, index_type)> LookupFunction
quintptr id() const override
index_type indexes(const DomItem &self) const override
DomItem index(const DomItem &self, index_type index) const override
std::function< index_type(const DomItem &)> Length
std::function< DomItem(const DomItem &, QString)> LookupFunction
Map(const Path &pathFromOwner, const LookupFunction &lookup, const Keys &keys, const QString &targetType)
std::function< QSet< QString >(const DomItem &)> Keys
bool iterateDirectSubpaths(const DomItem &self, DirectVisitor) const override
QSet< QString > const keys(const DomItem &self) const override
quintptr id() const override
DomItem key(const DomItem &self, const QString &name) const override
MutableDomItem addChild(QmlObject child)
MutableDomItem addPropertyDef(const PropertyDefinition &propertyDef, AddOption option=AddOption::Overwrite)
MutableDomItem addMethod(const MethodInfo &functionDef, AddOption option=AddOption::Overwrite)
void addError(ErrorMessage &&msg)
MutableDomItem path(const Path &p)
MutableDomItem addBinding(Binding binding, AddOption option=AddOption::Overwrite)
A DomItem that owns other DomItems and is managed through a shared pointer.
QDateTime createdAt() const
virtual bool iterateSubOwners(const DomItem &self, function_ref< bool(const DomItem &owner)> visitor)
virtual int revision() const
DomItem containingObject(const DomItem &self) const override
bool iterateErrors(const DomItem &self, function_ref< bool(const DomItem &source, const ErrorMessage &msg)> visitor, const Path &inPath=Path())
virtual void addError(const DomItem &self, ErrorMessage &&msg)
QDateTime frozenAt() const
void addErrorLocal(ErrorMessage &&msg)
virtual QDateTime lastDataUpdateAt() const
void clearErrors(const ErrorGroups &groups=ErrorGroups({}))
OwningItem(int derivedFrom, const QDateTime &lastDataUpdateAt)
bool iterateDirectSubpaths(const DomItem &self, DirectVisitor) const override
virtual bool frozen() const
virtual void refreshedDataAt(QDateTime tNew)
OwningItem(int derivedFrom=0)
OwningItem(const OwningItem &o)
Path operator[](difference_type n) const
Represents an immutable JsonPath like path in the Qml code model (from a DomItem to another DomItem).
Path dropTail(int n=1) const
Source split() const
Splits the path at the last field or current component, or right after a root anchor.
PathIterator begin() const
PathEls::Kind Kind
Kind headKind() const
Path withPath(const Path &toAdd) const
Returns a copy of this with toAdd appended to it.
std::optional< FieldName > headField() const
std::optional< PathRoot > headRoot() const
std::optional< PathCurrent > headCurrent() const
MutableDomItem addBinding(MutableDomItem &self, const Binding &binding, AddOption option)
MutableDomItem addChild(MutableDomItem &self, const QmlObject &child)
MutableDomItem addPropertyDef(MutableDomItem &self, const PropertyDefinition &propertyDef, AddOption option)
MutableDomItem addMethod(MutableDomItem &self, const MethodInfo &functionDef, AddOption option)
QList< std::pair< SourceLocation, DomItem > > Attributes
static bool addForPath(const DomItem &el, const Path &canonicalPath, const RefCacheEntry &entry, AddOption addOption=AddOption::KeepExisting)
static RefCacheEntry forPath(const DomItem &el, const Path &canonicalPath)
QList< QString > fields(const DomItem &self) const override
quintptr id() const override
static constexpr DomType kindValue
DomItem index(const DomItem &, index_type) const override
DomItem get(const DomItem &self, const ErrorHandler &h=nullptr, QList< Path > *visitedRefs=nullptr) const
DomItem field(const DomItem &self, FieldName name) const override
QList< DomItem > getAll(const DomItem &self, const ErrorHandler &h=nullptr, QList< Path > *visitedRefs=nullptr) const
bool iterateDirectSubpaths(const DomItem &self, DirectVisitor) const override
Reference(const Path &referredObject=Path(), const Path &pathFromOwner=Path(), const SourceLocation &loc=SourceLocation())
DomItem key(const DomItem &, const QString &) const override
Use this to contain any script element.
ScriptElement::PointerType< ScriptElement > base() const
Returns a pointer to the virtual base for virtual method calls.
Provides entities to maintain mappings between elements and their location in a file.
QMLDOM_EXPORT bool domTypeIsContainer(DomType k)
static QMap< QString, LookupType > stringToLookupTypeMap()
constexpr bool domTypeIsOwningItem(DomType)
static std::optional< LookupType > lookupTypeFromString(const QString &expectedType)
static bool visitForLookupType(const DomItem &el, LookupType lookupType, function_ref< bool(const DomItem &)> visitor)
static DomItem rootFromContext(const DomItem &root, PathRoot contextId)
QMLDOM_EXPORT QMap< DomKind, QString > domKindToStringMap()
std::shared_ptr< ExternalOwningItem > getFileItemOwner(const DomItem &fileItem)
static bool visitQualifiedNameLookup(const DomItem &newIt, const QStringList &subpath, function_ref< bool(const DomItem &)> visitor, LookupType lookupType, const ErrorHandler &errorHandler, QList< Path > *visitedRefs)
bool operator!=(const DomItem &o1, const DomItem &o2)
QMLDOM_EXPORT bool domTypeIsExternalItem(DomType k)
QMLDOM_EXPORT QMap< DomType, QString > domTypeToStringMap()
QMLDOM_EXPORT bool domTypeIsScope(DomType k)
static LookupOptions resolveLookupOptions(const PathCurrent &current, const DomItem &it)
QMLDOM_EXPORT QString domTypeToString(DomType k)
QMLDOM_EXPORT QString domKindToString(DomKind k)
bool operator!=(const Path &lhs, const Path &rhs)
std::function< void(const ErrorMessage &)> ErrorHandler
QMLDOM_EXPORT bool domTypeIsTopItem(DomType k)
QMLDOM_EXPORT void defaultErrorHandler(const ErrorMessage &)
Calls the default error handler (by default errorToQDebug).
static bool visitPrototypeIndex(QList< DomItem > &toDo, const DomItem &current, const DomItem &derivedFromPrototype, const ErrorHandler &h, QList< Path > *visitedRefs, VisitPrototypesOptions options, const DomItem &prototype)
bool operator==(const Path &lhs, const Path &rhs)
static DomItem resolveReference(const DomItem &it, const Path &refRef, QList< Path > *visitedRefs, const ErrorHandler &errorHandler, const ErrorGroups &errorGroup)
Combined button and popup list for selecting options.
QT_BEGIN_NAMESPACE Q_STATIC_LOGGING_CATEGORY(lcSynthesizedIterableAccess, "qt.iterable.synthesized", QtWarningMsg)
#define NewErrorGroup(name)
A common base class for all the script elements.
void setSemanticScope(const QQmlJSScope::ConstPtr &scope)
QQmlJSScope::ConstPtr semanticScope()