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
qqmldompath.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
5#include <QtCore/QDebug>
6#include <QtCore/QTextStream>
7#include <QtCore/QChar>
8
9#include <algorithm>
10#include <cstdint>
11
12QT_BEGIN_NAMESPACE
13namespace QQmlJS {
14namespace Dom {
15class ErrorMessage;
16
17namespace PathEls {
18
19/*!
20\internal
21\class QQmlJS::Dom::Path
22
23\brief Represents an immutable JsonPath like path in the Qml code model (from a DomItem to another
24 DomItem)
25
26
27\section1 Implementation Details
28
29A Path is a pointer to the node holding its last component, plus the path length.
30Each node (\c PathEls::PathNode) holds one \c PathComponent and a pointer to
31the node of the component before it:
32
33\badcode
34
35 __[.e] a.e (node e, length 2)
36 /
37 [$root] <- [.a] <- [.b] <- [.c] $root.a.b.c: (node c, length 4)
38 ^
39 \___ [.d] $root.a.d: (node d, length 3)
40\endcode
41
42Nodes are immutable and reference counted.
43
44The path consists of the \c m_length nodes ending in \c m_lastNode. Ancestors
45beyond that are not part of the path, which makes \c dropFront() O(1).
46\c dropTail(n) and \c mid() walk up from the tail, which is O(n) in the
47number of dropped components. That's often cheap, as they mostly drop the
48last one or two components.
49
50As the links point backwards, accessing the front of a path is O(length).
51Operations that traverse the components in order therefore first collect
52the nodes into an array.
53
54Each \c PathComponent owns the data it stores, there are no references to outside
55data strutures.
56
57\section1 Usage
58
59It can be created with the path static functions or by modifying an existing
60path. To parse a Path from its textual form, use \c parsePath() from
61\c qqmldompathparser_p.h.
62\code
63Path imports = Path::fromRoot(PathRoot::Env)
64 .withField(Fields::qmlFilesByPath)
65 .withKey(QStringLiteral("/path/to/file"))
66 .withField(Fields::imports);
67Path currentComponentImports = Path::fromCurrent(PathCurrent::Component)
68 .withField(Fields::imports);
69\endcode
70
71This is a way to refer to elements in the Dom models that is not dependent from the source location,
72and thus can also be used in visual tools.
73A Path is quite stable toward reallocations or changes in the Dom model, and accessing it is safe
74even when "dangling", thus it is a good long term reference to an element in the Dom model.
75
76Path objects are a value type that have a shared pointer to extra data if needed, thus one should
77use them as value objects.
78The implementation has still optimization potential, but the behavior for the user should be already
79the final one.
80
81Path is both a range, and a single element (a bit like strings and characters in python).
82
83The root contexts are:
84\list
85\li \l{$modules} All the known modules (even not imported), this is a global, rename independent
86 reference
87\li \l{$cpp} The Cpp names (namespaces, and Cpp types) visible in the current component
88\li \l{$libs} The plugins/libraries and their contents
89\li \l{$top} A top level entry in the DOM model, either $env or $universe (stepping in the universe
90 one looses the reference to its environment)
91\li \l{$env} The environment containing the currently available modules, i.e. the top level entry in
92 the DOM model
93\li \l{$universe} The dom unverse used by ths environment, and potentially shared with others that
94 contains all the known parse entries, and also the latest, potentially invalid entries
95\endlist
96
97The current contexts are:
98\list
99\li \l{@obj} The current object (if in a map or list goes up until it is in the current object) .
100\li \l{@component} The root object of the current component.
101\li \l{@module} The current module instantiation.
102\li \l{@ids} The ids in the current component.
103\li \l{@types} All the types in the current component (reachable through imports, respecting
104 renames)
105\li \l{@lookupStrict} The strict lookup inside the current object: localJS, ids, properties, proto
106 properties, component, its properties, global context, oterwise error
107\li \l{@lookupDynamic} The default lookup inside the current object: localJS, ids, properties, proto
108 properties, component, its properties, global context, ..
109\li \l{@lookup} Either lookupStrict or lookupDynamic depending on the current component and context.
110\endlist
111 */
112
113void Base::dump(const Sink &sink, const QString &name, bool hasSquareBrackets) const {
114 if (hasSquareBrackets)
115 sink(u"[");
116 sink(name);
117 if (hasSquareBrackets)
118 sink(u"]");
119}
120
122{
123 int k1 = static_cast<int>(p1.kind());
124 int k2 = static_cast<int>(p2.kind());
125 if (k1 < k2)
126 return -1;
127 if (k1 > k2)
128 return 1;
129 switch (p1.kind()) {
130 case Kind::Empty:
131 return 0;
132 case Kind::Field: {
133 const auto a = std::get<Field>(p1.m_data).fieldName;
134 const auto b = std::get<Field>(p2.m_data).fieldName;
135 if (a == b)
136 return 0;
137 return size_t(a) < size_t(b) ? -1 : 1;
138 }
139 case Kind::Index:
140 if (std::get<Index>(p1.m_data).indexValue < std::get<Index>(p2.m_data).indexValue)
141 return -1;
142 if (std::get<Index>(p1.m_data).indexValue > std::get<Index>(p2.m_data).indexValue)
143 return 1;
144 return 0;
145 case Kind::Key:
146 return std::get<Key>(p1.m_data).keyValue.compare(std::get<Key>(p2.m_data).keyValue);
147 case Kind::Root:
148 {
149 PathRoot k1 = std::get<Root>(p1.m_data).contextKind;
150 PathRoot k2 = std::get<Root>(p2.m_data).contextKind;
151 if (k1 == PathRoot::Env || k1 == PathRoot::Universe)
152 k1 = PathRoot::Top;
153 if (k2 == PathRoot::Env || k2 == PathRoot::Universe)
154 k2 = PathRoot::Top;
155 return int(k1) - int(k2);
156 }
157 case Kind::Current:
158 return int(std::get<Current>(p1.m_data).contextKind)
159 - int(std::get<Current>(p2.m_data).contextKind);
160 }
161 Q_ASSERT(false && "unexpected PathComponent in PathComponent::cmp");
162 return 0;
163}
164
165size_t PathComponent::hash(size_t seed) const
166{
167 QtPrivate::QHashCombineWithSeed combine(seed);
168 const size_t kindHash = combine(seed, int(kind()));
169 switch (kind()) {
170 case Kind::Empty:
171 return kindHash;
172 case Kind::Field:
173 return combine(kindHash, int(std::get<Field>(m_data).fieldName));
174 case Kind::Index:
175 return combine(kindHash, std::get<Index>(m_data).indexValue);
176 case Kind::Key:
177 return combine(kindHash, std::get<Key>(m_data).keyValue);
178 case Kind::Root: {
179 // Mirror cmp(), which treats Env and Universe like Top.
180 PathRoot r = std::get<Root>(m_data).contextKind;
181 if (r == PathRoot::Env || r == PathRoot::Universe)
182 r = PathRoot::Top;
183 return combine(kindHash, int(r));
184 }
185 case Kind::Current:
186 return combine(kindHash, int(std::get<Current>(m_data).contextKind));
187 }
188 Q_UNREACHABLE_RETURN(kindHash);
189}
190
191} // namespace PathEls
192
193namespace PathEls {
194
196{
197 // Release the chain of ancestors iteratively, to avoid recursive destruction
198 // blowing up stack space
199 const PathNode *node = parent.take();
200 while (node && !node->ref.deref()) {
201 const PathNode *next = const_cast<PathNode *>(node)->parent.take();
202 delete node;
203 node = next;
204 }
205}
206
207} // namespace PathEls
208
209/*!
210\internal
211\brief Returns the nodes of this path, front to back.
212*/
213Path::NodeArray Path::nodes() const
214{
215 NodeArray result(m_length);
216 const Node *node = m_lastNode.data();
217 for (qsizetype i = m_length; i > 0; node = node->parent.data())
218 result[--i] = node;
219 return result;
220}
221
222/*!
223\internal
224\brief Returns the \a i th component, in O(length - i).
225*/
226const PathEls::PathComponent &Path::component(int i) const
227{
228 static const Component emptyComponent;
229 if (i < 0)
230 i += m_length;
231 if (i >= m_length || i < 0) {
232 Q_ASSERT(false && "index out of bounds");
233 return emptyComponent;
234 }
235 const Node *node = m_lastNode.data();
236 for (int toSkip = m_length - 1 - i; toSkip > 0; --toSkip)
237 node = node->parent.data();
238 return node->component;
239}
240
241Path Path::operator[](int i) const
242{
243 return mid(i,1);
244}
245
246QQmlJS::Dom::Path::operator bool() const
247{
248 return length() != 0;
249}
250
252{
253 return PathIterator{*this};
254}
255
257{
258 return {};
259}
260
261std::optional<PathRoot> Path::headRoot() const
262{
263 auto &comp = component(0);
264 if (PathEls::Root const *r = comp.asRoot())
265 return r->contextKind;
266 return std::nullopt;
267}
268
269std::optional<PathCurrent> Path::headCurrent() const
270{
271 auto &comp = component(0);
272 if (PathEls::Current const *c = comp.asCurrent())
273 return c->contextKind;
274 return std::nullopt;
275}
276
277std::optional<FieldName> Path::headField() const
278{
279 auto &comp = component(0);
280 if (const PathEls::Field *f = comp.asField())
281 return f->fieldName;
282 return std::nullopt;
283}
284
286{
287 if (m_length == 0)
288 return Path::Kind::Empty;
289 return component(0).kind();
290}
291
293{
294 return component(0).name();
295}
296
298{
299 auto &comp = component(0);
300 if (PathEls::Index const *i = comp.asIndex())
301 return i->indexValue;
302 return std::nullopt;
303}
304
305Path Path::head() const
306{
307 return mid(0,1);
308}
309
310Path Path::last() const
311{
312 return mid(m_length-1, 1);
313}
314
315/*!
316\internal
317\brief Splits the path at the last field or current component, or right after a
318root anchor.
319
320Field and Current introduce a new logical "starting point" inside the path,
321so split puts everything before them into \c pathToSource and the component
322itself (plus any tail) into \c pathFromSource. A Root, in contrast, is an
323anchor: \c pathToSource includes the Root and \c pathFromSource is what
324follows it. If neither is present, the entire path is \c pathFromSource.
325*/
327{
328 const NodeArray nodes = this->nodes();
329 int i = length();
330 while (i>0) {
331 const PathEls::PathComponent &c = nodes[--i]->component;
332 if (c.kind() == Kind::Field || c.kind() == Kind::Current) {
333 return Source{mid(0, i), mid(i)};
334 }
335 if (c.kind() == Kind::Root) {
336 return Source{mid(0, i + 1), mid(i + 1)};
337 }
338 }
339 return Source{Path(), *this};
340}
341
342
344{
345 return Path().withComponent(std::move(c));
346}
347
349Path Path::fromIndex(index_type i) { return fromComponent(PathEls::Index(i)); }
350Path Path::fromField(FieldName name) { return fromComponent(name); }
351Path Path::fromKey(const QString &s) { return fromComponent(PathEls::Key(s)); }
352Path Path::fromKey(QStringView s) { return fromKey(s.toString()); }
354
356{
357 Q_ASSERT(m_length < std::numeric_limits<quint16>::max());
358 return Path(Node::Ptr(new Node(std::move(c), m_lastNode)), m_length + 1);
359}
360
362Path Path::withField(FieldName name) const { return withComponent(name); }
363Path Path::withKey(const QString &name) const { return withComponent(PathEls::Key(name)); }
364Path Path::withKey(QStringView name) const { return withKey(name.toString()); }
365Path Path::withIndex(index_type i) const { return withComponent(PathEls::Index(i)); }
367
368/*!
369\internal
370\brief Returns a copy of this with \c toAdd appended to it.
371
372This allocates one node per component of \a toAdd. If this path is empty,
373\a toAdd is returned as is.
374*/
375Path Path::withPath(const Path &toAdd) const
376{
377 if (m_length == 0)
378 return toAdd;
379 Path result = *this;
380 for (const Node *node : toAdd.nodes())
381 result = result.withComponent(node->component);
382 return result;
383}
384
385/*!
386\internal
387\brief Compares \a p1 and \a p2 lexicographically.
388*/
389int Path::cmp(const Path &p1, const Path &p2)
390{
391 if (p1.m_lastNode == p2.m_lastNode && p1.m_length == p2.m_length)
392 return 0;
393 const Node *n1 = p1.m_lastNode.data();
394 const Node *n2 = p2.m_lastNode.data();
395 // Lexicographic order only depends on the first min(length) components.
396 for (int l = p1.m_length; l > p2.m_length; --l)
397 n1 = n1->parent.data();
398 for (int l = p2.m_length; l > p1.m_length; --l)
399 n2 = n2->parent.data();
400 // Walk towards the front; the last mismatch seen is the first one in path order.
401 // Shared nodes are equal by pointer, which ends the walk early.
402 int result = 0;
403 for (int l = qMin(p1.m_length, p2.m_length); l > 0 && n1 != n2; --l) {
404 if (const int c = Component::cmp(n1->component, n2->component))
405 result = c;
406 n1 = n1->parent.data();
407 n2 = n2->parent.data();
408 }
409 if (result != 0)
410 return result;
411 return p1.m_length - p2.m_length;
412}
413
414void Path::dump(const Sink &sink) const
415{
416 const NodeArray nodes = this->nodes();
417 bool first = true;
418 for (const Node *node : nodes) {
419 const Component &c = node->component;
420 if (!c.hasSquareBrackets()) {
421 if (!first || (c.kind() != Kind::Root && c.kind() != Kind::Current))
422 sink(u".");
423 }
424 c.dump(sink);
425 first = false;
426 }
427}
428
430{
431 QString res;
432 QTextStream stream(&res);
433 dump([&stream](QStringView str){ stream << str; });
434 stream.flush();
435 return res;
436}
437
438Path Path::dropFront(int n) const
439{
440 if (m_length > n && n >= 0)
441 return Path(m_lastNode, m_length - n);
442 return Path();
443}
444
445Path Path::dropTail(int n) const
446{
447 if (m_length > n && n >= 0) {
448 const Node *node = m_lastNode.data();
449 for (int i = 0; i < n; ++i)
450 node = node->parent.data();
451 return Path(Node::Ptr(node), m_length - n);
452 }
453 return Path();
454}
455
456Path Path::mid(int offset, int length) const
457{
458 length = qMin(m_length - offset, length);
459 if (offset < 0 || offset >= m_length || length <= 0 || length > m_length)
460 return Path();
461 return dropTail(m_length - offset - length).dropFront(offset);
462}
463
464Path Path::mid(int offset) const
465{
466 return mid(offset, m_length - offset);
467}
468
469size_t qHash(const Path &path, size_t seed)
470{
471 QtPrivate::QHashCombineWithSeed combine(seed);
472 size_t hash = combine(seed, path.length());
473 const Path::Node *node = path.m_lastNode.data();
474 for (int i = path.length(); i > 0; --i, node = node->parent.data())
475 hash = combine(hash, node->component.hash(seed));
476 return hash;
477}
478
479} // end namespace Dom
480} // end namespace QQmlJS
481QT_END_NAMESPACE
Represents an error message connected to the dom.
void dump(const Sink &sink, const QString &name, bool hasSquareBrackets) const
static int cmp(const PathComponent &p1, const PathComponent &p2)
size_t hash(size_t seed) const
const Current * asCurrent() const
PathIterator(const Path &path)
Represents an immutable JsonPath like path in the Qml code model (from a DomItem to another DomItem).
std::optional< index_type > headIndex() const
Path dropTail(int n=1) const
Path withEmpty() const
static Path fromComponent(Component c)
Path withIndex(index_type i) const
static int cmp(const Path &p1, const Path &p2)
Compares p1 and p2 lexicographically.
static Path fromField(FieldName name)
PathSentinel end() const
Path withKey(QStringView name) const
QString headName() 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
static Path fromRoot(PathRoot r)
Path operator[](int i) const
Path withField(FieldName name) const
Path withKey(const QString &name) const
Path head() const
Path mid(int offset, int length) const
Path withCurrent(PathCurrent s) const
void dump(const Sink &sink) const
Path last() const
Kind headKind() const
Path mid(int offset) const
QString toString() 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
Path dropFront(int n=1) const
Path withComponent(PathEls::PathComponent c) const
PathEls::PathComponent Component
static Path fromCurrent(PathCurrent c)
std::optional< PathCurrent > headCurrent() const
QMLDOM_EXPORT size_t qHash(const Path &, size_t seed=0)