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
clangcodeparser.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
6
7#include "access.h"
8#include "classnode.h"
9#include "config.h"
10#include "doc.h"
11#include "enumnode.h"
12#include "fnlookupresult.h"
13#include "functionnode.h"
14#include "genustypes.h"
17#include "namespacenode.h"
18#include "propertynode.h"
19#include "qdocdatabase.h"
20#include "typedefnode.h"
21#include "variablenode.h"
23#include "utilities.h"
24
25#include <QtCore/qdebug.h>
26#include <QtCore/qdir.h>
27#include <QtCore/qelapsedtimer.h>
28#include <QtCore/qfile.h>
29#include <QtCore/qregularexpression.h>
30#include <QtCore/qscopedvaluerollback.h>
31#include <QtCore/qtemporarydir.h>
32#include <QtCore/qtextstream.h>
33#include <QtCore/qvarlengtharray.h>
34
35#include <clang-c/Index.h>
36
37#include <clang/AST/ASTConcept.h>
38#include <clang/AST/Decl.h>
39#include <clang/AST/DeclFriend.h>
40#include <clang/AST/DeclTemplate.h>
41#include <clang/AST/Expr.h>
42#include <clang/AST/ExprConcepts.h>
43#include <clang/AST/Type.h>
44#include <clang/AST/TypeLoc.h>
45#include <clang/Basic/SourceLocation.h>
46#include <clang/Frontend/ASTUnit.h>
47#include <clang/Lex/Lexer.h>
48#include <llvm/Support/Casting.h>
49
50#include "clang/AST/QualTypeNames.h"
52
53#include <algorithm>
54#include <cstdio>
55#include <optional>
56#include <string_view>
57
58QT_BEGIN_NAMESPACE
59
60using namespace Qt::Literals::StringLiterals;
61
63 CXIndex index = nullptr;
64
65 operator CXIndex() {
66 return index;
67 }
68
70 clang_disposeIndex(index);
71 }
72};
73
75 CXTranslationUnit tu = nullptr;
76
77 operator CXTranslationUnit() {
78 return tu;
79 }
80
81 operator bool() {
82 return tu;
83 }
84
86 clang_disposeTranslationUnit(tu);
87 }
88};
89
90// We're printing diagnostics in ClangCodeParser::printDiagnostics,
91// so avoid clang itself printing them.
92static const auto kClangDontDisplayDiagnostics = 0;
93
94static CXTranslationUnit_Flags flags_ = static_cast<CXTranslationUnit_Flags>(0);
95
96constexpr const char fnDummyFileName[] = "/fn_dummyfile.cpp";
97
98#ifndef QT_NO_DEBUG_STREAM
99template<class T>
100static QDebug operator<<(QDebug debug, const std::vector<T> &v)
101{
102 QDebugStateSaver saver(debug);
103 debug.noquote();
104 debug.nospace();
105 const size_t size = v.size();
106 debug << "std::vector<>[" << size << "](";
107 for (size_t i = 0; i < size; ++i) {
108 if (i)
109 debug << ", ";
110 debug << v[i];
111 }
112 debug << ')';
113 return debug;
114}
115#endif // !QT_NO_DEBUG_STREAM
116
117static void printDiagnostics(const CXTranslationUnit &translationUnit)
118{
119 if (!lcQdocClang().isDebugEnabled())
120 return;
121
122 static const auto displayOptions = CXDiagnosticDisplayOptions::CXDiagnostic_DisplaySourceLocation
123 | CXDiagnosticDisplayOptions::CXDiagnostic_DisplayColumn
124 | CXDiagnosticDisplayOptions::CXDiagnostic_DisplayOption;
125
126 for (unsigned i = 0, numDiagnostics = clang_getNumDiagnostics(translationUnit); i < numDiagnostics; ++i) {
127 auto diagnostic = clang_getDiagnostic(translationUnit, i);
128 auto formattedDiagnostic = clang_formatDiagnostic(diagnostic, displayOptions);
129 qCDebug(lcQdocClang) << clang_getCString(formattedDiagnostic);
130 clang_disposeString(formattedDiagnostic);
131 clang_disposeDiagnostic(diagnostic);
132 }
133}
134
135/*!
136 * Returns the underlying Decl that \a cursor represents.
137 *
138 * This can be used to drop back down from a LibClang's CXCursor to
139 * the underlying C++ AST that Clang provides.
140 *
141 * It should be used when LibClang does not expose certain
142 * functionalities that are available in the C++ AST.
143 *
144 * The CXCursor should represent a declaration. Usages of this
145 * function on CXCursors that do not represent a declaration may
146 * produce undefined results.
147 */
148static const clang::Decl* get_cursor_declaration(CXCursor cursor) {
149 assert(clang_isDeclaration(clang_getCursorKind(cursor)));
150
151 return static_cast<const clang::Decl*>(cursor.data[0]);
152}
153
154
155/*!
156 * Returns a string representing the name of \a type as if it was
157 * referred to at the end of the translation unit that it was parsed
158 * from.
159 *
160 * For example, given the following code:
161 *
162 * \code
163 * namespace foo {
164 * template<typename T>
165 * struct Bar {
166 * using Baz = const T&;
167 *
168 * void bam(Baz);
169 * };
170 * }
171 * \endcode
172 *
173 * Given a parsed translation unit and an AST node, say \e {decl},
174 * representing the parameter declaration of the first argument of \c {bam},
175 * calling \c{get_fully_qualified_name(decl->getType(), * decl->getASTContext())}
176 * would result in the string \c {foo::Bar<T>::Baz}.
177 *
178 * This should generally be used every time the stringified
179 * representation of a type is acquired as part of parsing with Clang,
180 * so as to ensure a consistent behavior and output.
181 */
182/*
183 * Ensures that bare "(unnamed)" or "(anonymous)" markers in \a typeName
184 * include the record keyword (struct, union, class). Without
185 * anonymous tag locations, some LLVM versions omit the keyword
186 * for some or all anonymous scopes. This function recovers the correct
187 * keyword for each scope from the RecordDecl hierarchy.
188 *
189 * Only anonymous record types produce scope components in fully qualified
190 * names — anonymous enums don't create "(unnamed enum)::" segments
191 * because their enumerators are injected into the enclosing scope.
192 *
193 * For nested anonymous records such as "(unnamed)::(unnamed)" where the
194 * outer scope is a union and the inner is a struct, each marker receives
195 * its own keyword. The parent walk follows only RecordDecl contexts,
196 * which is sufficient because only anonymous records produce these
197 * scope components in Clang's fully qualified name output.
198 *
199 * The function assumes Clang produces structurally well-formed anonymous
200 * markers: either bare "(unnamed)" or with a keyword "(unnamed struct)".
201 * Malformed spellings would silently consume a keyword entry.
202 */
203static std::string ensureAnonymousTagKeyword(std::string typeName, clang::QualType type)
204{
205 const clang::RecordType *rt = type->getAs<clang::RecordType>();
206 if (!rt)
207 return typeName;
208
209 // Collect keywords from innermost to outermost anonymous scope.
210 std::vector<std::string> keywords;
211 const clang::RecordDecl *decl = rt->getDecl();
212 while (decl) {
213 if (decl->getDeclName().isEmpty())
214 keywords.emplace_back(decl->getKindName());
215 const auto *parent = llvm::dyn_cast<clang::RecordDecl>(decl->getDeclContext());
216 decl = parent;
217 }
218 // Reverse so index 0 is the outermost anonymous scope,
219 // matching left-to-right marker order in the type string.
220 std::reverse(keywords.begin(), keywords.end());
221
222 // Scan left-to-right for "(unnamed" / "(anonymous" prefixes.
223 // Each prefix corresponds to one anonymous scope in the keyword list.
224 // Some LLVM versions already include the keyword (e.g., "(unnamed union)")
225 // while others produce bare "(unnamed)". Only inject when missing.
226 static constexpr std::string_view prefixes[] = { "(unnamed", "(anonymous" };
227 size_t keywordIndex = 0;
228 size_t pos = 0;
229 while (pos < typeName.size() && keywordIndex < keywords.size()) {
230 std::string_view foundPrefix;
231 size_t foundPos = std::string::npos;
232 for (auto prefix : prefixes) {
233 size_t p = typeName.find(prefix, pos);
234 if (p < foundPos) {
235 foundPos = p;
236 foundPrefix = prefix;
237 }
238 }
239 if (foundPos == std::string::npos)
240 break;
241
242 size_t afterPrefix = foundPos + foundPrefix.size();
243 if (afterPrefix < typeName.size() && typeName[afterPrefix] == ')') {
244 // Bare marker — inject the keyword before ')'.
245 typeName.insert(afterPrefix, " " + keywords[keywordIndex]);
246 pos = afterPrefix + 1 + keywords[keywordIndex].size() + 1;
247 } else {
248 // Already has a keyword — skip past the closing ')'.
249 size_t closePos = typeName.find(')', afterPrefix);
250 pos = (closePos != std::string::npos) ? closePos + 1 : afterPrefix;
251 }
252 ++keywordIndex;
253 }
254 return typeName;
255}
256
257static std::string get_fully_qualified_type_name(clang::QualType type, const clang::ASTContext& declaration_context) {
258 auto policy = declaration_context.getPrintingPolicy();
259#if LIBCLANG_VERSION_MAJOR >= 23
260 policy.AnonymousTagNameStyle = llvm::to_underlying(clang::PrintingPolicy::AnonymousTagMode::Plain);
261#else
262 policy.AnonymousTagLocations = false;
263#endif
264 std::string result = clang::TypeName::getFullyQualifiedName(type, declaration_context, policy);
265 return ensureAnonymousTagKeyword(std::move(result), type);
266}
267
268/*
269 * Normalizes anonymous type names in strings that do not come through
270 * get_fully_qualified_type_name(), such as cursor spelling results.
271 * Strips file-path locations from anonymous type names, transforming
272 * patterns such as "(unnamed struct at /path/file.h:67)" into
273 * "(unnamed struct)". The single-word token between the marker and
274 * " at " is preserved as-is — this is intentionally broader than
275 * just C++ record keywords so that any Clang spelling passes through
276 * without an exhaustive keyword list.
277 */
278static QString cleanAnonymousTypeName(const QString &typeName) {
279 if (!typeName.contains("(unnamed "_L1) && !typeName.contains("(anonymous "_L1))
280 return typeName;
281
282 static const QRegularExpression pattern(
283 R"(\‍((unnamed|anonymous)(\s+\w+)\s+at\s+[^)]+\‍))"
284 );
285 QString cleaned = typeName;
286 cleaned.replace(pattern, "(\\1\\2)"_L1);
287 return cleaned;
288}
289
290/*
291 * Retrieves expression as written in the original source code.
292 *
293 * declaration_context should be the ASTContext of the declaration
294 * from which the expression was extracted from.
295 *
296 * If the expression contains a leading equal sign it will be removed.
297 *
298 * Leading and trailing spaces will be similarly removed from the expression.
299 */
300static std::string get_expression_as_string(const clang::Expr* expression, const clang::ASTContext& declaration_context) {
301 QString default_value = QString::fromStdString(clang::Lexer::getSourceText(
302 clang::CharSourceRange::getTokenRange(expression->getSourceRange()),
303 declaration_context.getSourceManager(),
304 declaration_context.getLangOpts()
305 ).str());
306
307 if (default_value.startsWith("="))
308 default_value.remove(0, 1);
309
310 default_value = default_value.trimmed();
311
312 return default_value.toStdString();
313}
314
315/*
316 * Recursively walks a constraint expression and collects the fully-qualified
317 * name of every concept referenced by a ConceptSpecializationExpr in the
318 * subtree.
319 *
320 * The walker shares the AST traversal context that the existing requires-clause
321 * extraction already runs through, so the cost is one extra recursive descent
322 * per constrained item — no second visitor and no second translation-unit pass.
323 */
324static void collect_concept_references(const clang::Stmt *node,
325 std::vector<std::string> &out)
326{
327 if (!node)
328 return;
329 if (const auto *cse = llvm::dyn_cast<clang::ConceptSpecializationExpr>(node)) {
330 if (const auto *concept_decl = cse->getNamedConcept())
331 out.push_back(concept_decl->getQualifiedNameAsString());
332 }
333 for (const clang::Stmt *child : node->children())
334 collect_concept_references(child, out);
335}
336
337/*
338 * Retrieves the default value of the passed in type template parameter as a string.
339 *
340 * The default value of a type template parameter is always a type,
341 * and its stringified representation will be return as the fully
342 * qualified version of the type.
343 *
344 * If the parameter has no default value the empty string will be returned.
345 */
346static std::string get_default_value_initializer_as_string(const clang::TemplateTypeParmDecl* parameter) {
347 return (parameter && parameter->hasDefaultArgument()) ?
348 get_fully_qualified_type_name(parameter->getDefaultArgument().getArgument().getAsType(), parameter->getASTContext()) :
349 "";
350}
351
352/*
353 * Retrieves the default value of the passed in non-type template parameter as a string.
354 *
355 * The default value of a non-type template parameter is an expression
356 * and its stringified representation will be return as it was written
357 * in the original code.
358 *
359 * If the parameter as no default value the empty string will be returned.
360 */
361static std::string get_default_value_initializer_as_string(const clang::NonTypeTemplateParmDecl* parameter) {
362 return (parameter && parameter->hasDefaultArgument()) ?
363 get_expression_as_string(parameter->getDefaultArgument().getSourceExpression(), parameter->getASTContext()) : "";
364}
365
366/*
367 * Retrieves the default value of the passed in template template parameter as a string.
368 *
369 * The default value of a template template parameter is a template
370 * name and its stringified representation will be returned as a fully
371 * qualified version of that name.
372 *
373 * If the parameter as no default value the empty string will be returned.
374 */
375static std::string get_default_value_initializer_as_string(const clang::TemplateTemplateParmDecl* parameter) {
376 std::string default_value{};
377
378 if (parameter && parameter->hasDefaultArgument()) {
379 const clang::TemplateName template_name = parameter->getDefaultArgument().getArgument().getAsTemplate();
380
381 llvm::raw_string_ostream ss{default_value};
382 template_name.print(ss, parameter->getASTContext().getPrintingPolicy(), clang::TemplateName::Qualified::AsWritten);
383 }
384
385 return default_value;
386}
387
388/*
389 * Retrieves the default value of the passed in function parameter as
390 * a string.
391 *
392 * The default value of a function parameter is an expression and its
393 * stringified representation will be returned as it was written in
394 * the original code.
395 *
396 * If the parameter as no default value or Clang was not able to yet
397 * parse it at this time the empty string will be returned.
398 */
399static std::string get_default_value_initializer_as_string(const clang::ParmVarDecl* parameter) {
400 if (!parameter || !parameter->hasDefaultArg() || parameter->hasUnparsedDefaultArg())
401 return "";
402
403 return get_expression_as_string(
404 parameter->hasUninstantiatedDefaultArg() ? parameter->getUninstantiatedDefaultArg() : parameter->getDefaultArg(),
405 parameter->getASTContext()
406 );
407}
408
409/*
410 * Retrieves the default value of the passed in declaration, based on
411 * its concrete type, as a string.
412 *
413 * If the declaration is a nullptr or the concrete type of the
414 * declaration is not a supported one, the returned string will be the
415 * empty string.
416 */
417static std::string get_default_value_initializer_as_string(const clang::NamedDecl* declaration) {
418 if (!declaration) return "";
419
420 if (auto type_template_parameter = llvm::dyn_cast<clang::TemplateTypeParmDecl>(declaration))
421 return get_default_value_initializer_as_string(type_template_parameter);
422
423 if (auto non_type_template_parameter = llvm::dyn_cast<clang::NonTypeTemplateParmDecl>(declaration))
424 return get_default_value_initializer_as_string(non_type_template_parameter);
425
426 if (auto template_template_parameter = llvm::dyn_cast<clang::TemplateTemplateParmDecl>(declaration)) {
427 return get_default_value_initializer_as_string(template_template_parameter);
428 }
429
430 if (auto function_parameter = llvm::dyn_cast<clang::ParmVarDecl>(declaration)) {
431 return get_default_value_initializer_as_string(function_parameter);
432 }
433
434 return "";
435}
436
437/*!
438 Call clang_visitChildren on the given cursor with the lambda as a callback
439 T can be any functor that is callable with a CXCursor parameter and returns a CXChildVisitResult
440 (in other word compatible with function<CXChildVisitResult(CXCursor)>
441 */
442template<typename T>
443bool visitChildrenLambda(CXCursor cursor, T &&lambda)
444{
445 CXCursorVisitor visitor = [](CXCursor c, CXCursor,
446 CXClientData client_data) -> CXChildVisitResult {
447 return (*static_cast<T *>(client_data))(c);
448 };
449 return clang_visitChildren(cursor, visitor, &lambda);
450}
451
452/*!
453 convert a CXString to a QString, and dispose the CXString
454 */
455static QString fromCXString(CXString &&string)
456{
457 QString ret = QString::fromUtf8(clang_getCString(string));
458 clang_disposeString(string);
459 return ret;
460}
461
462/*
463 * Unwraps ElaboratedType (LLVM <= 21 only) to find the first
464 * TemplateSpecializationType at or just below the given type.
465 *
466 * This does not perform a general desugar walk. It handles the
467 * specific sugar shape that Clang produces for type alias template
468 * specializations used in Qt SFINAE patterns.
469 */
470static const clang::TemplateSpecializationType *find_template_specialization_through_sugar(
471 const clang::Type *type)
472{
473 // Qt's deepest SFINAE alias nesting is 2–3 levels. The limit
474 // guards against pathological types that could loop indefinitely.
475 for (int depth = 0; depth < 10 && type; ++depth) {
476 if (auto *tst = llvm::dyn_cast<clang::TemplateSpecializationType>(type))
477 return tst;
478
479#if LIBCLANG_VERSION_MAJOR < 22
480 // LLVM <= 21 wraps TemplateSpecializationType in ElaboratedType
481 if (auto *elaborated = llvm::dyn_cast<clang::ElaboratedType>(type)) {
482 type = elaborated->getNamedType().getTypePtr();
483 continue;
484 }
485#endif
486
487 // Not a type we can unwrap further
488 break;
489 }
490
491 return nullptr;
492}
493
494/*
495 * Returns true if the given qualified name ends with "enable_if"
496 * or "enable_if_t".
497 */
498static bool is_enable_if_name(const std::string &qualified_name)
499{
500 auto ends_with = [](const std::string &str, const std::string &suffix) {
501 return str.size() >= suffix.size()
502 && str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
503 };
504
505 return ends_with(qualified_name, "enable_if_t")
506 || ends_with(qualified_name, "enable_if");
507}
508
509/*
510 * Detects whether a non-type template parameter encodes a SFINAE
511 * constraint via std::enable_if_t.
512 *
513 * Qt uses SFINAE constraints as unnamed non-type template parameters
514 * with a default value of true, where the parameter type is a
515 * type alias that resolves through enable_if_t. For example:
516 *
517 * template <typename T, if_integral<T> = true>
518 *
519 * where if_integral<T> is an alias for
520 * std::enable_if_t<std::is_integral_v<T>, bool>.
521 *
522 * Detection targets unnamed NTTPs specifically. Named non-type
523 * template parameters are not treated as SFINAE constraints, even
524 * if their type resolves through enable_if_t, because named
525 * parameters carry explicit meaning that should be preserved in
526 * the rendered signature. A default value is not required — \fn
527 * commands often omit the "= true" default.
528 *
529 * After finding the outermost TemplateSpecializationType (unwrapping
530 * ElaboratedType on LLVM <= 21), the detection desugars inward to
531 * verify that enable_if or enable_if_t appears in the chain.
532 */
534 const clang::NonTypeTemplateParmDecl *param)
535{
536 if (!param->getName().empty())
537 return std::nullopt;
538
539 auto policy = param->getASTContext().getPrintingPolicy();
540
541 const clang::Type *type = param->getType().getTypePtr();
542
544 if (!alias_type) {
545 // Heuristic fallback for dependent nested-alias cases. When
546 // the outer template parameter is dependent, Clang represents
547 // the type as DependentNameType rather than
548 // TemplateSpecializationType, so the sugar chain cannot be
549 // walked to verify enable_if. For example:
550 //
551 // template <class T>
552 // template <typename X, QPointer<T>::if_convertible<X> = true>
553 //
554 // Clang cannot resolve QPointer<T>::if_convertible<X> because
555 // T is dependent. The fallback requires both a default value
556 // (SFINAE parameters always have one — the caller never
557 // provides the argument) and angle brackets in the printed
558 // type name (indicating a template specialization applied to
559 // type parameters).
560 if (!param->hasDefaultArgument())
561 return std::nullopt;
562
563 std::string type_name = param->getType().getAsString(policy);
564 if (type_name.find('<') != std::string::npos)
565 return SfinaeConstraint{ std::move(type_name) };
566
567 return std::nullopt;
568 }
569
570 auto *alias_decl = alias_type->getTemplateName().getAsTemplateDecl();
571 if (!alias_decl)
572 return std::nullopt;
573
574 // Walk the sugar chain to verify enable_if / enable_if_t is present
575 bool found_enable_if = false;
576 const clang::Type *sugar = alias_type->desugar().getTypePtr();
577
578 for (int depth = 0; depth < 10 && sugar; ++depth) {
580 if (!tst)
581 break;
582
583 if (auto *decl = tst->getTemplateName().getAsTemplateDecl()) {
584 if (is_enable_if_name(decl->getQualifiedNameAsString())) {
585 found_enable_if = true;
586 break;
587 }
588 }
589
590 sugar = tst->desugar().getTypePtr();
591 }
592
593 if (!found_enable_if)
594 return std::nullopt;
595
596 // Print from the original QualType (not the unwrapped TST) to
597 // preserve scope qualification. On LLVM <= 21 the ElaboratedType
598 // sugar carries the namespace qualifier; on LLVM 22+ the qualifier
599 // is embedded in the type name directly. The printed output is
600 // the same either way.
601 return SfinaeConstraint{
602 param->getType().getAsString(policy)
603 };
604}
605
606/*
607 * Returns an intermediate representation that models the the given
608 * template declaration.
609 */
610static RelaxedTemplateDeclaration get_template_declaration(const clang::TemplateDecl* template_declaration) {
611 assert(template_declaration);
612
613 RelaxedTemplateDeclaration template_declaration_ir{};
614
615 auto template_parameters = template_declaration->getTemplateParameters();
616 for (auto template_parameter : template_parameters->asArray()) {
617 auto kind{RelaxedTemplateParameter::Kind::TypeTemplateParameter};
618 std::string type{};
619
620 std::optional<SfinaeConstraint> sfinae{};
621
622 if (auto non_type_template_parameter = llvm::dyn_cast<clang::NonTypeTemplateParmDecl>(template_parameter)) {
623 kind = RelaxedTemplateParameter::Kind::NonTypeTemplateParameter;
624 type = get_fully_qualified_type_name(non_type_template_parameter->getType(), non_type_template_parameter->getASTContext());
625
626 // REMARK: QDoc uses this information to match a user
627 // provided documentation (for example from an "\fn"
628 // command) with a `Node` that was extracted from the
629 // code-base.
630 //
631 // Due to how QDoc obtains an AST for documentation that
632 // is provided by the user, there might be a mismatch in
633 // the type of certain non type template parameters.
634 //
635 // QDoc generally builds a fake out-of-line definition for
636 // a callable provided through an "\fn" command, when it
637 // needs to match it.
638 // In that context, certain type names may be dependent
639 // names, while they may not be when the element they
640 // represent is extracted from the code-base.
641 //
642 // This in turn makes their stringified representation
643 // different in the two contextes, as a dependent name may
644 // require the "typename" keyword to precede it.
645 //
646 // Since QDoc uses a very simplified model, and it
647 // generally doesn't need care about the exact name
648 // resolution rules for C++, since it passes by
649 // Clang-validated data, we remove the "typename" keyword
650 // if it prefixes the type representation, so that it
651 // doesn't impact the matching procedure..
652
653 // KLUDGE: Waiting for C++20 to avoid the conversion.
654 // Doesn't really impact performance in a
655 // meaningful way so it can be kept while waiting.
656 if (QString::fromStdString(type).startsWith("typename ")) type.erase(0, std::string("typename ").size());
657
658 sfinae = detect_sfinae_constraint(non_type_template_parameter);
659 }
660
661 auto template_template_parameter = llvm::dyn_cast<clang::TemplateTemplateParmDecl>(template_parameter);
662 if (template_template_parameter) kind = RelaxedTemplateParameter::Kind::TemplateTemplateParameter;
663
664 template_declaration_ir.parameters.push_back({
665 kind,
666 template_parameter->isTemplateParameterPack(),
667 {
668 std::move(type),
669 template_parameter->getNameAsString(),
670 get_default_value_initializer_as_string(template_parameter)
671 },
672 (template_template_parameter ?
673 std::optional<TemplateDeclarationStorage>(TemplateDeclarationStorage{
674 get_template_declaration(template_template_parameter).parameters
675 }) : std::nullopt),
676 std::move(sfinae),
677 std::nullopt
678 });
679
680 // Direct concept-on-template-parameter form, such as
681 // \c {template<Sortable T>}. The constraint hangs off the
682 // \c {TemplateTypeParmDecl} rather than appearing in a requires clause.
683 // The constraint's named concept is reachable as a \c {NamedDecl}, so
684 // its qualified name is available via getQualifiedNameAsString().
685 //
686 // Scope note: this extracts the type-template-parameter form only.
687 // A constrained-auto non-type template parameter, such as
688 // \c {template <Integral auto N>}, surfaces as a NonTypeTemplateParmDecl
689 // whose type contains a constrained AutoType, and is not covered here.
690 if (const auto *type_template_parameter =
691 llvm::dyn_cast<clang::TemplateTypeParmDecl>(template_parameter)) {
692 if (type_template_parameter->hasTypeConstraint()) {
693 if (const clang::TypeConstraint *constraint =
694 type_template_parameter->getTypeConstraint()) {
695 if (const clang::NamedDecl *concept_decl =
696 constraint->getNamedConcept()) {
697 template_declaration_ir.referenced_concepts.push_back(
698 concept_decl->getQualifiedNameAsString());
699 template_declaration_ir.parameters.back().concept_name =
700 concept_decl->getQualifiedNameAsString();
701 }
702 }
703 }
704 }
705 }
706
707 // Collect the explicit requires clause first, if present.
708 std::string explicit_requires;
709 if (const clang::Expr *requires_clause = template_parameters->getRequiresClause()) {
710 explicit_requires = QString::fromStdString(get_expression_as_string(
711 requires_clause, template_declaration->getASTContext())).simplified().toStdString();
712 collect_concept_references(requires_clause,
713 template_declaration_ir.referenced_concepts);
714 }
715
716 // Synthesize a requires clause from detected SFINAE constraints.
717 // SFINAE parameters are annotated but kept in the parameter list
718 // so that \fn matching (which compares parameter counts and types)
719 // still works when detection succeeds on one path but not the
720 // other. Rendering functions skip annotated parameters and emit
721 // the synthesized requires clause instead.
722 {
723 std::string synthesized;
724 const auto &params = template_declaration_ir.parameters;
725
726 for (const auto &param : params) {
727 if (param.sfinae_constraint) {
728 if (!synthesized.empty())
729 synthesized += " && ";
730 synthesized += param.sfinae_constraint->alias_with_args;
731 }
732 }
733
734 // Combine synthesized SFINAE constraints with explicit requires
735 // clause when both are present. The explicit clause is wrapped
736 // in parentheses to preserve its precedence.
737 if (!synthesized.empty() && !explicit_requires.empty())
738 template_declaration_ir.requires_clause = synthesized + " && (" + explicit_requires + ")";
739 else if (!synthesized.empty())
740 template_declaration_ir.requires_clause = std::move(synthesized);
741 else if (!explicit_requires.empty())
742 template_declaration_ir.requires_clause = std::move(explicit_requires);
743 }
744
745 {
746 auto &refs = template_declaration_ir.referenced_concepts;
747 std::sort(refs.begin(), refs.end());
748 refs.erase(std::unique(refs.begin(), refs.end()), refs.end());
749 }
750
751 return template_declaration_ir;
752}
753
754/*!
755 convert a CXSourceLocation to a qdoc Location
756 */
757static Location fromCXSourceLocation(CXSourceLocation location)
758{
759 unsigned int line, column;
760 CXString file;
761 clang_getPresumedLocation(location, &file, &line, &column);
762 Location l(fromCXString(std::move(file)));
763 l.setColumnNo(column);
764 l.setLineNo(line);
765 return l;
766}
767
768/*!
769 convert a CX_CXXAccessSpecifier to Node::Access
770 */
771static Access fromCX_CXXAccessSpecifier(CX_CXXAccessSpecifier spec)
772{
773 switch (spec) {
774 case CX_CXXPrivate:
775 return Access::Private;
776 case CX_CXXProtected:
777 return Access::Protected;
778 case CX_CXXPublic:
779 return Access::Public;
780 default:
781 return Access::Public;
782 }
783}
784
785/*!
786 Returns the spelling in the file for a source range
787 */
788
794
795static inline QString fromCache(const QByteArray &cache,
796 unsigned int offset1, unsigned int offset2)
797{
798 return QString::fromUtf8(cache.mid(offset1, offset2 - offset1));
799}
800
801static QString readFile(CXFile cxFile, unsigned int offset1, unsigned int offset2)
802{
803 using FileCache = QList<FileCacheEntry>;
804 static FileCache cache;
805
806 CXString cxFileName = clang_getFileName(cxFile);
807 const QByteArray fileName = clang_getCString(cxFileName);
808 clang_disposeString(cxFileName);
809
810 for (const auto &entry : std::as_const(cache)) {
811 if (fileName == entry.fileName)
812 return fromCache(entry.content, offset1, offset2);
813 }
814
815 QFile file(QString::fromUtf8(fileName));
816 if (file.open(QIODeviceBase::ReadOnly)) { // binary to match clang offsets
817 FileCacheEntry entry{std::move(fileName), file.readAll()};
818 cache.prepend(entry);
819 while (cache.size() > 5)
820 cache.removeLast();
821 return fromCache(entry.content, offset1, offset2);
822 }
823 return {};
824}
825
826static QString getSpelling(CXSourceRange range)
827{
828 auto start = clang_getRangeStart(range);
829 auto end = clang_getRangeEnd(range);
830 CXFile file1, file2;
831 unsigned int offset1, offset2;
832 clang_getFileLocation(start, &file1, nullptr, nullptr, &offset1);
833 clang_getFileLocation(end, &file2, nullptr, nullptr, &offset2);
834
835 if (file1 != file2 || offset2 <= offset1)
836 return QString();
837
838 return readFile(file1, offset1, offset2);
839}
840
841/*!
842 Returns the function name from a given cursor representing a
843 function declaration. This is usually clang_getCursorSpelling, but
844 not for the conversion function in which case it is a bit more complicated
845 */
846QString functionName(CXCursor cursor)
847{
848 if (clang_getCursorKind(cursor) == CXCursor_ConversionFunction) {
849 // For a CXCursor_ConversionFunction we don't want the spelling which would be something
850 // like "operator type-parameter-0-0" or "operator unsigned int". we want the actual name as
851 // spelled;
852 auto conversion_declaration =
853 static_cast<const clang::CXXConversionDecl*>(get_cursor_declaration(cursor));
854
855 return QLatin1String("operator ") + QString::fromStdString(get_fully_qualified_type_name(
856 conversion_declaration->getConversionType(),
857 conversion_declaration->getASTContext()
858 ));
859 }
860
861 QString name = fromCXString(clang_getCursorSpelling(cursor));
862
863 // Remove template stuff from constructor and destructor but not from operator<
864 auto ltLoc = name.indexOf('<');
865 if (ltLoc > 0 && !name.startsWith("operator<"))
866 name = name.left(ltLoc);
867 return name;
868}
869
870/*!
871 Reconstruct the qualified path name of a function that is
872 being overridden.
873 */
874static QString reconstructQualifiedPathForCursor(CXCursor cur)
875{
876 QString path;
877 auto kind = clang_getCursorKind(cur);
878 while (!clang_isInvalid(kind) && kind != CXCursor_TranslationUnit) {
879 switch (kind) {
880 case CXCursor_Namespace:
881 case CXCursor_StructDecl:
882 case CXCursor_ClassDecl:
883 case CXCursor_UnionDecl:
884 case CXCursor_ClassTemplate:
885 path.prepend("::");
886 path.prepend(fromCXString(clang_getCursorSpelling(cur)));
887 break;
888 case CXCursor_FunctionDecl:
889 case CXCursor_FunctionTemplate:
890 case CXCursor_CXXMethod:
891 case CXCursor_Constructor:
892 case CXCursor_Destructor:
893 case CXCursor_ConversionFunction:
894 path = functionName(cur);
895 break;
896 default:
897 break;
898 }
899 cur = clang_getCursorSemanticParent(cur);
900 kind = clang_getCursorKind(cur);
901 }
902 return path;
903}
904
905/*!
906 \internal
907
908 Extract a class name from a Clang parameter type, stripping references,
909 pointers, and qualifiers. Returns \c {std::nullopt} if the type doesn't
910 represent a class.
911 */
912static std::optional<QString> classNameFromParameterType(clang::QualType param_type)
913{
914 param_type = param_type.getNonReferenceType();
915 while (param_type->isPointerType())
916 param_type = param_type->getPointeeType();
917 param_type = param_type.getUnqualifiedType();
918
919 if (param_type->isBuiltinType())
920 return std::nullopt;
921
922 if (const auto *record_type = param_type->getAs<clang::RecordType>()) {
923 if (const auto *record_decl = record_type->getDecl())
924 return QString::fromStdString(record_decl->getQualifiedNameAsString());
925 }
926
927 // The type may be incomplete (forward-declared or unknown during \fn parsing).
928 // Extract the class name from the type spelling if it looks like a class.
929 QString class_name = QString::fromStdString(param_type.getAsString());
930 class_name.remove("const "_L1).remove("volatile "_L1);
931 class_name.remove("class "_L1).remove("struct "_L1);
932 class_name = class_name.trimmed();
933
934 if (class_name.isEmpty() || class_name.contains('('_L1) || class_name.contains('['_L1))
935 return std::nullopt;
936
937 // Strip template arguments (e.g. "QList<MyClass>" becomes "QList") as
938 // hidden friends are declared in the primary type.
939 if (auto angle = class_name.indexOf('<'_L1); angle > 0)
940 class_name.truncate(angle);
941
942 return class_name;
943}
944
945/*!
946 \internal
947
948 Search for hidden friend candidates by inspecting parameter types.
949 When a \fn command uses unqualified syntax for a hidden friend, the
950 initial name lookup won't find it because hidden friends are stored
951 under their enclosing class, not in the global namespace. This
952 function examines the parameter types of \a func_decl to locate
953 classes that may contain hidden friends with matching names.
954
955 Appends any found hidden friend nodes to \a candidates.
956 */
957static void findHiddenFriendCandidates(QDocDatabase *qdb, const QString &funcName,
958 const clang::FunctionDecl *func_decl, NodeVector &candidates)
959{
960 QSet<ClassNode *> searched_classes;
961 for (const auto *param : func_decl->parameters()) {
962 auto class_name = classNameFromParameterType(param->getType());
963 if (!class_name)
964 continue;
965
966 auto *class_node = qdb->findClassNode(class_name->split("::"_L1));
967 if (!class_node || searched_classes.contains(class_node))
968 continue;
969
970 searched_classes.insert(class_node);
971 NodeVector class_candidates;
972 class_node->findChildren(funcName, class_candidates);
973
974 for (Node *candidate : class_candidates) {
975 if (!candidate->isFunction(Genus::CPP))
976 continue;
977 if (static_cast<FunctionNode *>(candidate)->isHiddenFriend())
978 candidates.append(candidate);
979 }
980 }
981}
982
983/*
984 How a cursor is to be interpreted by findNodeForCursor().
985 */
987{
988 // Lookup of a declaration while parsing a header or source file.
990
991 // Lookup of a function signature written in a \fn command.
993};
994
995/*
996 How a function signature is to be matched by functionSignatureMatches().
997 */
999{
1000 // Ordinary matching: a genuine function template matches a signature
1001 // with a structurally substitutable leading template declaration, and
1002 // a non-template function matches a non-template signature.
1004
1005 // A \fn command may rename the genuine function template's binders too.
1006 // Declaration lookup retains its Q_QDOC spelling-based compatibility.
1008
1009 // The restricted hidden-friend-in-class-template interpretation of a
1010 // \fn command: in addition to the ordinary rules, a non-template
1011 // hidden friend in a class template matches a function template
1012 // signature whose leading template declaration describes the enclosing
1013 // class's template parameters, with the parameter names unified
1014 // positionally.
1016};
1017
1018/*
1019 Returns the type that \a parameter contributes to its function's type.
1020
1021 C++ drops top-level cv-qualifiers from parameter types, so
1022 \c {void f(const int)} and \c {void f(int)} declare the same function.
1023 Array element qualifiers become pointee qualifiers when the array decays,
1024 so array types are kept intact. Use this type only for lookup; recorded
1025 and rendered spellings keep the declared qualifiers.
1026 */
1027static clang::QualType parameterLookupType(const clang::ParmVarDecl *parameter)
1028{
1029 const clang::QualType type = parameter->getOriginalType();
1030 return type->isArrayType() ? type : type.getUnqualifiedType();
1031}
1032
1033// One parsed signature is compared with many candidates. Keep its Clang data
1034// and lazily computed spellings together for the lifetime of that lookup.
1036{
1037 CXCursor cursor;
1038 const clang::FunctionDecl *declaration;
1046
1047 QString typeSpelling(int index)
1048 {
1049 if (argumentSpellings.size() <= index)
1050 argumentSpellings.resize(index + 1);
1051 if (argumentSpellings.at(index).isEmpty()) {
1052 argumentSpellings[index] = QString::fromStdString(get_fully_qualified_type_name(
1053 declaration->getParamDecl(index)->getOriginalType(), declaration->getASTContext()));
1054 }
1055 return argumentSpellings.at(index);
1056 }
1057
1058 QString canonicalTypeSpelling(int index)
1059 {
1060 if (canonicalSpellings.size() <= index)
1061 canonicalSpellings.resize(index + 1);
1062 if (canonicalSpellings.at(index).isEmpty()) {
1063 canonicalSpellings[index] = QString::fromStdString(get_fully_qualified_type_name(
1064 parameterLookupType(declaration->getParamDecl(index)).getCanonicalType(),
1065 declaration->getASTContext()));
1066 }
1067 return canonicalSpellings.at(index);
1068 }
1069};
1070
1071/*!
1072 \internal
1073
1074 Returns \c true if the candidate \a fn matches the parsed \a signature.
1075
1076 Ordinary matching preserves declaration lookup, including Q_QDOC
1077 signatures. The hidden-friend mode additionally interprets the leading
1078 template declaration as enclosing-class context and compares parameter
1079 types using owned, binder-aware keys from Clang's canonical types.
1080 */
1082 FnSignatureMatchMode matchMode)
1083{
1084 const auto cur = signature.cursor;
1085 const auto *function_declaration = signature.declaration;
1086 int numArg = signature.numArgs;
1087 const bool isVariadic = signature.isVariadic;
1088 const auto &relaxed_template_declaration = signature.templateDeclaration;
1089 const bool compareTemplateTypes = matchMode == FnSignatureMatchMode::FnCommand
1090 && fn->templateDecl() && relaxed_template_declaration
1091 && !fn->templateParameterKey().isEmpty() && !signature.templateParameterKey.isEmpty();
1092 if (compareTemplateTypes && fn->templateParameterKey() != signature.templateParameterKey)
1093 return false;
1094 bool compareHiddenFriendTypes = false;
1095 if (!fn->templateDecl() && relaxed_template_declaration) {
1097 return false;
1098
1099 auto *enclosing = fn->parent();
1100 if (!enclosing || !enclosing->isClassNode())
1101 return false;
1102 const auto &classTemplateDecl = static_cast<ClassNode *>(enclosing)->templateDecl();
1103 if (!classTemplateDecl || fn->templateParameterKey().isEmpty()
1104 || fn->templateParameterKey() != signature.templateParameterKey)
1105 return false;
1106
1107 compareHiddenFriendTypes = true;
1108 } else if (fn->templateDecl() && !relaxed_template_declaration) {
1109 return false;
1110 } else if (fn->templateDecl() && relaxed_template_declaration) {
1111 if (!compareTemplateTypes
1112 && !are_template_declarations_substitutable(*fn->templateDecl(), *relaxed_template_declaration))
1113 return false;
1114 }
1115
1116 const Parameters &parameters = fn->parameters();
1117
1118 if (parameters.count() != numArg + isVariadic) {
1119 // Ignore possible last argument of type QPrivateSignal as it may have been dropped
1120 if (numArg > 0 && parameters.isPrivateSignal()
1121 && (parameters.isEmpty() || !parameters.last().type().endsWith(
1122 "QPrivateSignal"_L1))) {
1123 if (parameters.count() != --numArg + isVariadic)
1124 return false;
1125 } else {
1126 return false;
1127 }
1128 }
1129
1130 if (fn->isConst() != bool(clang_CXXMethod_isConst(cur)))
1131 return false;
1132
1133 if (isVariadic && parameters.last().type() != "..."_L1)
1134 return false;
1135
1136 if (fn->isRef() != (clang_Type_getCXXRefQualifier(clang_getCursorType(cur)) == CXRefQualifier_LValue))
1137 return false;
1138
1139 if (fn->isRefRef() != (clang_Type_getCXXRefQualifier(clang_getCursorType(cur)) == CXRefQualifier_RValue))
1140 return false;
1141
1142 bool typesDiffer = false;
1143 for (int i = 0; i < numArg; ++i) {
1144 auto *paramDecl = function_declaration->getParamDecl(i);
1145 auto paramType = paramDecl->getOriginalType();
1146
1147 if (compareHiddenFriendTypes || compareTemplateTypes) {
1148#if LIBCLANG_VERSION_MAJOR >= 21
1149 if (compareHiddenFriendTypes && function_declaration->getTrailingRequiresClause().ConstraintExpr)
1150#else
1151 if (compareHiddenFriendTypes && function_declaration->getTrailingRequiresClause())
1152#endif
1153 return false;
1154 const auto &recordedKeys = fn->templateParameterTypeKeys();
1155 if (i < recordedKeys.size() && i < signature.templateTypeKeys.size()
1156 && !recordedKeys.at(i).isEmpty() && !signature.templateTypeKeys.at(i).isEmpty()) {
1157 if (recordedKeys.at(i) != signature.templateTypeKeys.at(i))
1158 return false;
1159 continue;
1160 }
1161 // Unsupported types retain ordinary matching, but the restricted
1162 // hidden-friend convention must never guess their equivalence.
1163 if (compareHiddenFriendTypes)
1164 return false;
1165 }
1166
1167 QString recordedType = parameters.at(i).type();
1168 QString typeSpelling = signature.typeSpelling(i);
1169
1170 typesDiffer = recordedType != typeSpelling;
1171
1172 // Retry with a canonical type spelling unless the parameter is a bare
1173 // template type parameter, such as T but not const T& or MyContainer<T>.
1174 // Wrapped forms are safe because both sides of the comparison are
1175 // canonicalized in the same way. Exclude bare TemplateTypeParmType
1176 // because canonicalization removes the spelled Q_QDOC template
1177 // parameter name and can make distinct Q_QDOC-declared signatures
1178 // appear identical during matching.
1179 if (typesDiffer) {
1180 const bool isBareTemplateTypeParm =
1181 paramType.getTypePtrOrNull()
1182 && llvm::isa<clang::TemplateTypeParmType>(paramType.getTypePtr());
1183 if (!isBareTemplateTypeParm) {
1184 QStringView canonicalType = parameters.at(i).canonicalType();
1185 // An empty canonical type means that the recorded spelling
1186 // already names the canonical lookup type.
1187 if (canonicalType.isEmpty())
1188 canonicalType = recordedType;
1189 typesDiffer = canonicalType != signature.canonicalTypeSpelling(i);
1190 }
1191 }
1192
1193 if (typesDiffer) {
1194 break;
1195 }
1196 }
1197
1198 return !typesDiffer;
1199}
1200
1201static Node *findNodeForCursor(QDocDatabase *qdb, CXCursor cur);
1202
1203// Function lookup has one result channel. Declaration lookup below adapts it
1204// to Node*, but the \fn path must carry ambiguity all the way to the parser.
1206{
1207 Node *p = findNodeForCursor(qdb, clang_getCursorSemanticParent(cur));
1208 if (!p || !p->isAggregate())
1209 return {};
1210 auto *parent = static_cast<Aggregate *>(p);
1211 NodeVector candidates;
1212 parent->findChildren(functionName(cur), candidates);
1213 // Hidden friends are recorded under their lexical parent in the database.
1214 const auto *cur_decl = get_cursor_declaration(cur);
1215 if (candidates.isEmpty() && cur_decl && cur_decl->getFriendObjectKind() != clang::Decl::FOK_None) {
1216 if (auto *lexical_parent = findNodeForCursor(qdb, clang_getCursorLexicalParent(cur));
1217 lexical_parent && lexical_parent->isAggregate() && lexical_parent != parent)
1218 static_cast<Aggregate *>(lexical_parent)->findChildren(functionName(cur), candidates);
1219 }
1220
1221 // A broad same-named template must not suppress the hidden-friend search.
1222 const bool hasHiddenFriend = std::any_of(candidates.cbegin(), candidates.cend(), [](const Node *n) {
1223 return n->isFunction(Genus::CPP) && static_cast<const FunctionNode *>(n)->isHiddenFriend();
1224 });
1225 const auto *function_declaration = cur_decl ? cur_decl->getAsFunction() : nullptr;
1226 if (!hasHiddenFriend && function_declaration)
1227 findHiddenFriendCandidates(qdb, functionName(cur), function_declaration, candidates);
1228 if (candidates.isEmpty() || !function_declaration)
1229 return {};
1230
1231 const auto funcType = clang_getCursorType(cur);
1232 FunctionCursorSignature signature{ cur, function_declaration, clang_getNumArgTypes(funcType),
1233 bool(clang_isFunctionTypeVariadic(funcType)), {}, {}, {}, {}, {} };
1234 if (clang_getCursorKind(cur) == CXCursor_FunctionTemplate) {
1235 const auto *functionTemplate = function_declaration->getDescribedFunctionTemplate();
1236 signature.templateDeclaration = get_template_declaration(functionTemplate);
1237 if (mode == NodeLookupMode::FnCommand) {
1238 signature.templateParameterKey = templateParameterKey(*functionTemplate->getTemplateParameters());
1239 for (const auto *param : function_declaration->parameters())
1240 signature.templateTypeKeys.append(hiddenFriendTypeKey(
1241 parameterLookupType(param), *functionTemplate->getTemplateParameters()));
1242 }
1243 }
1244
1245 return resolveFnLookupCandidates(candidates, [&](Node *candidate) {
1246 return candidate->isFunction(Genus::CPP)
1247 && functionSignatureMatches(static_cast<FunctionNode *>(candidate), signature,
1248 FnSignatureMatchMode::Ordinary);
1249 }, [&](Node *candidate) {
1250 return mode == NodeLookupMode::FnCommand && candidate->isFunction(Genus::CPP)
1251 && functionSignatureMatches(static_cast<FunctionNode *>(candidate), signature,
1252 FnSignatureMatchMode::FnCommand);
1253 }, [&](Node *candidate) {
1254 return mode == NodeLookupMode::FnCommand && signature.templateDeclaration
1255 && candidate->isFunction(Genus::CPP)
1256 && functionSignatureMatches(static_cast<FunctionNode *>(candidate), signature,
1257 FnSignatureMatchMode::HiddenFriendInClassTemplate);
1258 });
1259}
1260
1261/*!
1262 Find the node in \a qdb corresponding to the declaration at \a cur.
1263 This declaration-only adapter deliberately does not enable \fn conventions.
1264 */
1265static Node *findNodeForCursor(QDocDatabase *qdb, CXCursor cur)
1266{
1267 auto kind = clang_getCursorKind(cur);
1268 if (clang_isInvalid(kind))
1269 return nullptr;
1270 if (kind == CXCursor_TranslationUnit)
1271 return qdb->primaryTreeRoot();
1272
1273 switch (kind) {
1274 case CXCursor_FunctionDecl:
1275 case CXCursor_FunctionTemplate:
1276 case CXCursor_CXXMethod:
1277 case CXCursor_Constructor:
1278 case CXCursor_Destructor:
1279 case CXCursor_ConversionFunction:
1280 return findFunctionForCursor(qdb, cur, NodeLookupMode::Declaration).node();
1281 default:
1282 break;
1283 }
1284
1285 Node *p = findNodeForCursor(qdb, clang_getCursorSemanticParent(cur));
1286 // Special case; if the cursor represents a template type|non-type|template parameter
1287 // and its semantic parent is a function, return a pointer to the function node.
1288 if (p && p->isFunction(Genus::CPP)) {
1289 switch (kind) {
1290 case CXCursor_TemplateTypeParameter:
1291 case CXCursor_NonTypeTemplateParameter:
1292 case CXCursor_TemplateTemplateParameter:
1293 return p;
1294 default:
1295 break;
1296 }
1297 }
1298
1299 // ...otherwise, the semantic parent must be an Aggregate node.
1300 if (!p || !p->isAggregate())
1301 return nullptr;
1302 auto parent = static_cast<Aggregate *>(p);
1303
1304 QString name;
1305 if (clang_Cursor_isAnonymous(cur)) {
1306 name = Utilities::uniqueIdentifier(
1307 fromCXSourceLocation(clang_getCursorLocation(cur)),
1308 QLatin1String("anonymous"));
1309 } else {
1310 name = fromCXString(clang_getCursorSpelling(cur));
1311 }
1312 switch (kind) {
1313 case CXCursor_Namespace:
1314 return parent->findNonfunctionChild(name, &Node::isNamespace);
1315 case CXCursor_StructDecl:
1316 case CXCursor_ClassDecl:
1317 case CXCursor_UnionDecl:
1318 case CXCursor_ClassTemplate:
1319 return parent->findNonfunctionChild(name, &Node::isClassNode);
1320 case CXCursor_EnumDecl:
1321 return parent->findNonfunctionChild(name, &Node::isEnumType);
1322 case CXCursor_FieldDecl:
1323 case CXCursor_VarDecl:
1324 return parent->findNonfunctionChild(name, &Node::isVariable);
1325 case CXCursor_TypedefDecl:
1326 return parent->findNonfunctionChild(name, &Node::isTypedef);
1327 default:
1328 return nullptr;
1329 }
1330}
1331
1332static void setOverridesForFunction(FunctionNode *fn, CXCursor cursor)
1333{
1334 CXCursor *overridden;
1335 unsigned int numOverridden = 0;
1336 clang_getOverriddenCursors(cursor, &overridden, &numOverridden);
1337 for (uint i = 0; i < numOverridden; ++i) {
1338 QString path = reconstructQualifiedPathForCursor(overridden[i]);
1339 if (!path.isEmpty()) {
1340 fn->setOverride(true);
1341 fn->setOverridesThis(path);
1342 break;
1343 }
1344 }
1345 clang_disposeOverriddenCursors(overridden);
1346}
1347
1349{
1350public:
1351 ClangVisitor(QDocDatabase *qdb, const std::set<Config::HeaderFilePath> &allHeaders,
1352 const Config::InternalFilePatterns& internalFilePatterns)
1353 : qdb_(qdb), parent_(qdb->primaryTreeRoot()),
1354 internalFilePatterns_(internalFilePatterns)
1355 {
1356 std::transform(allHeaders.cbegin(), allHeaders.cend(), std::inserter(allHeaders_, allHeaders_.begin()),
1357 [](const auto& header_file_path) -> const QString& { return header_file_path.filename; });
1358 }
1359
1360 QDocDatabase *qdocDB() { return qdb_; }
1361
1362 CXChildVisitResult visitChildren(CXCursor cursor)
1363 {
1364 auto ret = visitChildrenLambda(cursor, [&](CXCursor cur) {
1365 auto loc = clang_getCursorLocation(cur);
1366 if (clang_Location_isFromMainFile(loc))
1367 return visitSource(cur, loc);
1368
1369 CXFile file;
1370 clang_getFileLocation(loc, &file, nullptr, nullptr, nullptr);
1371 bool isInteresting = false;
1372 auto it = isInterestingCache_.find(file);
1373 if (it != isInterestingCache_.end()) {
1374 isInteresting = *it;
1375 } else {
1376 QFileInfo fi(fromCXString(clang_getFileName(file)));
1377 // Match by file name in case of PCH/installed headers
1378 isInteresting = allHeaders_.find(fi.fileName()) != allHeaders_.end();
1379 isInterestingCache_[file] = isInteresting;
1380 }
1381 if (isInteresting) {
1382 return visitHeader(cur, loc);
1383 }
1384
1385 return CXChildVisit_Continue;
1386 });
1387 return ret ? CXChildVisit_Break : CXChildVisit_Continue;
1388 }
1389
1390 /*
1391 Not sure about all the possibilities, when the cursor
1392 location is not in the main file.
1393 */
1395 {
1396 FnLookupResult result;
1397 visitChildrenLambda(cursor, [&](CXCursor cur) {
1398 auto loc = clang_getCursorLocation(cur);
1399 if (clang_Location_isFromMainFile(loc))
1400 return visitFnSignature(cur, loc, result);
1401 return CXChildVisit_Continue;
1402 });
1403 return result;
1404 }
1405
1406 Node *nodeForCommentAtLocation(CXSourceLocation loc, CXSourceLocation nextCommentLoc);
1407
1408private:
1409 QmlNativeTypeAttribute detectQmlNativeTypeAttribute(CXCursor cursor);
1410 /*!
1411 SimpleLoc represents a simple location in the main source file,
1412 which can be used as a key in a QMap.
1413 */
1414 struct SimpleLoc
1415 {
1416 unsigned int line {}, column {};
1417 friend bool operator<(const SimpleLoc &a, const SimpleLoc &b)
1418 {
1419 return a.line != b.line ? a.line < b.line : a.column < b.column;
1420 }
1421 };
1422 /*!
1423 \variable ClangVisitor::declMap_
1424 Map of all the declarations in the source file so we can match them
1425 with a documentation comment.
1426 */
1427 QMap<SimpleLoc, CXCursor> declMap_;
1428
1429 QDocDatabase *qdb_;
1430 Aggregate *parent_;
1431 std::set<QString> allHeaders_;
1432 QHash<CXFile, bool> isInterestingCache_; // doing a canonicalFilePath is slow, so keep a cache.
1433 const Config::InternalFilePatterns& internalFilePatterns_;
1434
1435 /*!
1436 Returns true if the symbol should be ignored for the documentation.
1437 */
1438 bool ignoredSymbol(const QString &symbolName)
1439 {
1440 if (symbolName == QLatin1String("QPrivateSignal"))
1441 return true;
1442 // Ignore functions generated by property macros
1443 if (symbolName.startsWith("_qt_property_"))
1444 return true;
1445 // Ignore template argument deduction guides
1446 if (symbolName.startsWith("<deduction guide"))
1447 return true;
1448 return false;
1449 }
1450
1451 CXChildVisitResult visitSource(CXCursor cursor, CXSourceLocation loc);
1452 CXChildVisitResult visitHeader(CXCursor cursor, CXSourceLocation loc);
1453 CXChildVisitResult visitFnSignature(CXCursor cursor, CXSourceLocation loc,
1454 FnLookupResult &result);
1455 void processFunction(FunctionNode *fn, CXCursor cursor);
1456 bool parseProperty(const QString &spelling, const Location &loc);
1457 void readParameterNamesAndAttributes(FunctionNode *fn, CXCursor cursor);
1458 Aggregate *getSemanticParent(CXCursor cursor);
1459};
1460
1461/*!
1462 Detects if a class cursor contains declarations specific to QML types:
1463
1464 \details {QML_SINGLETON macro}
1465 Returns QmlNativeTypeAttribute::Singleton if the macro is detected.
1466
1467 The \e QML_SINGLETON macro expands to multiple items including:
1468 \list
1469 \li \c {Q_CLASSINFO("QML.Singleton", "true")}
1470 \li \c {enum class QmlIsSingleton}
1471 \endlist
1472 \enddetails
1473
1474 \details {QML_UNCREATABLE macro}
1475 Returns ClassNode::QmlNativeTypeAttribute::Uncreatable if the macro is detected.
1476
1477 The \e QML_UNCREATABLE macro expands to multiple items including:
1478 \list
1479 \li \c {Q_CLASSINFO("QML.Creatable", "false")}
1480 \li \c {enum class QmlIsUncreatable}
1481 \endlist
1482 \enddetails
1483
1484 This method looks for the above expansion artifacts to detect the macros.
1485 If no artifacts are found, returns QmlNativeTypeAttribute::None
1486 (that is, a standard instantiable QML type).
1487*/
1488QmlNativeTypeAttribute ClangVisitor::detectQmlNativeTypeAttribute(CXCursor cursor)
1489{
1491
1492 visitChildrenLambda(cursor, [&attr](CXCursor child) -> CXChildVisitResult {
1493 // Look for Q_CLASSINFO calls that indicate QML.Singleton or QML.Creatable = false
1494 if (clang_getCursorKind(child) == CXCursor_CallExpr) {
1495 CXSourceRange range = clang_getCursorExtent(child);
1496 QString sourceText = getSpelling(range);
1497 static const QRegularExpression qmlClassInfoPattern(
1498 R"(Q_CLASSINFO\s*\‍(\s*["\']QML\.(Singleton|Creatable)["\']\s*,\s*["\'](true|false)["\']\s*\‍))");
1499 const auto match = qmlClassInfoPattern.match(sourceText);
1500 if (match.hasMatch()) {
1501 if (match.captured(1) == "Singleton"_L1 && match.captured(2) == "true"_L1) {
1503 return CXChildVisit_Break;
1504 } else if (match.captured(1) == "Creatable"_L1 && match.captured(2) == "false"_L1) {
1506 return CXChildVisit_Break;
1507 }
1508 }
1509 }
1510
1511 // Also check for enum class QmlIsSingleton which is part of the macro expansion
1512 if (clang_getCursorKind(child) == CXCursor_EnumDecl) {
1513 QString spelling = fromCXString(clang_getCursorSpelling(child));
1514 if (spelling == "QmlIsSingleton"_L1) {
1516 return CXChildVisit_Break;
1517 } else if (spelling == "QmlIsUncreatable"_L1) {
1519 return CXChildVisit_Break;
1520 }
1521 }
1522
1523 return CXChildVisit_Continue;
1524 });
1525
1526 return attr;
1527}
1528
1529/*!
1530 Visits a cursor in the .cpp file.
1531 This fills the declMap_
1532 */
1533CXChildVisitResult ClangVisitor::visitSource(CXCursor cursor, CXSourceLocation loc)
1534{
1535 auto kind = clang_getCursorKind(cursor);
1536 if (clang_isDeclaration(kind)) {
1537 SimpleLoc l;
1538 clang_getPresumedLocation(loc, nullptr, &l.line, &l.column);
1539 declMap_.insert(l, cursor);
1540 return CXChildVisit_Recurse;
1541 }
1542 return CXChildVisit_Continue;
1543}
1544
1545/*!
1546 If the semantic and lexical parent cursors of \a cursor are
1547 not the same, find the Aggregate node for the semantic parent
1548 cursor and return it. Otherwise return the current parent.
1549 */
1550Aggregate *ClangVisitor::getSemanticParent(CXCursor cursor)
1551{
1552 CXCursor sp = clang_getCursorSemanticParent(cursor);
1553 CXCursor lp = clang_getCursorLexicalParent(cursor);
1554 if (!clang_equalCursors(sp, lp) && clang_isDeclaration(clang_getCursorKind(sp))) {
1555 Node *spn = findNodeForCursor(qdb_, sp);
1556 if (spn && spn->isAggregate()) {
1557 return static_cast<Aggregate *>(spn);
1558 }
1559 }
1560 return parent_;
1561}
1562
1563CXChildVisitResult ClangVisitor::visitFnSignature(CXCursor cursor, CXSourceLocation,
1564 FnLookupResult &result)
1565{
1566 switch (clang_getCursorKind(cursor)) {
1567 case CXCursor_Namespace:
1568 return CXChildVisit_Recurse;
1569 case CXCursor_FunctionDecl:
1570 case CXCursor_FunctionTemplate:
1571 case CXCursor_CXXMethod:
1572 case CXCursor_Constructor:
1573 case CXCursor_Destructor:
1574 case CXCursor_ConversionFunction: {
1575 result.reset();
1576 if (ignoredSymbol(functionName(cursor))) {
1577 result.setIgnored();
1578 } else {
1579 result = findFunctionForCursor(qdb_, cursor, NodeLookupMode::FnCommand);
1580 if (result.hasMatch()) {
1581 if (result.node()->isFunction(Genus::CPP)) {
1582 auto *fn = static_cast<FunctionNode *>(result.node());
1583 readParameterNamesAndAttributes(fn, cursor);
1584
1585 const clang::Decl* declaration = get_cursor_declaration(cursor);
1586 assert(declaration);
1587 if (const auto function_declaration = declaration->getAsFunction()) {
1588 auto declaredReturnType = function_declaration->getDeclaredReturnType();
1589 if (llvm::dyn_cast_if_present<clang::AutoType>(declaredReturnType.getTypePtrOrNull()))
1590 fn->setDeclaredReturnType(QString::fromStdString(declaredReturnType.getAsString()));
1591 }
1592 }
1593 } else if (!result.isAmbiguous()) { // Possibly an implicitly generated special member
1594 QString name = functionName(cursor);
1595 if (ignoredSymbol(name))
1596 return CXChildVisit_Continue;
1597 Aggregate *semanticParent = getSemanticParent(cursor);
1598 if (semanticParent && semanticParent->isClass()) {
1599 auto *candidate = new FunctionNode(nullptr, name);
1600 processFunction(candidate, cursor);
1601 if (!candidate->isSpecialMemberFunction()
1602 || (candidate->isCtor() && !candidate->parameters().isEmpty())) {
1603 delete candidate;
1604 return CXChildVisit_Continue;
1605 }
1606 candidate->setImplicitlyGenerated(true);
1607 semanticParent->addChild(candidate);
1608 result.setMatched(candidate);
1609 }
1610 }
1611 }
1612 break;
1613 }
1614 default:
1615 break;
1616 }
1617 return CXChildVisit_Continue;
1618}
1619
1620CXChildVisitResult ClangVisitor::visitHeader(CXCursor cursor, CXSourceLocation loc)
1621{
1622 auto kind = clang_getCursorKind(cursor);
1623
1624 switch (kind) {
1625 case CXCursor_TypeAliasTemplateDecl:
1626 case CXCursor_TypeAliasDecl: {
1627 const QString aliasName = fromCXString(clang_getCursorSpelling(cursor));
1628 QString aliasedType;
1629
1630 const auto *templateDecl = (kind == CXCursor_TypeAliasTemplateDecl)
1631 ? llvm::dyn_cast<clang::TemplateDecl>(get_cursor_declaration(cursor))
1632 : nullptr;
1633
1634 if (kind == CXCursor_TypeAliasTemplateDecl) {
1635 // For template aliases, get the underlying TypeAliasDecl from the TemplateDecl
1636 if (const auto *aliasTemplate = llvm::dyn_cast<clang::TypeAliasTemplateDecl>(templateDecl)) {
1637 if (const auto *aliasDecl = aliasTemplate->getTemplatedDecl()) {
1638 clang::QualType underlyingType = aliasDecl->getUnderlyingType();
1639 aliasedType = QString::fromStdString(underlyingType.getAsString());
1640 }
1641 }
1642 } else {
1643 // For non-template aliases, get the underlying type via C API
1644 const CXType aliasedCXType = clang_getTypedefDeclUnderlyingType(cursor);
1645 if (aliasedCXType.kind != CXType_Invalid) {
1646 aliasedType = fromCXString(clang_getTypeSpelling(aliasedCXType));
1647 }
1648 }
1649
1650 if (!aliasedType.isEmpty()) {
1651 auto *ta = new TypeAliasNode(parent_, aliasName, aliasedType);
1652 ta->setAccess(fromCX_CXXAccessSpecifier(clang_getCXXAccessSpecifier(cursor)));
1653 ta->setLocation(fromCXSourceLocation(clang_getCursorLocation(cursor)));
1654
1655 if (templateDecl)
1656 ta->setTemplateDecl(get_template_declaration(templateDecl));
1657 }
1658 return CXChildVisit_Continue;
1659 }
1660 case CXCursor_StructDecl:
1661 case CXCursor_UnionDecl:
1662 if (fromCXString(clang_getCursorSpelling(cursor)).isEmpty()) // anonymous struct or union
1663 return CXChildVisit_Continue;
1664 Q_FALLTHROUGH();
1665 case CXCursor_ClassTemplate:
1666 Q_FALLTHROUGH();
1667 case CXCursor_ClassDecl: {
1668 if (!clang_isCursorDefinition(cursor))
1669 return CXChildVisit_Continue;
1670
1671 if (findNodeForCursor(qdb_, cursor)) // Was already parsed, probably in another TU
1672 return CXChildVisit_Continue;
1673
1674 QString className = cleanAnonymousTypeName(fromCXString(clang_getCursorSpelling(cursor)));
1675
1676 Aggregate *semanticParent = getSemanticParent(cursor);
1677 if (semanticParent && semanticParent->findNonfunctionChild(className, &Node::isClassNode)) {
1678 return CXChildVisit_Continue;
1679 }
1680
1681 CXCursorKind actualKind = (kind == CXCursor_ClassTemplate) ?
1682 clang_getTemplateCursorKind(cursor) : kind;
1683
1685 if (actualKind == CXCursor_StructDecl)
1686 type = NodeType::Struct;
1687 else if (actualKind == CXCursor_UnionDecl)
1688 type = NodeType::Union;
1689
1690 auto *classe = new ClassNode(type, semanticParent, className);
1691 classe->setAccess(fromCX_CXXAccessSpecifier(clang_getCXXAccessSpecifier(cursor)));
1692
1693 auto location = fromCXSourceLocation(clang_getCursorLocation(cursor));
1694 classe->setLocation(location);
1695
1696 if (!internalFilePatterns_.exactMatches.isEmpty() || !internalFilePatterns_.globPatterns.isEmpty()
1697 || !internalFilePatterns_.regexPatterns.isEmpty()) {
1698 if (Config::matchesInternalFilePattern(location.filePath(), internalFilePatterns_))
1699 classe->setStatus(Status::Internal);
1700 }
1701
1702 classe->setAnonymous(clang_Cursor_isAnonymous(cursor));
1703 classe->setQmlNativeTypeAttribute(detectQmlNativeTypeAttribute(cursor));
1704
1705 if (kind == CXCursor_ClassTemplate) {
1706 auto template_declaration = llvm::dyn_cast<clang::TemplateDecl>(get_cursor_declaration(cursor));
1707 classe->setTemplateDecl(get_template_declaration(template_declaration));
1708 }
1709
1710 QScopedValueRollback<Aggregate *> setParent(parent_, classe);
1711 return visitChildren(cursor);
1712 }
1713 case CXCursor_CXXBaseSpecifier: {
1714 if (!parent_->isClassNode())
1715 return CXChildVisit_Continue;
1716 auto access = fromCX_CXXAccessSpecifier(clang_getCXXAccessSpecifier(cursor));
1717 auto type = clang_getCursorType(cursor);
1718 auto baseCursor = clang_getTypeDeclaration(type);
1719 auto baseNode = findNodeForCursor(qdb_, baseCursor);
1720 auto classe = static_cast<ClassNode *>(parent_);
1721 if (baseNode == nullptr || !baseNode->isClassNode()) {
1722 QString bcName = reconstructQualifiedPathForCursor(baseCursor);
1723 classe->addUnresolvedBaseClass(access,
1724 bcName.split(QLatin1String("::"), Qt::SkipEmptyParts));
1725 return CXChildVisit_Continue;
1726 }
1727 auto baseClasse = static_cast<ClassNode *>(baseNode);
1728 classe->addResolvedBaseClass(access, baseClasse);
1729 return CXChildVisit_Continue;
1730 }
1731 case CXCursor_Namespace: {
1732 QString namespaceName = fromCXString(clang_getCursorDisplayName(cursor));
1733 NamespaceNode *ns = nullptr;
1734 if (parent_)
1735 ns = static_cast<NamespaceNode *>(
1736 parent_->findNonfunctionChild(namespaceName, &Node::isNamespace));
1737 if (!ns) {
1738 ns = new NamespaceNode(parent_, namespaceName);
1739 ns->setAccess(Access::Public);
1740 ns->setLocation(fromCXSourceLocation(clang_getCursorLocation(cursor)));
1741 }
1742 QScopedValueRollback<Aggregate *> setParent(parent_, ns);
1743 return visitChildren(cursor);
1744 }
1745 case CXCursor_LinkageSpec:
1746 return visitChildren(cursor);
1747 case CXCursor_FunctionTemplate:
1748 Q_FALLTHROUGH();
1749 case CXCursor_FunctionDecl:
1750 case CXCursor_CXXMethod:
1751 case CXCursor_Constructor:
1752 case CXCursor_Destructor:
1753 case CXCursor_ConversionFunction: {
1754 // Template instantiations belong to the template they come from.
1755 // Clang reports the ones it creates while parsing, such as a class
1756 // template's hidden friend used in a constant expression, as
1757 // top-level declarations. As root-level nodes, they would shadow the
1758 // real candidates in \fn lookup.
1759 if (const auto *declaration = get_cursor_declaration(cursor)->getAsFunction();
1760 declaration && declaration->isTemplateInstantiation())
1761 return CXChildVisit_Continue;
1762
1763 if (findNodeForCursor(qdb_, cursor)) // Was already parsed, probably in another TU
1764 return CXChildVisit_Continue;
1765 QString name = functionName(cursor);
1766 if (ignoredSymbol(name))
1767 return CXChildVisit_Continue;
1768 // constexpr constructors generate also a global instance; ignore
1769 if (kind == CXCursor_Constructor && parent_ == qdb_->primaryTreeRoot())
1770 return CXChildVisit_Continue;
1771
1772 auto *fn = new FunctionNode(parent_, name);
1773 CXSourceRange range = clang_Cursor_getCommentRange(cursor);
1774 if (!clang_Range_isNull(range)) {
1775 QString comment = getSpelling(range);
1776 if (comment.startsWith("//!")) {
1777 qsizetype tag = comment.indexOf(QChar('['));
1778 if (tag > 0) {
1779 qsizetype end = comment.indexOf(QChar(']'), ++tag);
1780 if (end > 0)
1781 fn->setTag(comment.mid(tag, end - tag));
1782 }
1783 }
1784 }
1785
1786 processFunction(fn, cursor);
1787
1788 if (kind == CXCursor_FunctionTemplate) {
1789 auto template_declaration = get_cursor_declaration(cursor)->getAsFunction()->getDescribedFunctionTemplate();
1790 fn->setTemplateDecl(get_template_declaration(template_declaration));
1791 }
1792
1793 if (!clang_Location_isInSystemHeader(loc))
1794 fn->autoGenerateSmfDoc(parent_->name());
1795
1796 return CXChildVisit_Continue;
1797 }
1798#if CINDEX_VERSION >= 36
1799 case CXCursor_FriendDecl: {
1800 return visitChildren(cursor);
1801 }
1802#endif
1803 case CXCursor_EnumDecl: {
1804 auto *en = static_cast<EnumNode *>(findNodeForCursor(qdb_, cursor));
1805 if (en && en->items().size())
1806 return CXChildVisit_Continue; // Was already parsed, probably in another TU
1807
1808 QString enumTypeName = fromCXString(clang_getCursorSpelling(cursor));
1809
1810 if (clang_Cursor_isAnonymous(cursor)) {
1811 enumTypeName = "anonymous";
1812 // Generate a unique name to enable auto-tying doc comments in headers
1813 // to anonymous enum declarations
1814 if (Config::instance().get(CONFIG_DOCUMENTATIONINHEADERS).asBool())
1815 enumTypeName = Utilities::uniqueIdentifier(fromCXSourceLocation(clang_getCursorLocation(cursor)), enumTypeName);
1816 if (parent_ && (parent_->isClassNode() || parent_->isNamespace())) {
1817 Node *n = parent_->findNonfunctionChild(enumTypeName, &Node::isEnumType);
1818 if (n)
1819 en = static_cast<EnumNode *>(n);
1820 }
1821 }
1822 if (!en) {
1823 en = new EnumNode(parent_, enumTypeName, clang_EnumDecl_isScoped(cursor));
1824 en->setAccess(fromCX_CXXAccessSpecifier(clang_getCXXAccessSpecifier(cursor)));
1825 en->setLocation(fromCXSourceLocation(clang_getCursorLocation(cursor)));
1826 en->setAnonymous(clang_Cursor_isAnonymous(cursor));
1827 }
1828
1829 // Enum values
1830 visitChildrenLambda(cursor, [&](CXCursor cur) {
1831 if (clang_getCursorKind(cur) != CXCursor_EnumConstantDecl)
1832 return CXChildVisit_Continue;
1833
1834 QString value;
1835 visitChildrenLambda(cur, [&](CXCursor cur) {
1836 if (clang_isExpression(clang_getCursorKind(cur))) {
1837 value = getSpelling(clang_getCursorExtent(cur));
1838 return CXChildVisit_Break;
1839 }
1840 return CXChildVisit_Continue;
1841 });
1842 if (value.isEmpty()) {
1843 QLatin1String hex("0x");
1844 if (!en->items().isEmpty() && en->items().last().value().startsWith(hex)) {
1845 value = hex + QString::number(clang_getEnumConstantDeclValue(cur), 16);
1846 } else {
1847 value = QString::number(clang_getEnumConstantDeclValue(cur));
1848 }
1849 }
1850
1851 en->addItem(EnumItem(fromCXString(clang_getCursorSpelling(cur)), std::move(value)));
1852 return CXChildVisit_Continue;
1853 });
1854 return CXChildVisit_Continue;
1855 }
1856 case CXCursor_FieldDecl:
1857 case CXCursor_VarDecl: {
1858 if (findNodeForCursor(qdb_, cursor)) // Was already parsed, probably in another TU
1859 return CXChildVisit_Continue;
1860
1861 auto value_declaration =
1862 llvm::dyn_cast<clang::ValueDecl>(get_cursor_declaration(cursor));
1863 assert(value_declaration);
1864
1865 auto access = fromCX_CXXAccessSpecifier(clang_getCXXAccessSpecifier(cursor));
1866 auto var = new VariableNode(parent_, fromCXString(clang_getCursorSpelling(cursor)));
1867
1868 var->setAccess(access);
1869 var->setLocation(fromCXSourceLocation(clang_getCursorLocation(cursor)));
1870 var->setLeftType(QString::fromStdString(get_fully_qualified_type_name(
1871 value_declaration->getType(),
1872 value_declaration->getASTContext()
1873 )));
1874 var->setStatic(kind == CXCursor_VarDecl && parent_->isClassNode());
1875
1876 return CXChildVisit_Continue;
1877 }
1878 case CXCursor_TypedefDecl: {
1879 if (findNodeForCursor(qdb_, cursor)) // Was already parsed, probably in another TU
1880 return CXChildVisit_Continue;
1881 auto *td = new TypedefNode(parent_, fromCXString(clang_getCursorSpelling(cursor)));
1882 td->setAccess(fromCX_CXXAccessSpecifier(clang_getCXXAccessSpecifier(cursor)));
1883 td->setLocation(fromCXSourceLocation(clang_getCursorLocation(cursor)));
1884 // Search to see if this is a Q_DECLARE_FLAGS (if the type is QFlags<ENUM>)
1885 visitChildrenLambda(cursor, [&](CXCursor cur) {
1886 if (clang_getCursorKind(cur) != CXCursor_TemplateRef
1887 || fromCXString(clang_getCursorSpelling(cur)) != QLatin1String("QFlags"))
1888 return CXChildVisit_Continue;
1889 // Found QFlags<XXX>
1890 visitChildrenLambda(cursor, [&](CXCursor cur) {
1891 if (clang_getCursorKind(cur) != CXCursor_TypeRef)
1892 return CXChildVisit_Continue;
1893 auto *en =
1894 findNodeForCursor(qdb_, clang_getTypeDeclaration(clang_getCursorType(cur)));
1895 if (en && en->isEnumType())
1896 static_cast<EnumNode *>(en)->setFlagsType(td);
1897 return CXChildVisit_Break;
1898 });
1899 return CXChildVisit_Break;
1900 });
1901 return CXChildVisit_Continue;
1902 }
1903 default:
1904 if (clang_isDeclaration(kind) && parent_->isClassNode()) {
1905 // may be a property macro or a static_assert
1906 // which is not exposed from the clang API
1907 parseProperty(getSpelling(clang_getCursorExtent(cursor)),
1909 }
1910 return CXChildVisit_Continue;
1911 }
1912}
1913
1914void ClangVisitor::readParameterNamesAndAttributes(FunctionNode *fn, CXCursor cursor)
1915{
1916 Parameters &parameters = fn->parameters();
1917 // Visit the parameters and attributes
1918 int i = 0;
1919 visitChildrenLambda(cursor, [&](CXCursor cur) {
1920 auto kind = clang_getCursorKind(cur);
1921 if (kind == CXCursor_AnnotateAttr) {
1922 QString annotation = fromCXString(clang_getCursorDisplayName(cur));
1923 if (annotation == QLatin1String("qt_slot")) {
1925 } else if (annotation == QLatin1String("qt_signal")) {
1927 }
1928 if (annotation == QLatin1String("qt_invokable"))
1929 fn->setInvokable(true);
1930 } else if (kind == CXCursor_CXXOverrideAttr) {
1931 fn->setOverride(true);
1932 } else if (kind == CXCursor_ParmDecl) {
1933 if (i >= parameters.count())
1934 return CXChildVisit_Break; // Attributes comes before parameters so we can break.
1935
1936 if (QString name = fromCXString(clang_getCursorSpelling(cur)); !name.isEmpty())
1937 parameters[i].setName(name);
1938
1939 const clang::ParmVarDecl* parameter_declaration = llvm::dyn_cast<const clang::ParmVarDecl>(get_cursor_declaration(cur));
1940 Q_ASSERT(parameter_declaration);
1941
1942 std::string default_value = get_default_value_initializer_as_string(parameter_declaration);
1943
1944 if (!default_value.empty())
1945 parameters[i].setDefaultValue(QString::fromStdString(default_value));
1946
1947 ++i;
1948 }
1949 return CXChildVisit_Continue;
1950 });
1951}
1952
1953/*
1954 Follows \a location, a token in a macro expansion, to its place in the
1955 body of the expanded macro. For a token passed as a macro argument,
1956 that's where the macro's parameter appears.
1957*/
1958static clang::SourceLocation macroBodyLocation(const clang::SourceManager &sourceManager,
1959 clang::SourceLocation location)
1960{
1961 while (sourceManager.isMacroArgExpansion(location))
1962 location = sourceManager.getImmediateExpansionRange(location).getBegin();
1963 return location;
1964}
1965
1966/*
1967 Returns \c true if the source text from \a location up to \a end may
1968 declare a function constexpr. That's the case if it contains a
1969 \c constexpr or \c consteval specifier, or a macro that might expand to
1970 one, other than the macro at \a readMacro, whose definition has been
1971 read already. Without an \a end, reads to the end of the line, which
1972 for a token in a macro definition is the end of the definition.
1973*/
1974static bool mayDeclareConstexpr(const clang::ASTContext &context, clang::SourceLocation location,
1975 clang::SourceLocation end, clang::SourceLocation readMacro)
1976{
1977 const clang::SourceManager &sourceManager = context.getSourceManager();
1978 const auto [fileId, offset] = sourceManager.getDecomposedLoc(location);
1979 if (end.isValid() && sourceManager.getFileID(end) != fileId)
1980 return true;
1981
1982 const llvm::StringRef buffer = sourceManager.getBufferData(fileId);
1983 clang::Lexer lexer(sourceManager.getLocForStartOfFile(fileId), context.getLangOpts(),
1984 buffer.begin(), buffer.begin() + offset, buffer.end());
1985 clang::Token token;
1986 for (bool first = true; !lexer.LexFromRawLexer(token); first = false) {
1987 if (end.isValid() ? !(token.getLocation() < end) : (!first && token.isAtStartOfLine()))
1988 break;
1989 if (!token.is(clang::tok::raw_identifier) || token.getLocation() == readMacro)
1990 continue;
1991 const llvm::StringRef spelling = token.getRawIdentifier();
1992 if (spelling == "constexpr" || spelling == "consteval"
1993 || context.Idents.get(spelling).hasMacroDefinition()) {
1994 return true;
1995 }
1996 }
1997 return false;
1998}
1999
2000/*
2001 Returns \c true if \a declaration is constexpr as its author declared it.
2002
2003 Clang treats a function that's explicitly defaulted on its first
2004 declaration as constexpr whenever the implicit declaration would be,
2005 and records that the same way as a written specifier. Which functions
2006 qualify depends on the language standard and the libclang version, so
2007 for these functions, look for a \c constexpr or \c consteval specifier
2008 before the name instead. When a macro declares the function, or a macro
2009 starts the declaration, look in the macro's definition. A macro may
2010 expand to either specifier, and the preprocessor isn't available here,
2011 so keep Clang's answer when the source can't be traced like this.
2012*/
2013static bool isConstexprAsDeclared(const clang::FunctionDecl *declaration)
2014{
2015 if (!declaration->isConstexpr())
2016 return false;
2017 if (!declaration->isExplicitlyDefaulted())
2018 return true;
2019
2020 const clang::ASTContext &context = declaration->getASTContext();
2021 const clang::SourceManager &sourceManager = context.getSourceManager();
2022 clang::SourceLocation begin = declaration->getBeginLoc();
2023 const clang::SourceLocation name = declaration->getLocation();
2024 if (name.isMacroID()) {
2025 begin = macroBodyLocation(sourceManager, begin);
2026 const clang::SourceLocation nameInBody = macroBodyLocation(sourceManager, name);
2027 if (sourceManager.getFileID(begin) != sourceManager.getFileID(nameInBody))
2028 return true;
2029 return mayDeclareConstexpr(context, sourceManager.getSpellingLoc(begin),
2030 sourceManager.getSpellingLoc(nameInBody), {});
2031 }
2032
2033 // Read the definitions of the macros that produce the first tokens,
2034 // from the innermost expansion outward.
2035 clang::SourceLocation readMacro;
2036 while (begin.isMacroID()) {
2037 if (sourceManager.isMacroArgExpansion(begin))
2038 return true;
2039 if (mayDeclareConstexpr(context, sourceManager.getImmediateSpellingLoc(begin), {},
2040 readMacro)) {
2041 return true;
2042 }
2043 begin = sourceManager.getImmediateExpansionRange(begin).getBegin();
2044 readMacro = sourceManager.getImmediateSpellingLoc(begin);
2045 }
2046 return mayDeclareConstexpr(context, begin, name, readMacro);
2047}
2048
2049void ClangVisitor::processFunction(FunctionNode *fn, CXCursor cursor)
2050{
2051 CXCursorKind kind = clang_getCursorKind(cursor);
2052 CXType funcType = clang_getCursorType(cursor);
2053 fn->setAccess(fromCX_CXXAccessSpecifier(clang_getCXXAccessSpecifier(cursor)));
2054 fn->setLocation(fromCXSourceLocation(clang_getCursorLocation(cursor)));
2055 fn->setStatic(clang_CXXMethod_isStatic(cursor));
2056 fn->setConst(clang_CXXMethod_isConst(cursor));
2057 fn->setVirtualness(!clang_CXXMethod_isVirtual(cursor)
2059 : clang_CXXMethod_isPureVirtual(cursor)
2062
2063 // REMARK: We assume that the following operations and casts are
2064 // generally safe.
2065 // Callers of those methods will generally check at the LibClang
2066 // level the kind of cursor we are dealing with and will pass on
2067 // only valid cursors that are of a function kind and that are at
2068 // least a declaration.
2069 //
2070 // Failure to do so implies a bug in the call chain and should be
2071 // dealt with as such.
2072 const clang::Decl* declaration = get_cursor_declaration(cursor);
2073
2074 assert(declaration);
2075
2076 const clang::FunctionDecl* function_declaration = declaration->getAsFunction();
2077
2078 if (kind == CXCursor_Constructor
2079 // a constructor template is classified as CXCursor_FunctionTemplate
2080 || (kind == CXCursor_FunctionTemplate && fn->name() == parent_->name()))
2082 else if (kind == CXCursor_Destructor)
2084 else if (kind != CXCursor_ConversionFunction)
2085 fn->setReturnType(QString::fromStdString(get_fully_qualified_type_name(
2086 function_declaration->getReturnType(),
2087 function_declaration->getASTContext()
2088 )));
2089
2090 const clang::CXXConstructorDecl* constructor_declaration = llvm::dyn_cast<const clang::CXXConstructorDecl>(function_declaration);
2091
2092 if (constructor_declaration && constructor_declaration->isCopyConstructor()) fn->setMetaness(Metaness::CCtor);
2093 else if (constructor_declaration && constructor_declaration->isMoveConstructor()) fn->setMetaness(Metaness::MCtor);
2094
2095 const clang::CXXConversionDecl* conversion_declaration = llvm::dyn_cast<const clang::CXXConversionDecl>(function_declaration);
2096
2097 if (isConstexprAsDeclared(function_declaration)) fn->markConstexpr();
2098 if (function_declaration->isExplicitlyDefaulted()) fn->markExplicitlyDefaulted();
2099 if (function_declaration->isDeletedAsWritten()) fn->markDeletedAsWritten();
2100 if (
2101 (constructor_declaration && constructor_declaration->isExplicit()) ||
2102 (conversion_declaration && conversion_declaration->isExplicit())
2103 ) fn->markExplicit();
2104
2105 const clang::CXXMethodDecl* method_declaration = llvm::dyn_cast<const clang::CXXMethodDecl>(function_declaration);
2106
2107 if (method_declaration && method_declaration->isCopyAssignmentOperator()) fn->setMetaness(Metaness::CAssign);
2108 else if (method_declaration && method_declaration->isMoveAssignmentOperator()) fn->setMetaness(Metaness::MAssign);
2109
2110 const clang::FunctionType* function_type = function_declaration->getFunctionType();
2111 const clang::FunctionProtoType* function_prototype = static_cast<const clang::FunctionProtoType*>(function_type);
2112
2113 if (function_prototype) {
2114 clang::FunctionProtoType::ExceptionSpecInfo exception_specification = function_prototype->getExceptionSpecInfo();
2115
2116 if (exception_specification.Type != clang::ExceptionSpecificationType::EST_None) {
2117 const std::string exception_specification_spelling =
2118 exception_specification.NoexceptExpr ? get_expression_as_string(
2119 exception_specification.NoexceptExpr,
2120 function_declaration->getASTContext()
2121 ) : "";
2122
2123 if (exception_specification_spelling != "false")
2124 fn->markNoexcept(QString::fromStdString(exception_specification_spelling));
2125 }
2126 }
2127
2128 // Collect every concept references a function carries (trailing requires
2129 // clause, any constrained-auto parameter types).
2130 // From Clang 21 we get an AssociatedConstraint struct for the trailing
2131 // clause (upstream commit 49fd0bf35d2e); earlier Clang versions return
2132 // a bare Expr*.
2133 QStringList referenced_concepts;
2134#if LIBCLANG_VERSION_MAJOR >= 21
2135 if (const auto trailing_requires = function_declaration->getTrailingRequiresClause();
2136 trailing_requires.ConstraintExpr) {
2137 QString requires_str = QString::fromStdString(
2138 get_expression_as_string(trailing_requires.ConstraintExpr,
2139 function_declaration->getASTContext()));
2140 fn->setTrailingRequiresClause(requires_str.simplified());
2141 std::vector<std::string> refs;
2142 collect_concept_references(trailing_requires.ConstraintExpr, refs);
2143 for (const auto &ref : refs)
2144 referenced_concepts << QString::fromStdString(ref);
2145 }
2146#else
2147 if (const clang::Expr *trailing_requires = function_declaration->getTrailingRequiresClause()) {
2148 QString requires_str = QString::fromStdString(
2149 get_expression_as_string(trailing_requires,
2150 function_declaration->getASTContext()));
2151 fn->setTrailingRequiresClause(requires_str.simplified());
2152 std::vector<std::string> refs;
2153 collect_concept_references(trailing_requires, refs);
2154 for (const auto &ref : refs)
2155 referenced_concepts << QString::fromStdString(ref);
2156 }
2157#endif
2158
2159 CXRefQualifierKind refQualKind = clang_Type_getCXXRefQualifier(funcType);
2160 if (refQualKind == CXRefQualifier_LValue)
2161 fn->setRef(true);
2162 else if (refQualKind == CXRefQualifier_RValue)
2163 fn->setRefRef(true);
2164 // For virtual functions, determine what it overrides
2165 // (except for destructor for which we do not want to classify as overridden)
2166 if (!fn->isNonvirtual() && kind != CXCursor_Destructor)
2168
2169 Parameters &parameters = fn->parameters();
2170 parameters.clear();
2171 parameters.reserve(function_declaration->getNumParams());
2172
2173 for (clang::ParmVarDecl* const parameter_declaration : function_declaration->parameters()) {
2174 clang::QualType parameter_type = parameter_declaration->getOriginalType();
2175
2176 parameters.append(QString::fromStdString(get_fully_qualified_type_name(
2177 parameter_type,
2178 parameter_declaration->getASTContext()
2179 )));
2180
2181 if (const clang::QualType lookup_type =
2182 parameterLookupType(parameter_declaration).getCanonicalType();
2183 lookup_type != parameter_type)
2184 parameters.last().setCanonicalType(QString::fromStdString(get_fully_qualified_type_name(
2185 lookup_type,
2186 parameter_declaration->getASTContext()
2187 )));
2188
2189 // Constrained-auto parameter form, e.g. \c {void f(Sortable auto x)}.
2190 if (const clang::AutoType *auto_type = parameter_type->getContainedAutoType()) {
2191 if (auto_type->isConstrained()) {
2192 if (const clang::NamedDecl *concept_decl =
2193 auto_type->getTypeConstraintConcept()) {
2194 referenced_concepts << QString::fromStdString(
2195 concept_decl->getQualifiedNameAsString());
2196 }
2197 }
2198 }
2199 }
2200
2201 if (!referenced_concepts.isEmpty()) {
2202 referenced_concepts.sort();
2203 referenced_concepts.removeDuplicates();
2204 fn->setReferencedConcepts(std::move(referenced_concepts));
2205 }
2206
2207 if (parameters.count() > 0) {
2208 if (parameters.last().type().endsWith(QLatin1String("QPrivateSignal"))) {
2209 parameters.pop_back(); // remove the QPrivateSignal argument
2210 parameters.setPrivateSignal();
2211 }
2212 }
2213
2214 if (clang_isFunctionTypeVariadic(funcType))
2215 parameters.append(QStringLiteral("..."));
2216 readParameterNamesAndAttributes(fn, cursor);
2217
2218 if (declaration && declaration->getFriendObjectKind() != clang::Decl::FOK_None) {
2219 fn->setRelatedNonmember(true);
2220 Q_ASSERT(function_declaration);
2221
2222 const bool hasNamespaceScopeRedeclaration =
2223 std::any_of(function_declaration->redecls_begin(),
2224 function_declaration->redecls_end(),
2225 [](const clang::FunctionDecl *r) {
2226 return r->getFriendObjectKind() == clang::Decl::FOK_None;
2227 });
2228 if (!hasNamespaceScopeRedeclaration)
2229 fn->setHiddenFriend(true);
2230 }
2231
2232 // Capture before the header TU dies. Do not change the recorded spelling,
2233 // canonical spelling, or the ordinary declaration deduplication rules.
2234 const clang::TemplateParameterList *binders = nullptr;
2235 if (const auto *functionTemplate = function_declaration->getDescribedFunctionTemplate()) {
2236 binders = functionTemplate->getTemplateParameters();
2237 } else if (fn->isHiddenFriend()) {
2238 const auto *record = llvm::dyn_cast<clang::CXXRecordDecl>(function_declaration->getLexicalDeclContext());
2239 if (const auto *classTemplate = record ? record->getDescribedClassTemplate() : nullptr)
2240 binders = classTemplate->getTemplateParameters();
2241 }
2242 if (binders && !fn->trailingRequiresClause()) {
2243 fn->setTemplateParameterKey(templateParameterKey(*binders));
2244 QList<QByteArray> typeKeys;
2245 for (int i = 0; i < parameters.count() && i < int(function_declaration->getNumParams()); ++i)
2246 typeKeys.append(hiddenFriendTypeKey(parameterLookupType(function_declaration->getParamDecl(i)),
2247 *binders));
2248 fn->setTemplateParameterTypeKeys(std::move(typeKeys));
2249 }
2250}
2251
2252bool ClangVisitor::parseProperty(const QString &spelling, const Location &loc)
2253{
2254 if (!spelling.startsWith(QLatin1String("Q_PROPERTY"))
2255 && !spelling.startsWith(QLatin1String("QDOC_PROPERTY"))
2256 && !spelling.startsWith(QLatin1String("Q_OVERRIDE")))
2257 return false;
2258
2259 qsizetype lpIdx = spelling.indexOf(QChar('('));
2260 qsizetype rpIdx = spelling.lastIndexOf(QChar(')'));
2261 if (lpIdx <= 0 || rpIdx <= lpIdx)
2262 return false;
2263
2264 QString signature = spelling.mid(lpIdx + 1, rpIdx - lpIdx - 1);
2265 signature = signature.simplified();
2266 QStringList parts = signature.split(QChar(' '), Qt::SkipEmptyParts);
2267
2268 static const QStringList attrs =
2269 QStringList() << "READ" << "MEMBER" << "WRITE"
2270 << "NOTIFY" << "CONSTANT" << "FINAL"
2271 << "REQUIRED" << "BINDABLE" << "DESIGNABLE"
2272 << "RESET" << "REVISION" << "SCRIPTABLE"
2273 << "STORED" << "USER";
2274
2275 // Find the location of the first attribute. All preceding parts
2276 // represent the property type + name.
2277 auto it = std::find_if(parts.cbegin(), parts.cend(),
2278 [](const QString &attr) -> bool {
2279 return attrs.contains(attr);
2280 });
2281
2282 if (it == parts.cend() || std::distance(parts.cbegin(), it) < 2)
2283 return false;
2284
2285 QStringList typeParts;
2286 std::copy(parts.cbegin(), it, std::back_inserter(typeParts));
2287 parts.erase(parts.cbegin(), it);
2288 QString name = typeParts.takeLast();
2289
2290 // Move the pointer operator(s) from name to type
2291 while (!name.isEmpty() && name.front() == QChar('*')) {
2292 typeParts.last().push_back(name.front());
2293 name.removeFirst();
2294 }
2295
2296 // Need at least READ or MEMBER + getter/member name
2297 if (parts.size() < 2 || name.isEmpty())
2298 return false;
2299
2300 auto *property = new PropertyNode(parent_, name);
2301 property->setAccess(Access::Public);
2302 property->setLocation(loc);
2303 property->setDataType(typeParts.join(QChar(' ')));
2304
2305 int i = 0;
2306 while (i < parts.size()) {
2307 const QString &key = parts.at(i++);
2308 // Keywords with no associated values
2309 if (key == "CONSTANT") {
2310 property->setConstant();
2311 } else if (key == "REQUIRED") {
2312 property->setRequired();
2313 }
2314 if (i < parts.size()) {
2315 QString value = parts.at(i++);
2316 if (key == "READ") {
2317 qdb_->addPropertyFunction(property, value, PropertyNode::FunctionRole::Getter);
2318 } else if (key == "WRITE") {
2319 qdb_->addPropertyFunction(property, value, PropertyNode::FunctionRole::Setter);
2320 property->setWritable(true);
2321 } else if (key == "MEMBER") {
2322 property->setWritable(true);
2323 } else if (key == "STORED") {
2324 property->setStored(value.toLower() == "true");
2325 } else if (key == "BINDABLE") {
2326 property->setPropertyType(PropertyNode::PropertyType::BindableProperty);
2327 qdb_->addPropertyFunction(property, value, PropertyNode::FunctionRole::Bindable);
2328 } else if (key == "RESET") {
2329 qdb_->addPropertyFunction(property, value, PropertyNode::FunctionRole::Resetter);
2330 } else if (key == "NOTIFY") {
2331 qdb_->addPropertyFunction(property, value, PropertyNode::FunctionRole::Notifier);
2332 }
2333 }
2334 }
2335 return true;
2336}
2337
2338/*!
2339 Given a comment at location \a loc, return a Node for this comment
2340 \a nextCommentLoc is the location of the next comment so the declaration
2341 must be inbetween.
2342 Returns nullptr if no suitable declaration was found between the two comments.
2343 */
2344Node *ClangVisitor::nodeForCommentAtLocation(CXSourceLocation loc, CXSourceLocation nextCommentLoc)
2345{
2346 ClangVisitor::SimpleLoc docloc;
2347 clang_getPresumedLocation(loc, nullptr, &docloc.line, &docloc.column);
2348 auto decl_it = declMap_.upperBound(docloc);
2349 if (decl_it == declMap_.end())
2350 return nullptr;
2351
2352 unsigned int declLine = decl_it.key().line;
2353 unsigned int nextCommentLine;
2354 clang_getPresumedLocation(nextCommentLoc, nullptr, &nextCommentLine, nullptr);
2355 if (nextCommentLine < declLine)
2356 return nullptr; // there is another comment before the declaration, ignore it.
2357
2358 // make sure the previous decl was finished.
2359 if (decl_it != declMap_.begin()) {
2360 CXSourceLocation prevDeclEnd = clang_getRangeEnd(clang_getCursorExtent(*(std::prev(decl_it))));
2361 unsigned int prevDeclLine;
2362 clang_getPresumedLocation(prevDeclEnd, nullptr, &prevDeclLine, nullptr);
2363 if (prevDeclLine >= docloc.line) {
2364 // The previous declaration was still going. This is only valid if the previous
2365 // declaration is a parent of the next declaration.
2366 auto parent = clang_getCursorLexicalParent(*decl_it);
2367 if (!clang_equalCursors(parent, *(std::prev(decl_it))))
2368 return nullptr;
2369 }
2370 }
2371 auto *node = findNodeForCursor(qdb_, *decl_it);
2372 // borrow the parameter name from the definition
2373 if (node && node->isFunction(Genus::CPP))
2374 readParameterNamesAndAttributes(static_cast<FunctionNode *>(node), *decl_it);
2375 return node;
2376}
2377
2379 QDocDatabase* qdb,
2380 Config& config,
2381 const std::vector<QByteArray>& include_paths,
2382 const QList<QByteArray>& defines,
2383 std::optional<std::reference_wrapper<const PCHFile>> pch
2384) : m_qdb{qdb},
2387 m_pch{pch}
2388{
2389 m_allHeaders = config.getHeaderFiles();
2390 m_internalFilePatterns = config.getInternalFilePatternsCompiled();
2391}
2392
2393static const char *defaultArgs_[] = {
2394 "-std=c++23",
2395#ifndef Q_OS_WIN
2396 "-fPIC",
2397#else
2398 "-fms-compatibility-version=19",
2399#endif
2400 "-DQ_QDOC",
2401 "-DQ_CLANG_QDOC",
2402 "-DQT_DISABLE_DEPRECATED_UP_TO=0",
2403 "-DQT_ANNOTATE_CLASS(type,...)=static_assert(sizeof(#__VA_ARGS__),#type);",
2404 "-DQT_ANNOTATE_CLASS2(type,a1,a2)=static_assert(sizeof(#a1,#a2),#type);",
2405 "-DQT_ANNOTATE_FUNCTION(a)=__attribute__((annotate(#a)))",
2406 "-DQT_ANNOTATE_ACCESS_SPECIFIER(a)=__attribute__((annotate(#a)))",
2407 "-Wno-constant-logical-operand",
2408 "-Wno-macro-redefined",
2409 "-Wno-nullability-completeness",
2410 "-fvisibility=default",
2411 "-ferror-limit=0",
2412 "-xc++"
2413};
2414
2415static std::vector<const char *> toConstCharPointers(const std::vector<QByteArray> &args)
2416{
2417 std::vector<const char *> pointers;
2418 pointers.reserve(args.size());
2419 for (const auto &arg : args)
2420 pointers.push_back(arg.constData());
2421 return pointers;
2422}
2423
2424/*!
2425 Load the default arguments and the defines into \a args.
2426 Clear \a args first.
2427 */
2428void getDefaultArgs(const QList<QByteArray>& defines, std::vector<QByteArray>& args)
2429{
2430 args.clear();
2431 for (const char *arg : defaultArgs_)
2432 args.emplace_back(arg);
2433
2434 // Add the defines from the qdocconf file.
2435 for (const auto &p : std::as_const(defines))
2436 args.push_back(p);
2437}
2438
2439/*!
2440 Load the include paths into \a args.
2441 */
2443 const std::vector<QByteArray>& include_paths,
2444 std::vector<QByteArray>& args
2445) {
2446 if (include_paths.empty()) {
2447 qCWarning(lcQdoc) << "No include paths provided."
2448 << "Set 'includepaths' in the qdocconf file"
2449 << "or pass -I flags on the command line."
2450 << "C++ parsing may produce incomplete results.";
2451 } else {
2452 args.insert(args.end(), include_paths.begin(), include_paths.end());
2453 }
2454}
2455
2456/*!
2457 Building the PCH must be possible when there are no .cpp
2458 files, so it is moved here to its own member function, and
2459 it is called after the list of header files is complete.
2460 */
2462 QDocDatabase* qdb,
2463 QString module_header,
2464 const std::set<Config::HeaderFilePath>& all_headers,
2465 const std::vector<QByteArray>& include_paths,
2466 const QList<QByteArray>& defines,
2467 const InclusionPolicy& policy
2468) {
2469 static std::vector<QByteArray> arguments{};
2470
2471 if (module_header.isEmpty()) return std::nullopt;
2472
2473 getDefaultArgs(defines, arguments);
2474 getMoreArgs(include_paths, arguments);
2475
2476 flags_ = static_cast<CXTranslationUnit_Flags>(CXTranslationUnit_Incomplete
2477 | CXTranslationUnit_SkipFunctionBodies
2478 | CXTranslationUnit_KeepGoing);
2479
2480 CompilationIndex index{ clang_createIndex(1, kClangDontDisplayDiagnostics) };
2481
2482 QTemporaryDir pch_directory{QDir::tempPath() + QLatin1String("/qdoc_pch")};
2483 if (!pch_directory.isValid()) return std::nullopt;
2484
2485 const QByteArray module = module_header.toUtf8();
2486 QByteArray header;
2487
2488 qCDebug(lcQdoc) << "Build and visit PCH for" << module_header;
2489 // A predicate for std::find_if() to locate a path to the module's header
2490 // (e.g. QtGui/QtGui) to be used as pre-compiled header
2491 struct FindPredicate
2492 {
2493 enum SearchType { Any, Module };
2494 QByteArray &candidate_;
2495 const QByteArray &module_;
2496 SearchType type_;
2497 FindPredicate(QByteArray &candidate, const QByteArray &module,
2498 SearchType type = Any)
2499 : candidate_(candidate), module_(module), type_(type)
2500 {
2501 }
2502
2503 bool operator()(const QByteArray &p) const
2504 {
2505 if (type_ != Any && !p.endsWith(module_))
2506 return false;
2507 candidate_ = p + "/";
2508 candidate_.append(module_);
2509 if (p.startsWith("-I"))
2510 candidate_ = candidate_.mid(2);
2511 return QFile::exists(QString::fromUtf8(candidate_));
2512 }
2513 };
2514
2515 // First, search for an include path that contains the module name, then any path
2516 QByteArray candidate;
2517 auto it = std::find_if(include_paths.begin(), include_paths.end(),
2518 FindPredicate(candidate, module, FindPredicate::Module));
2519 if (it == include_paths.end())
2520 it = std::find_if(include_paths.begin(), include_paths.end(),
2521 FindPredicate(candidate, module, FindPredicate::Any));
2522 if (it != include_paths.end())
2523 header = std::move(candidate);
2524
2525 if (header.isEmpty()) {
2526 qWarning() << "(qdoc) Could not find the module header in include paths for module"
2527 << module << " (include paths: " << include_paths << ")";
2528 qWarning() << " Artificial module header built from header dirs in qdocconf "
2529 "file";
2530 }
2531 arguments.push_back("-xc++");
2532
2533 TranslationUnit tu;
2534
2535 QString tmpHeader = pch_directory.path() + "/" + module;
2536 if (QFile tmpHeaderFile(tmpHeader); tmpHeaderFile.open(QIODevice::Text | QIODevice::WriteOnly)) {
2537 QTextStream out(&tmpHeaderFile);
2538 if (header.isEmpty()) {
2539 for (const auto& [header_path, header_name] : all_headers) {
2540 bool shouldInclude = !header_name.startsWith("moc_"_L1);
2541
2542 // Conditionally include private headers based on showInternal setting
2543 if (header_name.endsWith("_p.h"_L1))
2544 shouldInclude = shouldInclude && policy.showInternal;
2545
2546 if (shouldInclude) {
2547 out << "#include \"" << header_path << "/" << header_name << "\"\n";
2548 }
2549 }
2550 } else {
2551 QFileInfo headerFile(header);
2552 if (!headerFile.exists()) {
2553 qWarning() << "Could not find module header file" << header;
2554 return std::nullopt;
2555 }
2556
2557 out << "#include \"" << header << "\"\n";
2558
2559 if (policy.showInternal) {
2560 for (const auto& [header_path, header_name] : all_headers) {
2561 bool shouldInclude = !header_name.startsWith("moc_"_L1);
2562 if (header_name.endsWith("_p.h"_L1) && shouldInclude)
2563 out << "#include \"" << header_path << "/" << header_name << "\"\n";
2564 }
2565 }
2566 }
2567 }
2568
2569 const auto argPointers = toConstCharPointers(arguments);
2570 const QByteArray tmpHeaderLocal = tmpHeader.toLatin1();
2571 CXErrorCode err =
2572 clang_parseTranslationUnit2(index, tmpHeaderLocal.constData(), argPointers.data(),
2573 static_cast<int>(argPointers.size()), nullptr, 0,
2574 flags_ | CXTranslationUnit_ForSerialization, &tu.tu);
2575 qCDebug(lcQdoc) << __FUNCTION__ << "clang_parseTranslationUnit2(" << tmpHeader << arguments
2576 << ") returns" << err;
2577
2579
2580 if (err || !tu) {
2581 qCCritical(lcQdoc) << "Could not create PCH file for " << module_header;
2582 return std::nullopt;
2583 }
2584
2585 QByteArray pch_name = pch_directory.path().toUtf8() + "/" + module + ".pch";
2586 auto error = clang_saveTranslationUnit(tu, pch_name.constData(),
2587 clang_defaultSaveOptions(tu));
2588 if (error) {
2589 qCCritical(lcQdoc) << "Could not save PCH file for" << module_header;
2590 return std::nullopt;
2591 }
2592
2593 // Visit the header now, as token from pre-compiled header won't be visited
2594 // later
2595 CXCursor cur = clang_getTranslationUnitCursor(tu);
2596 auto &config = Config::instance();
2597 ClangVisitor visitor(qdb, all_headers, config.getInternalFilePatternsCompiled());
2598 visitor.visitChildren(cur);
2599 qCDebug(lcQdoc) << "PCH built and visited for" << module_header;
2600
2601 return std::make_optional(PCHFile{std::move(pch_directory), std::move(pch_name)});
2602}
2603
2604static float getUnpatchedVersion(QString t)
2605{
2606 if (t.count(QChar('.')) > 1)
2607 t.truncate(t.lastIndexOf(QChar('.')));
2608 return t.toFloat();
2609}
2610
2611/*!
2612 Get ready to parse the C++ cpp file identified by \a filePath
2613 and add its parsed contents to the database. \a location is
2614 used for reporting errors.
2615
2616 If parsing C++ header file as source, do not use the precompiled
2617 header as the source file itself is likely already included in the
2618 PCH and therefore interferes visiting the TU's children.
2619 */
2620ParsedCppFileIR ClangCodeParser::parse_cpp_file(const QString &filePath)
2621{
2622 flags_ = static_cast<CXTranslationUnit_Flags>(CXTranslationUnit_Incomplete
2623 | CXTranslationUnit_SkipFunctionBodies
2624 | CXTranslationUnit_KeepGoing);
2625
2626 CompilationIndex index{ clang_createIndex(1, kClangDontDisplayDiagnostics) };
2627
2628 getDefaultArgs(m_defines, m_args);
2629 if (m_pch && !filePath.endsWith(".mm")
2630 && !std::holds_alternative<CppHeaderSourceFile>(tag_source_file(filePath).second)) {
2631 m_args.push_back("-w");
2632 m_args.push_back("-include-pch");
2633 m_args.push_back((*m_pch).get().name);
2634 }
2635 getMoreArgs(m_includePaths, m_args);
2636
2637 TranslationUnit tu;
2638 const auto argPointers = toConstCharPointers(m_args);
2639 const QByteArray filePathLocal = filePath.toLocal8Bit();
2640 CXErrorCode err =
2641 clang_parseTranslationUnit2(index, filePathLocal.constData(), argPointers.data(),
2642 static_cast<int>(argPointers.size()), nullptr, 0, flags_, &tu.tu);
2643 qCDebug(lcQdoc) << __FUNCTION__ << "clang_parseTranslationUnit2(" << filePath << m_args
2644 << ") returns" << err;
2646
2647 if (err || !tu) {
2648 qWarning() << "(qdoc) Could not parse source file" << filePath << " error code:" << err;
2649 return {};
2650 }
2651
2652 ParsedCppFileIR parse_result{};
2653
2654 CXCursor tuCur = clang_getTranslationUnitCursor(tu);
2655 ClangVisitor visitor(m_qdb, m_allHeaders, m_internalFilePatterns);
2656 visitor.visitChildren(tuCur);
2657
2658 CXToken *tokens;
2659 unsigned int numTokens = 0;
2660 const QSet<QString> &commands = CppCodeParser::topic_commands + CppCodeParser::meta_commands;
2661 clang_tokenize(tu, clang_getCursorExtent(tuCur), &tokens, &numTokens);
2662
2663 for (unsigned int i = 0; i < numTokens; ++i) {
2664 if (clang_getTokenKind(tokens[i]) != CXToken_Comment)
2665 continue;
2666 QString comment = fromCXString(clang_getTokenSpelling(tu, tokens[i]));
2667 if (!comment.startsWith("/*!"))
2668 continue;
2669
2670 auto commentLoc = clang_getTokenLocation(tu, tokens[i]);
2671 auto loc = fromCXSourceLocation(commentLoc);
2672 auto end_loc = fromCXSourceLocation(clang_getRangeEnd(clang_getTokenExtent(tu, tokens[i])));
2673 Doc::trimCStyleComment(loc, comment);
2674
2675 // Doc constructor parses the comment.
2676 Doc doc(loc, end_loc, comment, commands, CppCodeParser::topic_commands);
2677 if (hasTooManyTopics(doc))
2678 continue;
2679
2680 if (doc.topicsUsed().isEmpty()) {
2681 Node *n = nullptr;
2682 if (i + 1 < numTokens) {
2683 // Try to find the next declaration.
2684 CXSourceLocation nextCommentLoc = commentLoc;
2685 while (i + 2 < numTokens && clang_getTokenKind(tokens[i + 1]) != CXToken_Comment)
2686 ++i; // already skip all the tokens that are not comments
2687 nextCommentLoc = clang_getTokenLocation(tu, tokens[i + 1]);
2688 n = visitor.nodeForCommentAtLocation(commentLoc, nextCommentLoc);
2689 }
2690
2691 if (n) {
2692 parse_result.tied.emplace_back(TiedDocumentation{doc, n});
2693 } else if (CodeParser::isWorthWarningAbout(doc)) {
2694 bool future = false;
2695 if (doc.metaCommandsUsed().contains(COMMAND_SINCE)) {
2696 QString sinceVersion = doc.metaCommandArgs(COMMAND_SINCE).at(0).first;
2697 if (getUnpatchedVersion(std::move(sinceVersion)) >
2698 getUnpatchedVersion(Config::instance().get(CONFIG_VERSION).asString()))
2699 future = true;
2700 }
2701 if (!future) {
2702 doc.location().warning(
2703 QStringLiteral("Cannot tie this documentation to anything"),
2704 QStringLiteral("qdoc found a /*! ... */ comment, but there was no "
2705 "topic command (e.g., '\\%1', '\\%2') in the "
2706 "comment and qdoc could not associate the "
2707 "declaration or definition following the "
2708 "comment with a documented entity.")
2709 .arg(COMMAND_FN, COMMAND_PAGE));
2710 }
2711 }
2712 } else {
2713 parse_result.untied.emplace_back(UntiedDocumentation{doc, QStringList()});
2714
2715 CXCursor cur = clang_getCursor(tu, commentLoc);
2716 while (true) {
2717 CXCursorKind kind = clang_getCursorKind(cur);
2718 if (clang_isTranslationUnit(kind) || clang_isInvalid(kind))
2719 break;
2720 if (kind == CXCursor_Namespace) {
2721 parse_result.untied.back().context << fromCXString(clang_getCursorSpelling(cur));
2722 }
2723 cur = clang_getCursorLexicalParent(cur);
2724 }
2725 }
2726 }
2727
2728 clang_disposeTokens(tu, tokens, numTokens);
2729 m_namespaceScope.clear();
2730 s_fn.clear();
2731
2732 return parse_result;
2733}
2734
2735/*!
2736 Use clang to parse the function signature from a function
2737 command. \a location is used for reporting errors. \a fnSignature
2738 is the string to parse. It is always a function decl.
2739 \a idTag is the optional bracketed argument passed to \\fn, or
2740 an empty string.
2741 \a context is a string list representing the scope (namespaces)
2742 under which the function is declared.
2743
2744 Returns a variant that's either a Node instance tied to the
2745 function declaration, or a parsing failure for later processing.
2746 */
2747std::variant<Node*, FnMatchError> FnCommandParser::operator()(const Location &location, const QString &fnSignature,
2748 const QString &idTag, QStringList context)
2749{
2750 Node *fnNode = nullptr;
2751 /*
2752 If the \fn command begins with a tag, then don't try to
2753 parse the \fn command with clang. Use the tag to search
2754 for the correct function node. It is an error if it can
2755 not be found. Return 0 in that case.
2756 */
2757 if (!idTag.isEmpty()) {
2758 fnNode = m_qdb->findFunctionNodeForTag(idTag);
2759 if (!fnNode) {
2760 location.error(
2761 QStringLiteral("tag \\fn [%1] not used in any include file in current module").arg(idTag));
2762 } else {
2763 /*
2764 The function node was found. Use the formal
2765 parameter names from the \fn command, because
2766 they will be the names used in the documentation.
2767 */
2768 auto *fn = static_cast<FunctionNode *>(fnNode);
2769 QStringList leftParenSplit = fnSignature.mid(fnSignature.indexOf(fn->name())).split('(');
2770 if (leftParenSplit.size() > 1) {
2771 QStringList rightParenSplit = leftParenSplit[1].split(')');
2772 if (!rightParenSplit.empty()) {
2773 QString params = rightParenSplit[0];
2774 if (!params.isEmpty()) {
2775 QStringList commaSplit = params.split(',');
2776 Parameters &parameters = fn->parameters();
2777 if (parameters.count() == commaSplit.size()) {
2778 for (int i = 0; i < parameters.count(); ++i) {
2779 QStringList blankSplit = commaSplit[i].split(' ', Qt::SkipEmptyParts);
2780 if (blankSplit.size() > 1) {
2781 QString pName = blankSplit.last();
2782 // Remove any non-letters from the start of parameter name
2783 auto it = std::find_if(std::begin(pName), std::end(pName),
2784 [](const QChar &c) { return c.isLetter(); });
2785 parameters[i].setName(
2786 pName.remove(0, std::distance(std::begin(pName), it)));
2787 }
2788 }
2789 }
2790 }
2791 }
2792 }
2793 }
2794 return fnNode;
2795 }
2796 auto flags = static_cast<CXTranslationUnit_Flags>(CXTranslationUnit_Incomplete
2797 | CXTranslationUnit_SkipFunctionBodies
2798 | CXTranslationUnit_KeepGoing);
2799
2800 CompilationIndex index{ clang_createIndex(1, kClangDontDisplayDiagnostics) };
2801
2802 getDefaultArgs(m_defines, m_args);
2803
2804 if (m_pch) {
2805 m_args.push_back("-w");
2806 m_args.push_back("-include-pch");
2807 m_args.push_back((*m_pch).get().name);
2808 }
2809
2810 TranslationUnit tu;
2811 QByteArray s_fn{};
2812 for (const auto &ns : std::as_const(context))
2813 s_fn.prepend("namespace " + ns.toUtf8() + " {");
2814 s_fn += fnSignature.toUtf8();
2815 if (!s_fn.endsWith(";"))
2816 s_fn += "{ }";
2817 s_fn.append(context.size(), '}');
2818
2819 const char *dummyFileName = fnDummyFileName;
2820 CXUnsavedFile unsavedFile { dummyFileName, s_fn.constData(),
2821 static_cast<unsigned long>(s_fn.size()) };
2822 const auto argPointers = toConstCharPointers(m_args);
2823 CXErrorCode err = clang_parseTranslationUnit2(index, dummyFileName, argPointers.data(),
2824 int(argPointers.size()), &unsavedFile, 1, flags, &tu.tu);
2825 qCDebug(lcQdoc) << __FUNCTION__ << "clang_parseTranslationUnit2(" << dummyFileName << m_args
2826 << ") returns" << err;
2828 if (err || !tu) {
2829 location.error(QStringLiteral("clang could not parse \\fn %1").arg(fnSignature));
2830 return fnNode;
2831 } else {
2832 /*
2833 Always visit the tu if one is constructed, because
2834 it might be possible to find the correct node, even
2835 if clang detected diagnostics. Only bother to report
2836 the diagnostics if they stop us finding the node.
2837 */
2838 CXCursor cur = clang_getTranslationUnitCursor(tu);
2839 auto &config = Config::instance();
2840 ClangVisitor visitor(m_qdb, m_allHeaders, config.getInternalFilePatternsCompiled());
2841 const FnLookupResult fnLookup = visitor.visitFnArg(cur);
2842 const auto phase = config.preparing() && !config.singleExec()
2844 if (shouldDiagnoseFnLookup(fnLookup, phase))
2845 return FnMatchError{ fnSignature, location };
2846 fnNode = fnLookup.node();
2847 }
2848 return fnNode;
2849}
2850
2851QT_END_NAMESPACE
static const clang::Decl * get_cursor_declaration(CXCursor cursor)
Returns the underlying Decl that cursor represents.
static QString reconstructQualifiedPathForCursor(CXCursor cur)
Reconstruct the qualified path name of a function that is being overridden.
static void findHiddenFriendCandidates(QDocDatabase *qdb, const QString &funcName, const clang::FunctionDecl *func_decl, NodeVector &candidates)
static std::optional< QString > classNameFromParameterType(clang::QualType param_type)
QString functionName(CXCursor cursor)
Returns the function name from a given cursor representing a function declaration.
static std::string get_default_value_initializer_as_string(const clang::TemplateTemplateParmDecl *parameter)
static QString fromCXString(CXString &&string)
convert a CXString to a QString, and dispose the CXString
static QDebug operator<<(QDebug debug, const std::vector< T > &v)
static QString getSpelling(CXSourceRange range)
static void setOverridesForFunction(FunctionNode *fn, CXCursor cursor)
static bool mayDeclareConstexpr(const clang::ASTContext &context, clang::SourceLocation location, clang::SourceLocation end, clang::SourceLocation readMacro)
static const auto kClangDontDisplayDiagnostics
static const clang::TemplateSpecializationType * find_template_specialization_through_sugar(const clang::Type *type)
static std::string get_default_value_initializer_as_string(const clang::ParmVarDecl *parameter)
static FnLookupResult findFunctionForCursor(QDocDatabase *qdb, CXCursor cur, NodeLookupMode mode)
static void collect_concept_references(const clang::Stmt *node, std::vector< std::string > &out)
static std::optional< SfinaeConstraint > detect_sfinae_constraint(const clang::NonTypeTemplateParmDecl *param)
static std::string get_expression_as_string(const clang::Expr *expression, const clang::ASTContext &declaration_context)
static clang::QualType parameterLookupType(const clang::ParmVarDecl *parameter)
bool visitChildrenLambda(CXCursor cursor, T &&lambda)
Call clang_visitChildren on the given cursor with the lambda as a callback T can be any functor that ...
static std::string get_default_value_initializer_as_string(const clang::NamedDecl *declaration)
static RelaxedTemplateDeclaration get_template_declaration(const clang::TemplateDecl *template_declaration)
static std::vector< const char * > toConstCharPointers(const std::vector< QByteArray > &args)
static std::string get_default_value_initializer_as_string(const clang::NonTypeTemplateParmDecl *parameter)
static QString fromCache(const QByteArray &cache, unsigned int offset1, unsigned int offset2)
static clang::SourceLocation macroBodyLocation(const clang::SourceManager &sourceManager, clang::SourceLocation location)
static bool is_enable_if_name(const std::string &qualified_name)
static bool isConstexprAsDeclared(const clang::FunctionDecl *declaration)
static float getUnpatchedVersion(QString t)
void getMoreArgs(const std::vector< QByteArray > &include_paths, std::vector< QByteArray > &args)
Load the include paths into args.
static Location fromCXSourceLocation(CXSourceLocation location)
convert a CXSourceLocation to a qdoc Location
static QString cleanAnonymousTypeName(const QString &typeName)
static Access fromCX_CXXAccessSpecifier(CX_CXXAccessSpecifier spec)
convert a CX_CXXAccessSpecifier to Node::Access
static std::string get_default_value_initializer_as_string(const clang::TemplateTypeParmDecl *parameter)
static bool functionSignatureMatches(FunctionNode *fn, FunctionCursorSignature &signature, FnSignatureMatchMode matchMode)
void getDefaultArgs(const QList< QByteArray > &defines, std::vector< QByteArray > &args)
Load the default arguments and the defines into args.
constexpr const char fnDummyFileName[]
static CXTranslationUnit_Flags flags_
static Node * findNodeForCursor(QDocDatabase *qdb, CXCursor cur)
static std::string get_fully_qualified_type_name(clang::QualType type, const clang::ASTContext &declaration_context)
FnSignatureMatchMode
static void printDiagnostics(const CXTranslationUnit &translationUnit)
static const char * defaultArgs_[]
std::optional< PCHFile > buildPCH(QDocDatabase *qdb, QString module_header, const std::set< Config::HeaderFilePath > &all_headers, const std::vector< QByteArray > &include_paths, const QList< QByteArray > &defines, const InclusionPolicy &policy)
Building the PCH must be possible when there are no .cpp files, so it is moved here to its own member...
static QString readFile(CXFile cxFile, unsigned int offset1, unsigned int offset2)
static std::string ensureAnonymousTagKeyword(std::string typeName, clang::QualType type)
Returns a string representing the name of type as if it was referred to at the end of the translation...
NodeLookupMode
void addChild(Node *child)
Adds the child to this node's child list and sets the child's parent pointer to this Aggregate.
ParsedCppFileIR parse_cpp_file(const QString &filePath)
Get ready to parse the C++ cpp file identified by filePath and add its parsed contents to the databas...
ClangCodeParser(QDocDatabase *qdb, Config &, const std::vector< QByteArray > &include_paths, const QList< QByteArray > &defines, std::optional< std::reference_wrapper< const PCHFile > > pch)
Node * nodeForCommentAtLocation(CXSourceLocation loc, CXSourceLocation nextCommentLoc)
Given a comment at location loc, return a Node for this comment nextCommentLoc is the location of the...
CXChildVisitResult visitChildren(CXCursor cursor)
QDocDatabase * qdocDB()
ClangVisitor(QDocDatabase *qdb, const std::set< Config::HeaderFilePath > &allHeaders, const Config::InternalFilePatterns &internalFilePatterns)
FnLookupResult visitFnArg(CXCursor cursor)
The ClassNode represents a C++ class.
Definition classnode.h:23
static bool isWorthWarningAbout(const Doc &doc)
Test for whether a doc comment warrants warnings.
The Config class contains the configuration variables for controlling how qdoc produces documentation...
Definition config.h:95
Definition doc.h:32
const Location & location() const
Returns the starting location of a qdoc comment.
Definition doc.cpp:89
TopicList topicsUsed() const
Returns a reference to the list of topic commands used in the current qdoc comment.
Definition doc.cpp:277
This node is used to represent any kind of function being documented.
void setConst(bool b)
void markDeletedAsWritten()
void setStatic(bool b)
bool isRef() const
void setVirtualness(Virtualness virtualness)
bool isNonvirtual() const
void setInvokable(bool b)
bool isHiddenFriend() const
void setRef(bool b)
void setOverride(bool b)
void setRefRef(bool b)
bool isConst() const
void markConstexpr()
bool isRefRef() const
void markExplicit()
void markExplicitlyDefaulted()
void setMetaness(Metaness metaness)
const std::optional< QString > & trailingRequiresClause() const
Parameters & parameters()
void setHiddenFriend(bool b)
The Location class provides a way to mark a location in a file.
Definition location.h:20
void setColumnNo(int no)
Definition location.h:43
void setLineNo(int no)
Definition location.h:42
This class represents a C++ namespace.
This class describes one instance of using the Q_PROPERTY macro.
\inmodule QtCore
Definition qbytearray.h:58
This class provides exclusive access to the qdoc database, which consists of a forrest of trees and a...
NamespaceNode * primaryTreeRoot()
Returns a pointer to the root node of the primary tree.
Status
Specifies the status of the QQmlIncubator.
#define COMMAND_SINCE
Definition codeparser.h:77
#define COMMAND_FN
Definition codeparser.h:27
#define COMMAND_PAGE
Definition codeparser.h:45
#define CONFIG_VERSION
Definition config.h:470
#define CONFIG_DOCUMENTATIONINHEADERS
Definition config.h:396
bool hasTooManyTopics(const Doc &doc)
Checks if there are too many topic commands in doc.
FnDiagnosticPhase
FnLookupResultFor< Node > FnLookupResult
NodeType
Definition genustypes.h:165
QmlNativeTypeAttribute
Defines QML-specific attributes affecting QmlTypeNode instances.
Definition genustypes.h:214
Metaness
Specifies the kind of function a FunctionNode represents.
Definition genustypes.h:242
This namespace holds QDoc-internal utility methods.
Definition utilities.h:21
std::string getFullyQualifiedName(QualType QT, const ASTContext &Ctx, const PrintingPolicy &Policy, bool WithGlobalNsPrefix=false)
QList< Node * > NodeVector
Definition node.h:47
#define assert
@ Internal
Definition status.h:15
Returns the spelling in the file for a source range.
std::variant< Node *, FnMatchError > operator()(const Location &location, const QString &fnSignature, const QString &idTag, QStringList context)
Use clang to parse the function signature from a function command.
Encapsulates information about.
Definition parsererror.h:13
QVarLengthArray< QString, 20 > canonicalSpellings
QString typeSpelling(int index)
QVarLengthArray< QString, 20 > argumentSpellings
std::optional< RelaxedTemplateDeclaration > templateDeclaration
QString canonicalTypeSpelling(int index)
QList< QByteArray > templateTypeKeys
const clang::FunctionDecl * declaration
The Node class is the base class for all the nodes in QDoc's parse tree.
void setAccess(Access t)
Sets the node's access type to t.
Definition node.h:172
bool isNamespace() const
Returns true if the node type is Namespace.
Definition node.h:110
bool isTypedef() const
Returns true if the node type is Typedef.
Definition node.h:128
Aggregate * parent() const
Returns the node's parent pointer, that is, the aggregate under which the node is documented.
Definition node.h:211
bool isVariable() const
Returns true if the node type is Variable.
Definition node.h:133
void setLocation(const Location &t)
Sets the node's declaration location, its definition location, or both, depending on the suffix of th...
Definition node.cpp:909
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
virtual void setRelatedNonmember(bool b)
Sets a flag in the node indicating whether this node is a related nonmember of something.
Definition node.h:188
const std::optional< RelaxedTemplateDeclaration > & templateDecl() const
Definition node.h:247
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 isClass() const
Returns true if the node type is Class.
Definition node.h:91
virtual bool isClassNode() const
Returns true if this is an instance of ClassNode.
Definition node.h:145
A class for parsing and managing a function parameter list.
Definition main.cpp:28
Parameter & operator[](int index)
Definition parameters.h:39
bool isEmpty() const
Definition parameters.h:32
void pop_back()
Definition parameters.h:43
void reserve(int count)
Definition parameters.h:35
void clear()
Definition parameters.h:24
Parameter & last()
Definition parameters.h:37
bool isPrivateSignal() const
Definition parameters.h:31
const Parameter & at(int i) const
Definition parameters.h:36
const Parameter & last() const
Definition parameters.h:38
int count() const
Definition parameters.h:34
void setPrivateSignal()
Definition parameters.h:44
Holds the source-level alias with its template arguments for a SFINAE constraint detected in a non-ty...
CXTranslationUnit tu