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
tree.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
3
4#include "tree.h"
5
6#include "anchorid.h"
7#include "classnode.h"
9#include "config.h"
10#include "doc.h"
11#include "enumnode.h"
12#include "functionnode.h"
13#include "htmlgenerator.h"
16#include "location.h"
17#include "node.h"
18#include "qdocdatabase.h"
20#include "text.h"
21#include "typedefnode.h"
22#include "utilities.h"
23#include "textutils.h"
24
25#include <utility>
26
28
29using namespace Qt::StringLiterals;
30
31/*!
32 \class Tree
33
34 This class constructs and maintains a tree of instances of
35 the subclasses of Node.
36
37 This class is now private. Only class QDocDatabase has access.
38 Please don't change this. If you must access class Tree, do it
39 though the pointer to the singleton QDocDatabase.
40
41 Tree is being converted to a forest. A static member provides a
42 map of Tree *values with the module names as the keys. There is
43 one Tree in the map for each index file read, and there is one
44 tree that is not in the map for the module whose documentation
45 is being generated.
46 */
47
48/*!
49 \class TargetRec
50 \brief A record of a linkable target within the documentation.
51*/
52
53/*!
54 \enum TargetRec::TargetType
55
56 A type of a linkable target record.
57
58 \value Unknown
59 Unknown/target not set.
60 \value Target
61 A location marked with a \\target command.
62 \value Keyword
63 A location marked with a \\keyword command.
64 \value Contents
65 A table of contents item (section title).
66 \value ContentsKeyword
67 A \\keyword tied to a section title.
68*/
69
70/*!
71 Constructs a Tree. \a qdb is the pointer to the singleton
72 qdoc database that is constructing the tree. This might not
73 be necessary, and it might be removed later.
74
75 \a camelCaseModuleName is the project name for this tree
76 as it appears in the qdocconf file.
77 */
78Tree::Tree(const QString &camelCaseModuleName, QDocDatabase *qdb)
79 : m_camelCaseModuleName(camelCaseModuleName),
80 m_physicalModuleName(camelCaseModuleName.toLower()),
81 m_qdb(qdb),
82 m_root(nullptr, QString())
83{
84 m_root.setPhysicalModuleName(m_physicalModuleName);
85 m_root.setTree(this);
86}
87
88/*!
89 Destroys the Tree.
90
91 There are two maps of targets, keywords, and contents.
92 One map is indexed by ref, the other by title. Both maps
93 use the same set of TargetRec objects as the values,
94 so we only need to delete the values from one of them.
95
96 The Node instances themselves are destroyed by the root
97 node's (\c m_root) destructor.
98 */
99Tree::~Tree()
100{
101 qDeleteAll(m_nodesByTargetRef);
102 m_nodesByTargetRef.clear();
103 m_nodesByTargetTitle.clear();
104}
105
106/* API members */
107
108/*!
109 Calls findClassNode() first with \a path and \a start. If
110 it finds a node, the node is returned. If not, it calls
111 findNamespaceNode() with the same parameters. The result
112 is returned.
113 */
114Node *Tree::findNodeForInclude(const QStringList &path) const
115{
116 Node *n = findClassNode(path);
117 if (n == nullptr)
118 n = findNamespaceNode(path);
119 return n;
120}
121
122/*!
123 This function searches this tree for an Aggregate node with
124 the specified \a name. It returns the pointer to that node
125 or nullptr.
126
127 We might need to split the name on '::' but we assume the
128 name is a single word at the moment.
129 */
130Aggregate *Tree::findAggregate(const QString &name)
131{
132 QStringList path = name.split(QLatin1String("::"));
133 return static_cast<Aggregate *>(findNodeRecursive(path, 0, const_cast<NamespaceNode *>(root()),
134 &Node::isFirstClassAggregate));
135}
136
137/*!
138 Find the C++ class node named \a path. Begin the search at the
139 \a start node. If the \a start node is 0, begin the search
140 at the root of the tree. Only a C++ class node named \a path is
141 acceptible. If one is not found, 0 is returned.
142 */
143ClassNode *Tree::findClassNode(const QStringList &path, const Node *start) const
144{
145 if (start == nullptr)
146 start = const_cast<NamespaceNode *>(root());
147 return static_cast<ClassNode *>(findNodeRecursive(path, 0, start, &Node::isClassNode));
148}
149
150/*!
151 Find the Namespace node named \a path. Begin the search at
152 the root of the tree. Only a Namespace node named \a path
153 is acceptible. If one is not found, 0 is returned.
154 */
155NamespaceNode *Tree::findNamespaceNode(const QStringList &path) const
156{
157 Node *start = const_cast<NamespaceNode *>(root());
158 return static_cast<NamespaceNode *>(findNodeRecursive(path, 0, start, &Node::isNamespace));
159}
160
161/*!
162 This function searches for the node specified by \a path.
163 The matching node can be one of several different types
164 including a C++ class, a C++ namespace, or a C++ header
165 file.
166
167 I'm not sure if it can be a QML type, but if that is a
168 possibility, the code can easily accommodate it.
169
170 If a matching node is found, a pointer to it is returned.
171 Otherwise 0 is returned.
172 */
173Aggregate *Tree::findRelatesNode(const QStringList &path)
174{
175 Node *n = findNodeRecursive(path, 0, root(), &Node::isRelatableType);
176 return (((n != nullptr) && n->isAggregate()) ? static_cast<Aggregate *>(n) : nullptr);
177}
178
179/*!
180 Records that \a node is related to the aggregate named \a target,
181 which is documented in a different module.
182
183 In the primary tree, the \c relates command of \a node lists
184 \a target as an additional target that comes from an index file.
185 The relationship is written to the index file of this module.
186
187 In a tree read from an index file, the relationship is read from
188 the index file. If \a target is found in the primary tree, its
189 documentation links to \a node.
190
191 \sa externalRelates(), QDocDatabase::resolveProxies()
192 */
193void Tree::addExternalRelates(Node *node, const QString &target)
194{
195 if (!m_externalRelates.contains(node, target))
196 m_externalRelates.insert(node, target);
197}
198
199/*! \fn const QMultiHash<Node *, QString> &Tree::externalRelates() const
200 Returns the nodes in this tree that are related to an aggregate
201 in a different module, mapped to the name of that aggregate.
202
203 \sa addExternalRelates()
204 */
205
206/*!
207 Inserts function name \a funcName and function role \a funcRole into
208 the property function map for the specified \a property.
209 */
210void Tree::addPropertyFunction(PropertyNode *property, const QString &funcName,
211 PropertyNode::FunctionRole funcRole)
212{
213 m_unresolvedPropertyMap[property].insert(funcRole, funcName);
214}
215
216/*!
217 This function resolves C++ inheritance and reimplementation
218 settings for each C++ class node found in the tree beginning
219 at \a n. It also calls itself recursively for each C++ class
220 node or namespace node it encounters.
221
222 This function does not resolve QML inheritance.
223 */
224void Tree::resolveBaseClasses(Aggregate *n)
225{
226 for (auto it = n->constBegin(); it != n->constEnd(); ++it) {
227 if ((*it)->isClassNode()) {
228 auto *cn = static_cast<ClassNode *>(*it);
229 QList<RelatedClass> &bases = cn->baseClasses_mutable();
230 for (auto &base : bases) {
231 if (base.m_node == nullptr) {
232 Node *n = m_qdb->findClassNode(base.m_path);
233 /*
234 If the node for the base class was not found,
235 the reason might be that the subclass is in a
236 namespace and the base class is in the same
237 namespace, but the base class name was not
238 qualified with the namespace name. That is the
239 case most of the time. Then restart the search
240 at the parent of the subclass node (the namespace
241 node) using the unqualified base class name.
242 */
243 if (n == nullptr) {
244 Aggregate *parent = cn->parent();
245 if (parent != nullptr)
246 // Exclude the root namespace
247 if (parent->isNamespace() && !parent->name().isEmpty())
248 n = findClassNode(base.m_path, parent);
249 }
250 if (n != nullptr) {
251 auto *bcn = static_cast<ClassNode *>(n);
252 base.m_node = bcn;
253 bcn->addDerivedClass(base.m_access, cn);
254 }
255 }
256 }
257 resolveBaseClasses(cn);
258 } else if ((*it)->isNamespace()) {
259 resolveBaseClasses(static_cast<NamespaceNode *>(*it));
260 }
261 }
262}
263
264/*!
265 */
266void Tree::resolvePropertyOverriddenFromPtrs(Aggregate *n)
267{
268 for (auto node = n->constBegin(); node != n->constEnd(); ++node) {
269 if ((*node)->isClassNode()) {
270 auto *cn = static_cast<ClassNode *>(*node);
271 for (auto property = cn->constBegin(); property != cn->constEnd(); ++property) {
272 if ((*property)->isProperty())
273 cn->resolvePropertyOverriddenFromPtrs(static_cast<PropertyNode *>(*property));
274 }
275 resolvePropertyOverriddenFromPtrs(cn);
276 } else if ((*node)->isNamespace()) {
277 resolvePropertyOverriddenFromPtrs(static_cast<NamespaceNode *>(*node));
278 }
279 }
280}
281
282/*!
283 Resolves access functions associated with each PropertyNode stored
284 in \c m_unresolvedPropertyMap, and adds them into the property node.
285 This allows the property node to list the access functions when
286 generating their documentation.
287 */
289{
290 for (auto propEntry = m_unresolvedPropertyMap.constBegin();
291 propEntry != m_unresolvedPropertyMap.constEnd(); ++propEntry) {
292 PropertyNode *property = propEntry.key();
293 Aggregate *parent = property->parent();
294 QString getterName = (*propEntry)[PropertyNode::FunctionRole::Getter];
295 QString setterName = (*propEntry)[PropertyNode::FunctionRole::Setter];
296 QString resetterName = (*propEntry)[PropertyNode::FunctionRole::Resetter];
297 QString notifierName = (*propEntry)[PropertyNode::FunctionRole::Notifier];
298 QString bindableName = (*propEntry)[PropertyNode::FunctionRole::Bindable];
299
300 for (auto it = parent->constBegin(); it != parent->constEnd(); ++it) {
301 if ((*it)->isFunction()) {
302 auto *function = static_cast<FunctionNode *>(*it);
303 if (function->access() == property->access()
304 && (function->status() == property->status() || function->doc().isEmpty())) {
305 if (function->name() == getterName) {
307 } else if (function->name() == setterName) {
309 } else if (function->name() == resetterName) {
311 } else if (function->name() == notifierName) {
313 } else if (function->name() == bindableName) {
315 }
316 }
317 }
318 }
319 }
320
321 for (auto propEntry = m_unresolvedPropertyMap.constBegin();
322 propEntry != m_unresolvedPropertyMap.constEnd(); ++propEntry) {
323 PropertyNode *property = propEntry.key();
324 // redo it to set the property functions
325 if (property->overriddenFrom())
327 }
328
329 m_unresolvedPropertyMap.clear();
330}
331
332/*!
333 Validates that all properties in the documentation tree that require
334 documentation according to the inclusion policy have documentation.
335 Generates warnings for undocumented properties.
336
337 This method recursively traverses the tree starting from \a aggregate,
338 checking each PropertyNode for documentation. Properties without
339 documentation that require it according to the inclusion policy will
340 generate a warning.
341
342 \sa InclusionFilter::requiresDocumentation()
343 */
344void Tree::validatePropertyDocumentation(const Aggregate *aggregate) const
345{
346 const auto &config = Config::instance();
347 const InclusionPolicy policy = config.createInclusionPolicy();
348 validatePropertyDocumentation(aggregate, policy);
349}
350
351/*!
352 \internal
353 \overload
354
355 Private helper that takes \a policy by const reference to avoid
356 recreating it on each recursive call while traversing \a aggregate.
357 */
358void Tree::validatePropertyDocumentation(const Aggregate *aggregate, const InclusionPolicy &policy) const
359{
360 for (auto it = aggregate->constBegin(); it != aggregate->constEnd(); ++it) {
361 Node *node = *it;
362
363 if (node->isProperty() && !node->hasDoc() && !node->isWrapper()) {
364 const NodeContext context = node->createContext();
366 node->location().warning(u"Undocumented property '%1'"_s.arg(node->plainFullName()));
367 }
368
369 if (node->isAggregate())
370 validatePropertyDocumentation(static_cast<Aggregate *>(node), policy);
371 }
372}
373
374/*!
375 For each QML class node that points to a C++ class node,
376 follow its C++ class node pointer and set the C++ class
377 node's QML class node pointer back to the QML class node.
378 */
379void Tree::resolveCppToQmlLinks()
380{
381
382 const NodeList &children = m_root.childNodes();
383 for (auto *child : children) {
384 if (child->isQmlType()) {
385 auto *qcn = static_cast<QmlTypeNode *>(child);
386 auto *cn = const_cast<ClassNode *>(qcn->classNode());
387 if (cn)
388 cn->insertQmlNativeType(qcn);
389 }
390 }
391}
392
393/*!
394 For each \a aggregate, recursively set the \\since version based on
395 \\since information from the associated physical or logical module.
396 That is, C++ and QML types inherit the \\since of their module,
397 unless that command is explicitly used in the type documentation.
398
399 In addition, resolve the since information for individual enum
400 values.
401*/
402void Tree::resolveSince(Aggregate &aggregate)
403{
404 for (auto *child : aggregate.childNodes()) {
405 // Order matters; resolve since-clauses in enum values
406 // first as EnumNode is not an Aggregate
407 if (child->isEnumType())
408 resolveEnumValueSince(static_cast<EnumNode&>(*child));
409 if (!child->isAggregate())
410 continue;
411 if (!child->since().isEmpty())
412 continue;
413
414 if (const auto collectionNode = m_qdb->getModuleNode(child))
415 child->setSince(collectionNode->since());
416
417 resolveSince(static_cast<Aggregate&>(*child));
418 }
419}
420
421/*!
422 Resolve since information for values of enum node \a en.
423
424 Enum values are not derived from Node, but they can have
425 'since' information associated with them. Since-strings
426 for each enum item are initially stored in the Doc
427 instance of EnumNode as SinceTag atoms; parse the doc
428 and store them into each EnumItem.
429*/
430void Tree::resolveEnumValueSince(EnumNode &en)
431{
432 const QStringList enumItems{en.doc().enumItemNames()};
433 const Atom *atom = en.doc().body().firstAtom();
434 if (!atom)
435 return;
436 while ((atom = atom->find(Atom::ListTagLeft))) {
437 if (atom = atom->next(); !atom)
438 break;
439 if (const auto &val = atom->string(); enumItems.contains(val)) {
440 if (atom = atom->next(); atom && atom->next(Atom::SinceTagLeft))
441 en.setSince(val, atom->next()->next()->string());
442 }
443 }
444}
445
446/*!
447 Traverse this Tree and for each ClassNode found, remove
448 from its list of base classes any that are marked private
449 or internal. When a class is removed from a base class
450 list, promote its public pase classes to be base classes
451 of the class where the base class was removed. This is
452 done for documentation purposes. The function is recursive
453 on namespace nodes.
454 */
455void Tree::removePrivateAndInternalBases(NamespaceNode *rootNode)
456{
457 if (rootNode == nullptr)
458 rootNode = root();
459
460 for (auto node = rootNode->constBegin(); node != rootNode->constEnd(); ++node) {
461 if ((*node)->isClassNode())
462 static_cast<ClassNode *>(*node)->removePrivateAndInternalBases();
463 else if ((*node)->isNamespace())
464 removePrivateAndInternalBases(static_cast<NamespaceNode *>(*node));
465 }
466}
467
468/*!
469 */
470ClassList Tree::allBaseClasses(const ClassNode *classNode) const
471{
472 ClassList result;
473 const auto &baseClasses = classNode->baseClasses();
474 for (const auto &relatedClass : baseClasses) {
475 if (relatedClass.m_node != nullptr) {
476 result += relatedClass.m_node;
477 result += allBaseClasses(relatedClass.m_node);
478 }
479 }
480 return result;
481}
482
483/*!
484 Find the node with the specified \a path name that is of
485 the specified \a type and \a subtype. Begin the search at
486 the \a start node. If the \a start node is 0, begin the
487 search at the tree root. \a subtype is not used unless
488 \a type is \c{Page}.
489 */
490Node *Tree::findNodeByNameAndType(const QStringList &path, bool (Node::*isMatch)() const) const
491{
492 return findNodeRecursive(path, 0, root(), isMatch);
493}
494
495/*!
496 Recursive search for a node identified by \a path. Each
497 path element is a name. \a pathIndex specifies the index
498 of the name in \a path to try to match. \a start is the
499 node whose children shoulod be searched for one that has
500 that name. Each time a match is found, increment the
501 \a pathIndex and call this function recursively.
502
503 If the end of the path is reached (i.e. if a matching
504 node is found for each name in the \a path), the \a type
505 must match the type of the last matching node, and if the
506 type is \e{Page}, the \a subtype must match as well.
507
508 If the algorithm is successful, the pointer to the final
509 node is returned. Otherwise 0 is returned.
510 */
511Node *Tree::findNodeRecursive(const QStringList &path, int pathIndex, const Node *start,
512 bool (Node::*isMatch)() const) const
513{
514 if (start == nullptr || path.isEmpty())
515 return nullptr;
516 Node *node = const_cast<Node *>(start);
517 if (!node->isAggregate())
518 return ((pathIndex >= path.size()) ? node : nullptr);
519 auto *current = static_cast<Aggregate *>(node);
520 const NodeList &children = current->childNodes();
521 const QString &name = path.at(pathIndex);
522 for (auto *node : children) {
523 if (node == nullptr)
524 continue;
525 if (node->name() == name) {
526 if (pathIndex + 1 >= path.size()) {
527 if ((node->*(isMatch))())
528 return node;
529 continue;
530 } else { // Search the children of n for the next name in the path.
531 node = findNodeRecursive(path, pathIndex + 1, node, isMatch);
532 if (node != nullptr)
533 return node;
534 }
535 }
536 }
537 return nullptr;
538}
539
540/*!
541 Searches the tree for a node that matches the \a path plus
542 the \a target. The search begins at \a start and moves up
543 the parent chain from there, or, if \a start is 0, the search
544 begins at the root.
545
546 The \a flags can indicate whether to search base classes and/or
547 the enum values in enum types. \a genus further restricts
548 the type of nodes to match, i.e. CPP or QML.
549
550 If a matching node is found, \a ref is set to the HTML fragment
551 identifier to use for the link. On return, the optional
552 \a targetType parameter contains the type of the resolved
553 target; section title (Contents), \\target, \\keyword, or other
554 (Unknown).
555 */
556const Node *Tree::findNodeForTarget(const QStringList &path, const QString &target,
557 const Node *start, int flags, Genus genus,
558 QString &ref, TargetRec::TargetType *targetType) const
559{
560 const Node *node = nullptr;
561
562 // Retrieves and sets ref from target for Node n.
563 // Returns n on valid (or empty) target, or nullptr on an invalid target.
564 auto set_ref_from_target = [this, &ref, &target](const Node *n) -> const Node* {
565 if (!target.isEmpty()) {
566 if (ref = getRef(target, n); ref.isEmpty())
567 return nullptr;
568 }
569 return n;
570 };
571
572 if (genus == Genus::DontCare || genus == Genus::DOC) {
573 if (node = findPageNodeByTitle(path.at(0)); node) {
574 if (node = set_ref_from_target(node); node)
575 return node;
576 }
577 }
578
579 /*
580 For C++ class and QML type contexts, prioritize hierarchical search (including
581 base classes/types) over global target maps. This allows inherited members to
582 take precedence over unrelated global targets such as section titles in other
583 documentation pages. See QTBUG-72107 and QTBUG-141606.
584
585 Documentation authored on a member of a class or QML type, such as a function
586 body or a shared comment, is in the same context as the type's own body, so
587 the member's parent decides.
588 */
589 const Node *scope = (start && !start->isAggregate()) ? start->parent() : start;
590 const bool prioritizeHierarchy = scope &&
591 ((scope->isClassNode() && (genus == Genus::CPP || genus == Genus::DontCare)) ||
592 (scope->isQmlType() && (genus == Genus::QML || genus == Genus::DontCare)));
593
594 const TargetRec *result = nullptr;
595 if (!prioritizeHierarchy) {
596 result = findUnambiguousTarget(path.join(QLatin1String("::")), genus, start);
597 if (result) {
598 ref = result->m_ref;
599 if (node = set_ref_from_target(result->m_node); node) {
600 // Delay returning references to section titles as we
601 // may find a better match below
602 if (result->m_type != TargetRec::Contents) {
603 if (targetType)
604 *targetType = result->m_type;
605 return node;
606 }
607 ref.clear();
608 }
609 }
610 }
611
612 const Node *current = start ? start : root();
613 /*
614 If the path contains one or two double colons ("::"),
615 check if the first two path elements refer to a QML type.
616 If so, path[0] is QML module identifier, and path[1] is
617 the type.
618 */
619 int path_idx = 0;
620 if ((genus == Genus::QML || genus == Genus::DontCare)
621 && path.size() >= 2 && !path[0].isEmpty()) {
622 if (auto *qcn = lookupQmlType(path.sliced(0, 2).join(QLatin1String("::")), start); qcn) {
623 current = qcn;
624 // No further elements in the path, return the type
625 if (path.size() == 2)
626 return set_ref_from_target(qcn);
627 path_idx = 2;
628 }
629 }
630
631 while (current) {
632 if (current->isAggregate()) {
633 if (const Node *match = matchPathAndTarget(
634 path, path_idx, target, current, flags, genus, ref);
635 match != nullptr)
636 return match;
637 }
638 current = current->parent();
639 path_idx = 0;
640 }
641
642 // If we prioritized hierarchy but found nothing, try global targets as fallback
643 if (prioritizeHierarchy) {
644 result = findUnambiguousTarget(path.join(QLatin1String("::")), genus, start);
645 if (result) {
646 ref = result->m_ref;
647 if (node = set_ref_from_target(result->m_node); node) {
648 if (targetType)
649 *targetType = result->m_type;
650 return node;
651 }
652 }
653 }
654
655 if (node && result) {
656 // Fall back to previously found section title
657 ref = result->m_ref;
658 if (targetType)
659 *targetType = result->m_type;
660 }
661 return node;
662}
663
664/*!
665 First, the \a path is used to find a node. The \a path
666 matches some part of the node's fully quallified name.
667 If the \a target is not empty, it must match a target
668 in the matching node. If the matching of the \a path
669 and the \a target (if present) is successful, \a ref
670 is set from the \a target, and the pointer to the
671 matching node is returned. \a idx is the index into the
672 \a path where to begin the matching. The function is
673 recursive with idx being incremented for each recursive
674 call.
675
676 The matching node must be of the correct \a genus, i.e.
677 either QML or C++, but \a genus can be set to \c DontCare.
678 \a flags indicates whether to search base classes and
679 whether to search for an enum value. \a node points to
680 the node where the search should begin, assuming the
681 \a path is a not a fully-qualified name. \a node is
682 most often the root of this Tree.
683 */
684const Node *Tree::matchPathAndTarget(const QStringList &path, int idx, const QString &target,
685 const Node *node, int flags, Genus genus,
686 QString &ref, int duplicates) const
687{
688 /*
689 If the path has been matched, then if there is a target,
690 try to match the target. If there is a target, but you
691 can't match it at the end of the path, give up; return
692 \nullptr.
693 */
694 if (idx == path.size()) {
695 if (!target.isEmpty()) {
696 ref = getRef(target, node);
697 if (ref.isEmpty())
698 return nullptr;
699 }
700 if (node->isFunction() && node->name() == node->parent()->name())
701 node = node->parent();
702
703 // If attached properties are requested, only match attached properties.
704 if (flags & QmlAttachedProperties) {
705 if (node->isAttached())
706 return node;
707 else
708 return nullptr;
709 }
710 // Match regular properties if attached properties are not specified.
711 // Match attached properties if they do not shadow regular properties.
712 if (node->isQmlProperty()) {
713 if (!node->isAttached() || duplicates == 0)
714 return node;
715 else
716 return nullptr;
717 } else
718 return node;
719 }
720
721 QString name = path.at(idx);
722 if (node->isAggregate()) {
723 NodeVector nodes;
724 static_cast<const Aggregate *>(node)->findChildren(name, nodes);
725 for (const auto *child : std::as_const(nodes)) {
726 if (genus != Genus::DontCare && !(hasCommonGenusType(genus, child->genus())))
727 continue;
728 const Node *t = matchPathAndTarget(path, idx + 1, target, child, flags, genus, ref, nodes.count() - 1);
729 if (t && !t->isPrivate() && !t->isInternal())
730 return t;
731 }
732 }
733 if (target.isEmpty() && (flags & SearchEnumValues)) {
734 const auto *enumNode = node->isAggregate() ?
735 findEnumNode(nullptr, node, path, idx) :
736 findEnumNode(node, nullptr, path, idx);
737 if (enumNode)
738 return enumNode;
739 }
740 if (((genus == Genus::CPP) || (genus == Genus::DontCare)) && node->isClassNode()
741 && (flags & SearchBaseClasses)) {
742 const ClassList bases = allBaseClasses(static_cast<const ClassNode *>(node));
743 for (const auto *base : bases) {
744 const Node *t = matchPathAndTarget(path, idx, target, base, flags, genus, ref);
745 if (t && !t->isPrivate() && !t->isInternal())
746 return t;
747 if (target.isEmpty() && (flags & SearchEnumValues)) {
748 if ((t = findEnumNode(base->findChildNode(path.at(idx), genus, flags), base, path, idx)))
749 return t;
750 }
751 }
752 }
753 if (((genus == Genus::QML) || (genus == Genus::DontCare)) && node->isQmlType()
754 && (flags & SearchBaseClasses)) {
755 const QmlTypeNode *qtn = static_cast<const QmlTypeNode *>(node);
756 while (qtn && qtn->qmlBaseNode()) {
757 qtn = qtn->qmlBaseNode();
758 const Node *t = matchPathAndTarget(path, idx, target, qtn, flags, genus, ref);
759 if (t && !t->isPrivate() && !t->isInternal())
760 return t;
761 }
762 }
763 return nullptr;
764}
765
766/*!
767 Searches the tree for a node that matches the \a path. The
768 search begins at \a start but can move up the parent chain
769 recursively if no match is found. The \a flags are used to
770 restrict the search.
771 */
772const Node *Tree::findNode(const QStringList &path, const Node *start, int flags,
773 Genus genus) const
774{
775 const Node *current = start;
776 if (current == nullptr)
777 current = root();
778
779 do {
780 const Node *node = current;
781 int i;
782 int start_idx = 0;
783
784 /*
785 If the path contains one or two double colons ("::"),
786 check first to see if the first two path strings refer
787 to a QML element. If they do, path[0] will be the QML
788 module identifier, and path[1] will be the QML type.
789 If the answer is yes, the reference identifies a QML
790 type node.
791 */
792 if (((genus == Genus::QML) || (genus == Genus::DontCare)) && (path.size() >= 2)
793 && !path[0].isEmpty()) {
794 QmlTypeNode *qcn = lookupQmlType(QString(path[0] + "::" + path[1]), start);
795 if (qcn != nullptr) {
796 node = qcn;
797 if (path.size() == 2)
798 return node;
799 start_idx = 2;
800 }
801 }
802
803 for (i = start_idx; i < path.size(); ++i) {
804 if (node == nullptr || !node->isAggregate())
805 break;
806
807 // Clear the TypesOnly flag until the last path segment, as e.g. namespaces are not
808 // types. We also ignore module nodes as they are not aggregates and thus have no
809 // children.
810 int tmpFlags = (i < path.size() - 1) ? (flags & ~TypesOnly) | IgnoreModules : flags;
811
812 const Node *next = static_cast<const Aggregate *>(node)->findChildNode(path.at(i),
813 genus, tmpFlags);
814 const Node *enumNode = (flags & SearchEnumValues) ?
815 findEnumNode(next, node, path, i) : nullptr;
816
817 if (enumNode)
818 return enumNode;
819
820
821 if (!next && ((genus == Genus::CPP) || (genus == Genus::DontCare))
822 && node->isClassNode() && (flags & SearchBaseClasses)) {
823 const ClassList bases = allBaseClasses(static_cast<const ClassNode *>(node));
824 for (const auto *base : bases) {
825 next = base->findChildNode(path.at(i), genus, tmpFlags);
826 if (flags & SearchEnumValues)
827 if ((enumNode = findEnumNode(next, base, path, i)))
828 return enumNode;
829 if (next)
830 break;
831 }
832 }
833 if (!next && ((genus == Genus::QML) || (genus == Genus::DontCare))
834 && node->isQmlType() && (flags & SearchBaseClasses)) {
835 const QmlTypeNode *qtn = static_cast<const QmlTypeNode *>(node);
836 while (qtn && qtn->qmlBaseNode() && !next) {
837 qtn = qtn->qmlBaseNode();
838 next = qtn->findChildNode(path.at(i), genus, tmpFlags);
839 }
840 }
841 node = next;
842 }
843 if ((node != nullptr) && i == path.size())
844 return node;
845 current = current->parent();
846 } while (current != nullptr);
847
848 return nullptr;
849}
850
851
852/*!
853 \internal
854
855 Helper function to return an enum that matches the \a path at a specified \a offset.
856 If \a node is a valid enum node, the enum name is assumed to be included in the path
857 (i.e, a scoped enum). Otherwise, query the \a aggregate (typically, the class node)
858 for enum node that includes the value at the last position in \a path.
859 */
860const Node *Tree::findEnumNode(const Node *node, const Node *aggregate, const QStringList &path, int offset) const
861{
862 // Scoped enum (path ends in enum_name :: enum_value)
863 if (node && node->isEnumType() && offset == path.size() - 1) {
864 const auto *en = static_cast<const EnumNode*>(node);
865 if (en->hasItem(path.last()))
866 return en;
867 }
868
869 // Standard enum (path ends in class_name :: enum_value)
870 return (!node && aggregate && offset == path.size() - 1) ?
871 static_cast<const Aggregate *>(aggregate)->findEnumNodeForValue(path.last()) :
872 nullptr;
873}
874
875/*!
876 This function searches for a node with a canonical title
877 constructed from \a target. If the node it finds is \a node,
878 it returns the ref from that node. Otherwise it returns an
879 empty string.
880 */
881QString Tree::getRef(const QString &target, const Node *node) const
882{
883 auto it = m_nodesByTargetTitle.constFind(target);
884 if (it != m_nodesByTargetTitle.constEnd()) {
885 do {
886 if (it.value()->m_node == node)
887 return it.value()->m_ref;
888 ++it;
889 } while (it != m_nodesByTargetTitle.constEnd() && it.key() == target);
890 }
891 QString key = TextUtils::asAsciiPrintable(target);
892 it = m_nodesByTargetRef.constFind(key);
893 if (it != m_nodesByTargetRef.constEnd()) {
894 do {
895 if (it.value()->m_node == node)
896 return it.value()->m_ref;
897 ++it;
898 } while (it != m_nodesByTargetRef.constEnd() && it.key() == key);
899 }
900 return QString();
901}
902
903/*!
904 Inserts a new target into the target table. \a name is the
905 key. The target record contains the \a type, a pointer to
906 the \a node, the \a priority. and a canonicalized form of
907 the \a name, which is later used.
908 */
909void Tree::insertTarget(const QString &name, const QString &title, TargetRec::TargetType type,
910 Node *node, int priority)
911{
912 auto *target = new TargetRec(name, type, node, priority);
913 m_nodesByTargetRef.insert(name, target);
914 m_nodesByTargetTitle.insert(title, target);
915}
916
917/*!
918 \internal
919
920 \a root is the root node of the tree to resolve targets for. This function
921 traverses the tree starting from the root node and processes each child
922 node. If the child node is an aggregate node, this function is called
923 recursively on the child node.
924 */
925void Tree::resolveTargets(Aggregate *root)
926{
927 for (auto *child : root->childNodes()) {
928 addToPageNodeByTitleMap(child);
929 populateTocSectionTargetMap(child);
930 addKeywordsToTargetMaps(child);
931 addTargetsToTargetMap(child);
932
933 if (child->isAggregate())
934 resolveTargets(static_cast<Aggregate *>(child));
935 }
936}
937
938static const Atom *nextSection(const Atom *a);
939
940/*!
941 \internal
942
943 Updates the target maps for targets associated with the given \a node.
944 */
945void Tree::addTargetsToTargetMap(Node *node) {
946 if (!node || !node->doc().hasTargets())
947 return;
948
949 QSet<QString> usedRefs;
950 for (const Atom *heading : node->doc().tableOfContents())
951 usedRefs.insert(refForAtom(heading));
952 if (node->isPageNode())
953 usedRefs.insert("details"_L1);
954
955 for (Atom *i : std::as_const(node->doc().targets())) {
956 QString ref = refForAtom(i);
957 const QString title = i->string();
958 if (!ref.isEmpty() && !title.isEmpty()) {
959 const QString rawRef = TextUtils::asAsciiPrintable(title);
960 // A target elsewhere on the page must not reuse a section's id.
961 // A target tied to the following section already shares its anchor.
962 if (i->count() == 1 && usedRefs.contains(rawRef)
963 && (!nextSection(i) || ref != rawRef)) {
964 const QString base = rawRef + "-target"_L1;
965 ref = base;
966 for (int n = 2; usedRefs.contains(ref); ++n)
967 ref = base + '-'_L1 + QString::number(n);
968 i->append(ref);
969 }
970 usedRefs.insert(ref);
971 QString key = TextUtils::asAsciiPrintable(title);
972 auto *target = new TargetRec(std::move(ref), TargetRec::Target, node, 2);
973 m_nodesByTargetRef.insert(key, target);
974 m_nodesByTargetTitle.insert(title, target);
975 }
976 }
977}
978
979/*
980 If atom \a a is immediately followed by a
981 section title (\section1..\section4 command),
982 returns the SectionLeft atom; otherwise nullptr.
983*/
984static const Atom *nextSection(const Atom *a)
985{
986 while (a && a->next(Atom::SectionRight))
987 a = a->next(); // skip closing section atoms
988 return a ? a->next(Atom::SectionLeft) : nullptr;
989}
990
991/*!
992 \internal
993
994 Updates the target maps for keywords associated with the given \a node.
995 */
996void Tree::addKeywordsToTargetMaps(Node *node) {
997 if (!node->doc().hasKeywords())
998 return;
999
1000 for (Atom *i : std::as_const(node->doc().keywords())) {
1001 QString ref = refForAtom(i);
1002 QString title = i->string();
1003 if (!ref.isEmpty() && !title.isEmpty()) {
1004 auto *target = new TargetRec(ref, nextSection(i) ? TargetRec::ContentsKeyword : TargetRec::Keyword, node, 1);
1005 m_nodesByTargetRef.insert(TextUtils::asAsciiPrintable(title), target);
1006 m_nodesByTargetTitle.insert(title, target);
1007 if (!target->isEmpty())
1008 i->append(target->m_ref);
1009 }
1010 }
1011}
1012
1013/*!
1014 \internal
1015
1016 Populates the map of targets for each section in the table of contents for
1017 the given \a node while ensuring that each target has a unique reference.
1018 */
1019void Tree::populateTocSectionTargetMap(Node *node) {
1020 if (!node || !node->doc().hasTableOfContents())
1021 return;
1022
1023 QStack<Atom *> tocLevels;
1024 QSet<QString> anchors;
1025
1026 // Member documentation is rendered on its parent's page.
1027 QString memberRef = node->isPageNode() ? QString() : computeAnchorId(node);
1028 if (node->isSharedCommentNode() && memberRef.isEmpty()) {
1029 const auto *shared = static_cast<const SharedCommentNode *>(node);
1030 if (!shared->collective().isEmpty())
1031 memberRef = computeAnchorId(shared->collective().first());
1032 }
1033
1034 qsizetype index = 0;
1035
1036 for (Atom *atom: std::as_const(node->doc().tableOfContents())) {
1037 while (!tocLevels.isEmpty() && tocLevels.top()->string().toInt() >= atom->string().toInt())
1038 tocLevels.pop();
1039
1040 tocLevels.push(atom);
1041
1042 QString ref = refForAtom(atom);
1043 const QString &title = Text::sectionHeading(atom).toString();
1044 if (ref.isEmpty() || title.isEmpty())
1045 continue;
1046
1047 if (!memberRef.isEmpty() && node->parent() && node->parent()->isAggregate()) {
1048 const auto *page = static_cast<const Aggregate *>(node->parent());
1049 bool collides = false;
1050 for (const Node *sibling : page->childNodes()) {
1051 if (sibling == node)
1052 continue;
1053 for (const Atom *heading : sibling->doc().tableOfContents()) {
1054 if (TextUtils::asAsciiPrintable(Text::sectionHeading(heading).toString()) == ref) {
1055 collides = true;
1056 break;
1057 }
1058 }
1059 if (collides)
1060 break;
1061 }
1062 if (collides)
1063 ref = memberRef + '-'_L1 + ref;
1064 } else if (node->isAggregate()) {
1065 // A class section can otherwise shadow a member's link target.
1066 const auto *aggregate = static_cast<const Aggregate *>(node);
1067 for (const Node *child : aggregate->childNodes()) {
1068 if (computeAnchorId(child) == ref) {
1069 ref += "-section"_L1;
1070 break;
1071 }
1072 }
1073 }
1074
1075 // Legacy HTML reserves these ids for its page details and signal
1076 // summary, independently of the section titles in the source text.
1077 if (ref == "details"_L1 && node->isPageNode()) {
1078 ref += "-section"_L1;
1079 } else if (ref == "signals"_L1 && node->isAggregate()) {
1080 const auto *aggregate = static_cast<const Aggregate *>(node);
1081 for (const Node *child : aggregate->childNodes()) {
1082 if (child->isFunction() && static_cast<const FunctionNode *>(child)->isSignal()) {
1083 ref += "-section"_L1;
1084 break;
1085 }
1086 }
1087 }
1088
1089 if (anchors.contains(ref)) {
1090 QStringList refParts;
1091 for (const auto tocLevel : tocLevels)
1092 refParts << refForAtom(tocLevel);
1093
1094 refParts << QString::number(index);
1095 ref = refParts.join(QLatin1Char('-'));
1096 }
1097
1098 anchors.insert(ref);
1099 if (atom->next(Atom::SectionHeadingLeft) && atom->next()->count() == 1)
1100 atom->next()->append(ref);
1101 ++index;
1102
1103 const QString &key = TextUtils::asAsciiPrintable(title);
1104 auto *target = new TargetRec(ref, TargetRec::Contents, node, 3);
1105 m_nodesByTargetRef.insert(key, target);
1106 m_nodesByTargetTitle.insert(title, target);
1107 }
1108}
1109
1110/*!
1111 \internal
1112
1113 Checks if the \a node's title is registered in the page nodes by title map.
1114 If not, it stores the page node in the map.
1115 */
1116void Tree::addToPageNodeByTitleMap(Node *node) {
1117 if (!node || !node->isTextPageNode())
1118 return;
1119
1120 auto *pageNode = static_cast<PageNode *>(node);
1121 QString key = pageNode->title();
1122 if (key.isEmpty())
1123 return;
1124
1125 if (key.contains(QChar(' ')))
1126 key = TextUtils::asAsciiPrintable(key);
1127 const QList<PageNode *> nodes = m_pageNodesByTitle.values(key);
1128
1129 bool alreadyThere = std::any_of(nodes.cbegin(), nodes.cend(), [&](const auto &knownNode) {
1130 return knownNode->isExternalPage() && knownNode->name() == pageNode->name();
1131 });
1132
1133 if (!alreadyThere)
1134 m_pageNodesByTitle.insert(key, pageNode);
1135}
1136
1137/*!
1138 Finds a target anchor that matches \a target and \a genus. Returns the
1139 associated TargetRec instance, or nullptr if no match is found.
1140
1141 Searches target titles first. If no matching title is found, searches
1142 target references.
1143
1144 For each search, selects a matching target in the following order:
1145 \list 1
1146 \li Keyword targets.
1147 \li Targets whose node is \a start, its parent, or one of its children.
1148 \li Other targets.
1149 \endlist
1150
1151 Within each category, prefers targets with lower numeric priority values.
1152 If multiple targets have the same rank, returns the first one encountered.
1153 */
1154const TargetRec *Tree::findUnambiguousTarget(const QString &target, Genus genus, const Node *start) const
1155{
1156 // Nodes that are the same, children or parents are closely related.
1157 auto closelyRelated = [](const Node *n1, const Node *n2) {
1158 if (!n1 || !n2)
1159 return false;
1160 return (n1 == n2) || (n1->parent() == n2) || (n1 == n2->parent());
1161 };
1162
1163 enum class TargetCategory { Keyword, Nearby, Other };
1164
1165 auto rank = [&](const TargetRec *candidate) {
1166 auto category = TargetCategory::Other;
1167 if (candidate->m_type == TargetRec::Keyword) {
1168 category = TargetCategory::Keyword;
1169 } else if (closelyRelated(candidate->m_node, start)) {
1170 category = TargetCategory::Nearby;
1171 }
1172
1173 return std::pair{category, candidate->m_priority};
1174 };
1175
1176 auto findBestCandidate = [&](const TargetMap &tgtMap, const QString &key) {
1177 TargetRec *best = nullptr;
1178 auto [it, end] = tgtMap.equal_range(key);
1179 while (it != end) {
1180 TargetRec *candidate = it.value();
1181 if ((genus == Genus::DontCare) || hasCommonGenusType(genus, candidate->genus())) {
1182 if (!best || rank(candidate) < rank(best))
1183 best = candidate;
1184 }
1185 ++it;
1186 }
1187 return best;
1188 };
1189
1190 TargetRec *bestTarget = findBestCandidate(m_nodesByTargetTitle, target);
1191 if (!bestTarget)
1192 bestTarget = findBestCandidate(m_nodesByTargetRef, TextUtils::asAsciiPrintable(target));
1193
1194 return bestTarget;
1195}
1196
1197/*!
1198 This function searches for a node with the specified \a title.
1199 */
1200const PageNode *Tree::findPageNodeByTitle(const QString &title) const
1201{
1202 PageNodeMultiMap::const_iterator it;
1203 if (title.contains(QChar(' ')))
1204 it = m_pageNodesByTitle.constFind(TextUtils::asAsciiPrintable(title));
1205 else
1206 it = m_pageNodesByTitle.constFind(title);
1207 if (it != m_pageNodesByTitle.constEnd()) {
1208 /*
1209 Reporting all these duplicate section titles is probably
1210 overkill. We should report the duplicate file and let
1211 that suffice.
1212 */
1213 PageNodeMultiMap::const_iterator j = it;
1214 ++j;
1215 if (j != m_pageNodesByTitle.constEnd() && j.key() == it.key()) {
1216 while (j != m_pageNodesByTitle.constEnd()) {
1217 if (j.key() == it.key() && j.value()->url().isEmpty()) {
1218 break; // Just report one duplicate for now.
1219 }
1220 ++j;
1221 }
1222 if (j != m_pageNodesByTitle.cend()) {
1223 it.value()->location().warning("This page title exists in more than one file: "
1224 + title);
1225 j.value()->location().warning("[It also exists here]");
1226 }
1227 }
1228 return it.value();
1229 }
1230 return nullptr;
1231}
1232
1233/*!
1234 Returns a canonical title for the \a atom, if the \a atom
1235 is a SectionLeft, SectionHeadingLeft, Keyword, or Target.
1236
1237 If a target or a keyword is immediately followed by a
1238 section, the former adopts the title (ref) of the latter.
1239 */
1240QString Tree::refForAtom(const Atom *atom)
1241{
1242 Q_ASSERT(atom);
1243
1244 switch (atom->type()) {
1245 case Atom::SectionLeft:
1246 atom = atom->next();
1247 [[fallthrough]];
1249 if (atom->count() >= 2)
1250 return atom->string(1);
1251 return TextUtils::asAsciiPrintable(Text::sectionHeading(atom).toString());
1252 case Atom::Target:
1253 [[fallthrough]];
1254 case Atom::Keyword:
1255 if (atom->count() >= 2)
1256 return atom->string(1);
1257 if (const auto *section = nextSection(atom))
1258 return refForAtom(section);
1259 return TextUtils::asAsciiPrintable(atom->string());
1260 default:
1261 return {};
1262 }
1263}
1264
1265/*!
1266 \fn const CNMap &Tree::groups() const
1267 Returns a const reference to the collection of all
1268 group nodes.
1269*/
1270
1271/*!
1272 \fn const ModuleMap &Tree::modules() const
1273 Returns a const reference to the collection of all
1274 module nodes.
1275*/
1276
1277/*!
1278 \fn const QmlModuleMap &Tree::qmlModules() const
1279 Returns a const reference to the collection of all
1280 QML module nodes.
1281*/
1282
1283/*!
1284 Returns a pointer to the collection map specified by \a type.
1285 Returns null if \a type is not specified.
1286 */
1287CNMap *Tree::getCollectionMap(NodeType type)
1288{
1289 switch (type) {
1290 case NodeType::Group:
1291 return &m_groups;
1292 case NodeType::Module:
1293 return &m_modules;
1295 return &m_qmlModules;
1296 case NodeType::Concept:
1297 return &m_concepts;
1298 default:
1299 break;
1300 }
1301 return nullptr;
1302}
1303
1304/*!
1305 Searches this tree for a collection named \a name with the
1306 specified \a type. If the collection is found, a pointer
1307 to it is returned. If a collection is not found, null is
1308 returned.
1309 */
1310CollectionNode *Tree::getCollection(const QString &name, NodeType type)
1311{
1312 CNMap *map = getCollectionMap(type);
1313 if (map) {
1314 auto it = map->constFind(name);
1315 if (it != map->cend())
1316 return it.value();
1317 }
1318 return nullptr;
1319}
1320
1321/*!
1322 Find the group, module, or QML module named \a name and return a
1323 pointer to that collection node. \a type specifies which kind of
1324 collection node you want. If a collection node with the specified \a
1325 name and \a type is not found, a new one is created, and the pointer
1326 to the new one is returned.
1327
1328 If a new collection node is created, its parent is the tree
1329 root, and the new collection node is marked \e{not seen}.
1330
1331 \a genus must be specified, i.e. it must not be \c{DontCare}.
1332 If it is \c{DontCare}, 0 is returned, which is a programming
1333 error.
1334 */
1335CollectionNode *Tree::findCollection(const QString &name, NodeType type)
1336{
1337 CNMap *m = getCollectionMap(type);
1338 if (!m) // error
1339 return nullptr;
1340 auto it = m->constFind(name);
1341 if (it != m->cend())
1342 return it.value();
1343 CollectionNode *cn = new CollectionNode(type, root(), name);
1345 m->insert(name, cn);
1346 return cn;
1347}
1348
1349/*! \fn CollectionNode *Tree::findGroup(const QString &name)
1350 Find the group node named \a name and return a pointer
1351 to it. If the group node is not found, add a new group
1352 node named \a name and return a pointer to the new one.
1353
1354 If a new group node is added, its parent is the tree root,
1355 and the new group node is marked \e{not seen}.
1356 */
1357
1358/*! \fn CollectionNode *Tree::findModule(const QString &name)
1359 Find the module node named \a name and return a pointer
1360 to it. If a matching node is not found, add a new module
1361 node named \a name and return a pointer to that one.
1362
1363 If a new module node is added, its parent is the tree root,
1364 and the new module node is marked \e{not seen}.
1365 */
1366
1367/*! \fn CollectionNode *Tree::findQmlModule(const QString &name)
1368 Find the QML module node named \a name and return a pointer
1369 to it. If a matching node is not found, add a new QML module
1370 node named \a name and return a pointer to that one.
1371
1372 If a new QML module node is added, its parent is the tree root,
1373 and the new node is marked \e{not seen}.
1374 */
1375
1376/*! \fn CollectionNode *Tree::addGroup(const QString &name)
1377 Looks up the group node named \a name in the collection
1378 of all group nodes. If a match is found, a pointer to the
1379 node is returned. Otherwise, a new group node named \a name
1380 is created and inserted into the collection, and the pointer
1381 to that node is returned.
1382 */
1383
1384/*! \fn CollectionNode *Tree::addModule(const QString &name)
1385 Looks up the module node named \a name in the collection
1386 of all module nodes. If a match is found, a pointer to the
1387 node is returned. Otherwise, a new module node named \a name
1388 is created and inserted into the collection, and the pointer
1389 to that node is returned.
1390 */
1391
1392/*! \fn CollectionNode *Tree::addQmlModule(const QString &name)
1393 Looks up the QML module node named \a name in the collection
1394 of all QML module nodes. If a match is found, a pointer to the
1395 node is returned. Otherwise, a new QML module node named \a name
1396 is created and inserted into the collection, and the pointer
1397 to that node is returned.
1398 */
1399
1400/*!
1401 Looks up the group node named \a name in the collection
1402 of all group nodes. If a match is not found, a new group
1403 node named \a name is created and inserted into the collection.
1404 Then append \a node to the group's members list, and append the
1405 group name to the list of group names in \a node. The parent of
1406 \a node is not changed by this function. Returns a pointer to
1407 the group node.
1408 */
1409CollectionNode *Tree::addToGroup(const QString &name, Node *node)
1410{
1411 CollectionNode *cn = findGroup(name);
1412 if (!node->isInternal()) {
1413 cn->addMember(node);
1414 node->appendGroupName(name);
1415 }
1416 return cn;
1417}
1418
1419/*!
1420 Looks up the module node named \a name in the collection
1421 of all module nodes. If a match is not found, a new module
1422 node named \a name is created and inserted into the collection.
1423 Then append \a node to the module's members list. The parent of
1424 \a node is not changed by this function. Returns the module node.
1425 */
1426CollectionNode *Tree::addToModule(const QString &name, Node *node)
1427{
1428 CollectionNode *cn = findModule(name);
1429 cn->addMember(node);
1430 node->setPhysicalModuleName(name);
1431 return cn;
1432}
1433
1434/*!
1435 Looks up the QML module named \a name. If it isn't there,
1436 create it. Then append \a node to the QML module's member
1437 list. The parent of \a node is not changed by this function.
1438 Returns the pointer to the QML module node.
1439 */
1440CollectionNode *Tree::addToQmlModule(const QString &name, Node *node)
1441{
1442 QStringList qmid;
1443 QStringList dotSplit;
1444 QStringList blankSplit = name.split(QLatin1Char(' '));
1445 qmid.append(blankSplit[0]);
1446 if (blankSplit.size() > 1) {
1447 qmid.append(blankSplit[0] + blankSplit[1]);
1448 dotSplit = blankSplit[1].split(QLatin1Char('.'));
1449 qmid.append(blankSplit[0] + dotSplit[0]);
1450 }
1451
1452 CollectionNode *cn = findQmlModule(blankSplit[0]);
1453 cn->addMember(node);
1454 node->setQmlModule(cn);
1455 if (node->isQmlType()) {
1456 QmlTypeNode *n = static_cast<QmlTypeNode *>(node);
1457 for (int i = 0; i < qmid.size(); ++i) {
1458 QString key = qmid[i] + "::" + node->name();
1459 insertQmlType(key, n);
1460 }
1461 // Also insert with unqualified name for context-aware disambiguation
1462 insertQmlType(node->name(), n);
1463 }
1464 return cn;
1465}
1466
1467/*!
1468 Inserts QML type node \a n with the specified \a key into the type map.
1469 Since the map is a QMultiMap, multiple types with the same name can coexist
1470 (e.g., Shape from different modules).
1471 */
1472void Tree::insertQmlType(const QString &key, QmlTypeNode *n)
1473{
1474 m_qmlTypeMap.insert(key, n);
1475}
1476
1477/*!
1478 Looks up and returns the QML type node identified by \a name. When multiple
1479 types with the same name exist (e.g., Shape from different modules), prefers
1480 the type from the same module as \a relative if provided. Returns the first
1481 match if no module relationship exists, or nullptr if not found.
1482 */
1483QmlTypeNode *Tree::lookupQmlType(const QString &name, const Node *relative) const
1484{
1485 auto values = m_qmlTypeMap.values(name);
1486 if (values.isEmpty())
1487 return nullptr;
1488
1489 // If no context or only one match, return first result
1490 if (!relative || values.size() == 1)
1491 return values.first();
1492
1493 // Prefer types from the same module as the relative context
1494 if (relative->isQmlType()) {
1495 const auto *relativeQmlType = static_cast<const QmlTypeNode *>(relative);
1496 const CollectionNode *relativeModule = relativeQmlType->logicalModule();
1497
1498 for (auto *candidate : values) {
1499 if (candidate->logicalModule() == relativeModule)
1500 return candidate;
1501 }
1502 }
1503
1504 // Fallback to first match
1505 return values.first();
1506}
1507
1508/*!
1509 Finds the function node with the specifried name \a path that
1510 also has the specified \a parameters and returns a pointer to
1511 the first matching function node if one is found.
1512
1513 This function begins searching the tree at \a relative for
1514 the \l {FunctionNode} {function node} identified by \a path
1515 that has the specified \a parameters. The \a flags are
1516 used to restrict the search. If a matching node is found, a
1517 pointer to it is returned. Otherwise, nullis returned. If
1518 \a relative is ull, the search begins at the tree root.
1519 */
1520const FunctionNode *Tree::findFunctionNode(const QStringList &path, const Parameters &parameters,
1521 const Node *relative, Genus genus) const
1522{
1523 if (path.size() == 3 && !path[0].isEmpty()
1524 && ((genus == Genus::QML) || (genus == Genus::DontCare))) {
1525 QmlTypeNode *qcn = lookupQmlType(QString(path[0] + "::" + path[1]), relative);
1526 if (qcn == nullptr) {
1527 QStringList p(path[1]);
1528 Node *n = findNodeByNameAndType(p, &Node::isQmlType);
1529 if ((n != nullptr) && n->isQmlType())
1530 qcn = static_cast<QmlTypeNode *>(n);
1531 }
1532 if (qcn != nullptr)
1533 return static_cast<const FunctionNode *>(qcn->findFunctionChild(path[2], parameters));
1534 }
1535
1536 if (relative == nullptr)
1537 relative = root();
1538 else if (genus != Genus::DontCare) {
1539 if (!(hasCommonGenusType(genus, relative->genus())))
1540 relative = root();
1541 }
1542
1543 do {
1544 Node *node = const_cast<Node *>(relative);
1545 int i;
1546
1547 for (i = 0; i < path.size(); ++i) {
1548 if (node == nullptr || !node->isAggregate())
1549 break;
1550
1551 Aggregate *aggregate = static_cast<Aggregate *>(node);
1552 Node *next = nullptr;
1553 if (i == path.size() - 1)
1554 next = aggregate->findFunctionChild(path.at(i), parameters);
1555 else
1556 next = aggregate->findChildNode(path.at(i), genus);
1557
1558 if ((next == nullptr) && aggregate->isClassNode()) {
1559 const ClassList bases = allBaseClasses(static_cast<const ClassNode *>(aggregate));
1560 for (auto *base : bases) {
1561 if (i == path.size() - 1)
1562 next = base->findFunctionChild(path.at(i), parameters);
1563 else
1564 next = base->findChildNode(path.at(i), genus);
1565
1566 if (next != nullptr)
1567 break;
1568 }
1569 }
1570
1571 node = next;
1572 } // for (i = 0; i < path.size(); ++i)
1573
1574 if (node && i == path.size() && node->isFunction()) {
1575 // A function node was found at the end of the path.
1576 // If it is not marked private, return it. If it is
1577 // marked private, then if it overrides a function,
1578 // find that function instead because it might not
1579 // be marked private. If all the overloads are
1580 // marked private, return the original function node.
1581 // This should be replace with findOverriddenFunctionNode().
1582 const FunctionNode *fn = static_cast<const FunctionNode *>(node);
1583 const FunctionNode *FN = fn;
1584 while (FN->isPrivate() && !FN->overridesThis().isEmpty()) {
1585 QStringList path = FN->overridesThis().split("::");
1586 FN = m_qdb->findFunctionNode(path, parameters, relative, genus);
1587 if (FN == nullptr)
1588 break;
1589 if (!FN->isPrivate())
1590 return FN;
1591 }
1592 return fn;
1593 }
1594 relative = relative->parent();
1595 } while (relative);
1596 return nullptr;
1597}
1598
1599/*!
1600 Search this tree recursively from \a parent to find a function
1601 node with the specified \a tag. If no function node is found
1602 with the required \a tag, return 0.
1603 */
1604FunctionNode *Tree::findFunctionNodeForTag(const QString &tag, Aggregate *parent)
1605{
1606 if (parent == nullptr)
1607 parent = root();
1608 const NodeList &children = parent->childNodes();
1609 for (Node *n : children) {
1610 if (n != nullptr && n->isFunction() && n->hasTag(tag))
1611 return static_cast<FunctionNode *>(n);
1612 }
1613 for (Node *n : children) {
1614 if (n != nullptr && n->isAggregate()) {
1615 n = findFunctionNodeForTag(tag, static_cast<Aggregate *>(n));
1616 if (n != nullptr)
1617 return static_cast<FunctionNode *>(n);
1618 }
1619 }
1620 return nullptr;
1621}
1622
1623/*!
1624 There should only be one macro node for macro name \a t.
1625 The macro node is not built until the \macro command is seen.
1626 */
1627FunctionNode *Tree::findMacroNode(const QString &t, const Aggregate *parent)
1628{
1629 if (parent == nullptr)
1630 parent = root();
1631 const NodeList &children = parent->childNodes();
1632 for (Node *n : children) {
1633 if (n != nullptr && (n->isMacro() || n->isFunction()) && n->name() == t)
1634 return static_cast<FunctionNode *>(n);
1635 }
1636 for (Node *n : children) {
1637 if (n != nullptr && n->isAggregate()) {
1638 FunctionNode *fn = findMacroNode(t, static_cast<Aggregate *>(n));
1639 if (fn != nullptr)
1640 return fn;
1641 }
1642 }
1643 return nullptr;
1644}
1645
1646/*!
1647 Add the class and struct names in \a arg to the \e {don't document}
1648 map.
1649 */
1650void Tree::addToDontDocumentMap(QString &arg)
1651{
1652 arg.remove(QChar('('));
1653 arg.remove(QChar(')'));
1654 QString t = arg.simplified();
1655 QStringList sl = t.split(QChar(' '));
1656 if (sl.isEmpty())
1657 return;
1658 for (const QString &s : sl) {
1659 if (!m_dontDocumentMap.contains(s))
1660 m_dontDocumentMap.insert(s, nullptr);
1661 }
1662}
1663
1664/*!
1665 The \e {don't document} map has been loaded with the names
1666 of classes and structs in the current module that are not
1667 documented and should not be documented. Now traverse the
1668 map, and for each class or struct name, find the class node
1669 that represents that class or struct and mark it with the
1670 \C DontDocument status.
1671
1672 This results in a map of the class and struct nodes in the
1673 module that are in the public API but are not meant to be
1674 used by anyone. They are only used internally, but for one
1675 reason or another, they must have public visibility.
1676 */
1678{
1679 for (auto it = m_dontDocumentMap.begin(); it != m_dontDocumentMap.end(); ++it) {
1680 Aggregate *node = findAggregate(it.key());
1681 if (node != nullptr)
1683 }
1684}
1685
1686QT_END_NAMESPACE
FunctionNode * findFunctionChild(const FunctionNode *clone)
Returns the function node that is a child of this node, such that the function described has the same...
const NodeList & childNodes() const
Returns a const reference to the child list.
Definition aggregate.h:48
The Atom class is the fundamental unit for representing documents internally.
Definition atom.h:19
AtomType type() const
Return the type of this atom.
Definition atom.h:146
@ ListTagLeft
Definition atom.h:69
@ Keyword
Definition atom.h:61
@ Target
Definition atom.h:108
@ SectionRight
Definition atom.h:86
@ SectionHeadingLeft
Definition atom.h:87
@ SinceTagLeft
Definition atom.h:92
@ SectionLeft
Definition atom.h:85
const Atom * next() const
Return the next atom in the atom list.
Definition atom.h:143
const Atom * next(AtomType t) const
Return the next Atom in the list if it is of AtomType t.
Definition atom.cpp:302
The ClassNode represents a C++ class.
Definition classnode.h:23
void removePrivateAndInternalBases()
Remove private and internal bases classes from this class's list of base classes.
A class for holding the members of a collection of doc pages.
void addMember(Node *node) override
Appends node to the collection node's member list and updates the new member's status.
bool hasTableOfContents() const
Definition doc.cpp:292
bool hasKeywords() const
Definition doc.cpp:297
bool hasTargets() const
Definition doc.cpp:302
This node is used to represent any kind of function being documented.
static bool requiresDocumentation(const InclusionPolicy &policy, const NodeContext &context)
This class represents a C++ namespace.
A PageNode is a Node that generates a documentation page.
Definition pagenode.h:19
This class describes one instance of using the Q_PROPERTY macro.
const PropertyNode * overriddenFrom() const
void addFunction(FunctionNode *function, FunctionRole role)
void setOverriddenFrom(const PropertyNode *baseProperty)
Sets this property's {overridden from} property to baseProperty, which indicates that this property o...
void addSignal(FunctionNode *function, FunctionRole role)
This class provides exclusive access to the qdoc database, which consists of a forrest of trees and a...
Status
Specifies the status of the QQmlIncubator.
QmlTypeNode * qmlBaseNode() const override
If this Aggregate is a QmlTypeNode, this function returns a pointer to the QmlTypeNode that is its ba...
Definition qmltypenode.h:54
Definition text.h:12
static Text sectionHeading(const Atom *sectionBegin)
Definition text.cpp:157
This class constructs and maintains a tree of instances of the subclasses of Node.
Definition tree.h:59
void addExternalRelates(Node *node, const QString &target)
Records that node is related to the aggregate named target, which is documented in a different module...
Definition tree.cpp:193
void markDontDocumentNodes()
The {don't document} map has been loaded with the names of classes and structs in the current module ...
Definition tree.cpp:1677
void addToDontDocumentMap(QString &arg)
Add the class and struct names in arg to the {don't document} map.
Definition tree.cpp:1650
Node * findNodeByNameAndType(const QStringList &path, bool(Node::*isMatch)() const) const
Find the node with the specified path name that is of the specified type and subtype.
Definition tree.cpp:490
void resolveProperties()
Resolves access functions associated with each PropertyNode stored in m_unresolvedPropertyMap,...
Definition tree.cpp:288
void addPropertyFunction(PropertyNode *property, const QString &funcName, PropertyNode::FunctionRole funcRole)
Inserts function name funcName and function role funcRole into the property function map for the spec...
Definition tree.cpp:210
NodeType
Definition genustypes.h:165
Combined button and popup list for selecting options.
QList< Node * > NodeList
Definition node.h:45
QList< ClassNode * > ClassList
Definition node.h:46
QList< Node * > NodeVector
Definition node.h:47
QMap< QString, CollectionNode * > CNMap
Definition node.h:52
@ QmlAttachedProperties
@ SearchBaseClasses
@ SearchEnumValues
@ IgnoreModules
@ TypesOnly
@ DontDocument
Definition status.h:17
The Node class is the base class for all the nodes in QDoc's parse tree.
const Doc & doc() const
Returns a reference to the node's Doc data member.
Definition node.h:239
virtual bool isWrapper() const
Returns true if the node is a class node or a QML type node that is marked as being a wrapper class o...
Definition node.cpp:989
bool isPrivate() const
Returns true if this node's access is Private.
Definition node.h:113
virtual void setQmlModule(CollectionNode *)
If this is a QmlTypeNode, this function sets the QML type's QML module pointer to the CollectionNode ...
Definition node.h:263
bool isQmlType() const
Returns true if the node type is QmlType or QmlValueType.
Definition node.h:123
bool isSharedCommentNode() const
Returns true if the node type is SharedComment.
Definition node.h:126
virtual bool isInternal() const
Returns true if the node's status is Internal, or if its parent is a class with Internal status.
Definition node.cpp:868
Genus genus() const override
Returns this node's Genus.
Definition node.h:85
virtual bool isPageNode() const
Returns true if this node represents something that generates a documentation page.
Definition node.h:150
bool isEnumType() const
Returns true if the node type is Enum.
Definition node.h:94
virtual Status status() const
Returns the node's status value.
Definition node.h:243
virtual bool isTextPageNode() const
Returns true if the node is a PageNode but not an Aggregate.
Definition node.h:155
virtual bool isAttached() const
Returns true if the QML property or QML method node is marked as attached.
Definition node.h:144
Aggregate * parent() const
Returns the node's parent pointer, that is, the aggregate under which the node is documented.
Definition node.h:211
virtual bool isAggregate() const
Returns true if this node is an aggregate, which means it inherits Aggregate and can therefore have c...
Definition node.h:138
const Location & location() const
If this node's definition location is empty, this function returns this node's declaration location.
Definition node.h:235
Access access() const
Returns the node's Access setting, which can be Public, Protected, or Private.
Definition node.h:232
bool isFunction(Genus g=Genus::DontCare) const
Returns true if this is a FunctionNode and its Genus is set to g.
Definition node.h:101
bool isProperty() const
Returns true if the node type is Property.
Definition node.h:114
NodeContext createContext() const
Definition node.cpp:175
bool hasDoc() const
Returns true if this node is documented, or it represents a documented node read from the index ('had...
Definition node.cpp:942
virtual bool isClassNode() const
Returns true if this is an instance of ClassNode.
Definition node.h:145
virtual void setStatus(Status t)
Sets the node's status to t.
Definition node.cpp:574
bool isQmlProperty() const
Returns true if the node type is QmlProperty.
Definition node.h:122
A class for parsing and managing a function parameter list.
Definition main.cpp:28
A record of a linkable target within the documentation.
Definition tree.h:28
Node * m_node
Definition tree.h:47
Genus genus() const
Definition tree.h:45
TargetType
A type of a linkable target record.
Definition tree.h:30
@ Keyword
Definition tree.h:30
@ Contents
Definition tree.h:30
TargetType m_type
Definition tree.h:49
static const Atom * nextSection(const Atom *a)
Definition tree.cpp:984
QMultiMap< QString, TargetRec * > TargetMap
Definition tree.h:53