summaryrefslogtreecommitdiff
path: root/src/qdoc/clangcodeparser.cpp
blob: d2d72abfe49e7316df7c98441703f0e8844cc991 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
// Copyright (C) 2021 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "clangcodeparser.h"

#include "access.h"
#include "classnode.h"
#include "codechunk.h"
#include "config.h"
#include "enumnode.h"
#include "functionnode.h"
#include "namespacenode.h"
#include "propertynode.h"
#include "qdocdatabase.h"
#include "typedefnode.h"
#include "utilities.h"
#include "variablenode.h"

#include <QtCore/qdebug.h>
#include <QtCore/qelapsedtimer.h>
#include <QtCore/qfile.h>
#include <QtCore/qscopedvaluerollback.h>
#include <QtCore/qtemporarydir.h>
#include <QtCore/qtextstream.h>
#include <QtCore/qvarlengtharray.h>

#include <clang-c/Index.h>

#include <cstdio>

QT_BEGIN_NAMESPACE

// We're printing diagnostics in ClangCodeParser::printDiagnostics,
// so avoid clang itself printing them.
static const auto kClangDontDisplayDiagnostics = 0;

static CXTranslationUnit_Flags flags_ = static_cast<CXTranslationUnit_Flags>(0);
static CXIndex index_ = nullptr;

QByteArray ClangCodeParser::s_fn;
constexpr const char *fnDummyFileName = "/fn_dummyfile.cpp";

#ifndef QT_NO_DEBUG_STREAM
template<class T>
static QDebug operator<<(QDebug debug, const std::vector<T> &v)
{
    QDebugStateSaver saver(debug);
    debug.noquote();
    debug.nospace();
    const size_t size = v.size();
    debug << "std::vector<>[" << size << "](";
    for (size_t i = 0; i < size; ++i) {
        if (i)
            debug << ", ";
        debug << v[i];
    }
    debug << ')';
    return debug;
}
#endif // !QT_NO_DEBUG_STREAM

/*!
   Call clang_visitChildren on the given cursor with the lambda as a callback
   T can be any functor that is callable with a CXCursor parameter and returns a CXChildVisitResult
   (in other word compatible with function<CXChildVisitResult(CXCursor)>
 */
template<typename T>
bool visitChildrenLambda(CXCursor cursor, T &&lambda)
{
    CXCursorVisitor visitor = [](CXCursor c, CXCursor,
                                 CXClientData client_data) -> CXChildVisitResult {
        return (*static_cast<T *>(client_data))(c);
    };
    return clang_visitChildren(cursor, visitor, &lambda);
}

/*!
    convert a CXString to a QString, and dispose the CXString
 */
static QString fromCXString(CXString &&string)
{
    QString ret = QString::fromUtf8(clang_getCString(string));
    clang_disposeString(string);
    return ret;
}

static QString templateDecl(CXCursor cursor);

/*!
    Returns a list of template parameters at \a cursor.
*/
static QStringList getTemplateParameters(CXCursor cursor)
{
    QStringList parameters;
    visitChildrenLambda(cursor, [&parameters](CXCursor cur) {
        QString name = fromCXString(clang_getCursorSpelling(cur));
        QString type;

        switch (clang_getCursorKind(cur)) {
        case CXCursor_TemplateTypeParameter:
            type = QStringLiteral("typename");
            break;
        case CXCursor_NonTypeTemplateParameter:
            type = fromCXString(clang_getTypeSpelling(clang_getCursorType(cur)));
            // Hack: Omit QtPrivate template parameters from public documentation
            if (type.startsWith(QLatin1String("QtPrivate")))
                return CXChildVisit_Continue;
            break;
        case CXCursor_TemplateTemplateParameter:
            type = templateDecl(cur) + QLatin1String(" class");
            break;
        default:
            return CXChildVisit_Continue;
        }

        if (!name.isEmpty())
            name.prepend(QLatin1Char(' '));

        parameters << type + name;
        return CXChildVisit_Continue;
    });

    return parameters;
}

/*!
   Gets the template declaration at specified \a cursor.
 */
static QString templateDecl(CXCursor cursor)
{
    QStringList params = getTemplateParameters(cursor);
    return QLatin1String("template <") + params.join(QLatin1String(", ")) + QLatin1Char('>');
}

/*!
    convert a CXSourceLocation to a qdoc Location
 */
static Location fromCXSourceLocation(CXSourceLocation location)
{
    unsigned int line, column;
    CXString file;
    clang_getPresumedLocation(location, &file, &line, &column);
    Location l(fromCXString(std::move(file)));
    l.setColumnNo(column);
    l.setLineNo(line);
    return l;
}

/*!
    convert a CX_CXXAccessSpecifier to Node::Access
 */
static Access fromCX_CXXAccessSpecifier(CX_CXXAccessSpecifier spec)
{
    switch (spec) {
    case CX_CXXPrivate:
        return Access::Private;
    case CX_CXXProtected:
        return Access::Protected;
    case CX_CXXPublic:
        return Access::Public;
    default:
        return Access::Public;
    }
}

/*!
   Returns the spelling in the file for a source range
 */
static QString getSpelling(CXSourceRange range)
{
    auto start = clang_getRangeStart(range);
    auto end = clang_getRangeEnd(range);
    CXFile file1, file2;
    unsigned int offset1, offset2;
    clang_getFileLocation(start, &file1, nullptr, nullptr, &offset1);
    clang_getFileLocation(end, &file2, nullptr, nullptr, &offset2);

    if (file1 != file2 || offset2 <= offset1)
        return QString();
    QFile file(fromCXString(clang_getFileName(file1)));
    if (!file.open(QFile::ReadOnly)) {
        if (file.fileName() == fnDummyFileName)
            return QString::fromUtf8(ClangCodeParser::fn().mid(offset1, offset2 - offset1));
        return QString();
    }
    file.seek(offset1);
    return QString::fromUtf8(file.read(offset2 - offset1));
}

/*!
  Returns the function name from a given cursor representing a
  function declaration. This is usually clang_getCursorSpelling, but
  not for the conversion function in which case it is a bit more complicated
 */
QString functionName(CXCursor cursor)
{
    if (clang_getCursorKind(cursor) == CXCursor_ConversionFunction) {
        // For a CXCursor_ConversionFunction we don't want the spelling which would be something
        // like "operator type-parameter-0-0" or "operator unsigned int". we want the actual name as
        // spelled;
        QString type = fromCXString(clang_getTypeSpelling(clang_getCursorResultType(cursor)));
        if (type.isEmpty())
            return fromCXString(clang_getCursorSpelling(cursor));
        return QLatin1String("operator ") + type;
    }

    QString name = fromCXString(clang_getCursorSpelling(cursor));

    // Remove template stuff from constructor and destructor but not from operator<
    auto ltLoc = name.indexOf('<');
    if (ltLoc > 0 && !name.startsWith("operator<"))
        name = name.left(ltLoc);
    return name;
}

/*!
  Reconstruct the qualified path name of a function that is
  being overridden.
 */
static QString reconstructQualifiedPathForCursor(CXCursor cur)
{
    QString path;
    auto kind = clang_getCursorKind(cur);
    while (!clang_isInvalid(kind) && kind != CXCursor_TranslationUnit) {
        switch (kind) {
        case CXCursor_Namespace:
        case CXCursor_StructDecl:
        case CXCursor_ClassDecl:
        case CXCursor_UnionDecl:
        case CXCursor_ClassTemplate:
            path.prepend("::");
            path.prepend(fromCXString(clang_getCursorSpelling(cur)));
            break;
        case CXCursor_FunctionDecl:
        case CXCursor_FunctionTemplate:
        case CXCursor_CXXMethod:
        case CXCursor_Constructor:
        case CXCursor_Destructor:
        case CXCursor_ConversionFunction:
            path = functionName(cur);
            break;
        default:
            break;
        }
        cur = clang_getCursorSemanticParent(cur);
        kind = clang_getCursorKind(cur);
    }
    return path;
}

/*!
  Find the node from the QDocDatabase \a qdb that corrseponds to the declaration
  represented by the cursor \a cur, if it exists.
 */
static Node *findNodeForCursor(QDocDatabase *qdb, CXCursor cur)
{
    auto kind = clang_getCursorKind(cur);
    if (clang_isInvalid(kind))
        return nullptr;
    if (kind == CXCursor_TranslationUnit)
        return qdb->primaryTreeRoot();

    Node *p = findNodeForCursor(qdb, clang_getCursorSemanticParent(cur));
    if (p == nullptr)
        return nullptr;
    if (!p->isAggregate())
        return nullptr;
    auto parent = static_cast<Aggregate *>(p);

    QString name = fromCXString(clang_getCursorSpelling(cur));
    switch (kind) {
    case CXCursor_Namespace:
        return parent->findNonfunctionChild(name, &Node::isNamespace);
    case CXCursor_StructDecl:
    case CXCursor_ClassDecl:
    case CXCursor_UnionDecl:
    case CXCursor_ClassTemplate:
        return parent->findNonfunctionChild(name, &Node::isClassNode);
    case CXCursor_FunctionDecl:
    case CXCursor_FunctionTemplate:
    case CXCursor_CXXMethod:
    case CXCursor_Constructor:
    case CXCursor_Destructor:
    case CXCursor_ConversionFunction: {
        NodeVector candidates;
        parent->findChildren(functionName(cur), candidates);
        if (candidates.isEmpty())
            return nullptr;
        CXType funcType = clang_getCursorType(cur);
        auto numArg = clang_getNumArgTypes(funcType);
        bool isVariadic = clang_isFunctionTypeVariadic(funcType);
        QVarLengthArray<QString, 20> args;
        for (Node *candidate : qAsConst(candidates)) {
            if (!candidate->isFunction(Node::CPP))
                continue;
            auto fn = static_cast<FunctionNode *>(candidate);
            const Parameters &parameters = fn->parameters();
            if (parameters.count() != numArg + isVariadic)
                continue;
            if (fn->isConst() != bool(clang_CXXMethod_isConst(cur)))
                continue;
            if (isVariadic && parameters.last().type() != QLatin1String("..."))
                continue;
            if (fn->isRef() != (clang_Type_getCXXRefQualifier(funcType) == CXRefQualifier_LValue))
                continue;
            if (fn->isRefRef() != (clang_Type_getCXXRefQualifier(funcType) == CXRefQualifier_RValue))
                continue;

            bool different = false;
            for (int i = 0; i < numArg; ++i) {
                CXType argType = clang_getArgType(funcType, i);
                if (args.size() <= i)
                    args.append(fromCXString(clang_getTypeSpelling(argType)));
                QString recordedType = parameters.at(i).type();
                QString typeSpelling = args.at(i);
                auto p = parent;
                while (p && recordedType != typeSpelling) {
                    QString parentScope = p->name() + QLatin1String("::");
                    recordedType.remove(parentScope);
                    typeSpelling.remove(parentScope);
                    p = p->parent();
                }
                different = recordedType != typeSpelling;

                // Retry with a canonical type spelling
                if (different && (argType.kind == CXType_Typedef || argType.kind == CXType_Elaborated)) {
                    QStringView canonicalType = parameters.at(i).canonicalType();
                    if (!canonicalType.isEmpty()) {
                        different = canonicalType !=
                            fromCXString(clang_getTypeSpelling(clang_getCanonicalType(argType)));
                    }
                }
                if (different) {
                    break;
                }
            }
            if (!different)
                return fn;
        }
        return nullptr;
    }
    case CXCursor_EnumDecl:
        return parent->findNonfunctionChild(name, &Node::isEnumType);
    case CXCursor_FieldDecl:
    case CXCursor_VarDecl:
        return parent->findNonfunctionChild(name, &Node::isVariable);
    case CXCursor_TypedefDecl:
        return parent->findNonfunctionChild(name, &Node::isTypedef);
    default:
        return nullptr;
    }
}

static void setOverridesForFunction(FunctionNode *fn, CXCursor cursor)
{
    CXCursor *overridden;
    unsigned int numOverridden = 0;
    clang_getOverriddenCursors(cursor, &overridden, &numOverridden);
    for (uint i = 0; i < numOverridden; ++i) {
        QString path = reconstructQualifiedPathForCursor(overridden[i]);
        if (!path.isEmpty()) {
            fn->setOverride(true);
            fn->setOverridesThis(path);
            break;
        }
    }
    clang_disposeOverriddenCursors(overridden);
}

class ClangVisitor
{
public:
    ClangVisitor(QDocDatabase *qdb, const QMultiHash<QString, QString> &allHeaders)
        : qdb_(qdb), parent_(qdb->primaryTreeRoot()), allHeaders_(allHeaders)
    {
    }

    QDocDatabase *qdocDB() { return qdb_; }

    CXChildVisitResult visitChildren(CXCursor cursor)
    {
        auto ret = visitChildrenLambda(cursor, [&](CXCursor cur) {
            auto loc = clang_getCursorLocation(cur);
            if (clang_Location_isFromMainFile(loc))
                return visitSource(cur, loc);
            CXFile file;
            clang_getFileLocation(loc, &file, nullptr, nullptr, nullptr);
            bool isInteresting = false;
            auto it = isInterestingCache_.find(file);
            if (it != isInterestingCache_.end()) {
                isInteresting = *it;
            } else {
                QFileInfo fi(fromCXString(clang_getFileName(file)));
                // Match by file name in case of PCH/installed headers
                isInteresting = allHeaders_.contains(fi.fileName());
                isInterestingCache_[file] = isInteresting;
            }
            if (isInteresting) {
                return visitHeader(cur, loc);
            }

            return CXChildVisit_Continue;
        });
        return ret ? CXChildVisit_Break : CXChildVisit_Continue;
    }

    /*
      Not sure about all the possibilities, when the cursor
      location is not in the main file.
     */
    CXChildVisitResult visitFnArg(CXCursor cursor, Node **fnNode, bool &ignoreSignature)
    {
        auto ret = visitChildrenLambda(cursor, [&](CXCursor cur) {
            auto loc = clang_getCursorLocation(cur);
            if (clang_Location_isFromMainFile(loc))
                return visitFnSignature(cur, loc, fnNode, ignoreSignature);
            return CXChildVisit_Continue;
        });
        return ret ? CXChildVisit_Break : CXChildVisit_Continue;
    }

    Node *nodeForCommentAtLocation(CXSourceLocation loc, CXSourceLocation nextCommentLoc);

private:
    /*!
      SimpleLoc represents a simple location in the main source file,
      which can be used as a key in a QMap.
     */
    struct SimpleLoc
    {
        unsigned int line {}, column {};
        friend bool operator<(const SimpleLoc &a, const SimpleLoc &b)
        {
            return a.line != b.line ? a.line < b.line : a.column < b.column;
        }
    };
    /*!
      \variable ClangVisitor::declMap_
      Map of all the declarations in the source file so we can match them
      with a documentation comment.
     */
    QMap<SimpleLoc, CXCursor> declMap_;

    QDocDatabase *qdb_;
    Aggregate *parent_;
    bool m_friendDecl { false };             // true if currently visiting a friend declaration
    const QMultiHash<QString, QString> allHeaders_;
    QHash<CXFile, bool> isInterestingCache_; // doing a canonicalFilePath is slow, so keep a cache.

    /*!
        Returns true if the symbol should be ignored for the documentation.
     */
    bool ignoredSymbol(const QString &symbolName)
    {
        if (symbolName == QLatin1String("QPrivateSignal"))
            return true;
        // Ignore functions generated by property macros
        if (symbolName.startsWith("_qt_property_"))
            return true;
        return false;
    }

    /*!
        The type parameters do not need to be fully qualified
        This function removes the ClassName:: if needed.

        example: 'QLinkedList::iterator' -> 'iterator'
     */
    QString adjustTypeName(const QString &typeName)
    {
        auto parent = parent_->parent();
        if (parent && parent->isClassNode()) {
            QStringView typeNameConstRemoved(typeName);
            if (typeNameConstRemoved.startsWith(QLatin1String("const ")))
                typeNameConstRemoved = typeNameConstRemoved.mid(6);

            auto parentName = parent->fullName();
            if (typeNameConstRemoved.startsWith(parentName)
                && typeNameConstRemoved.mid(parentName.size(), 2) == QLatin1String("::")) {
                QString result = typeName;
                result.remove(typeName.indexOf(typeNameConstRemoved), parentName.size() + 2);
                return result;
            }
        }
        return typeName;
    }

    CXChildVisitResult visitSource(CXCursor cursor, CXSourceLocation loc);
    CXChildVisitResult visitHeader(CXCursor cursor, CXSourceLocation loc);
    CXChildVisitResult visitFnSignature(CXCursor cursor, CXSourceLocation loc, Node **fnNode,
                                        bool &ignoreSignature);
    void processFunction(FunctionNode *fn, CXCursor cursor);
    bool parseProperty(const QString &spelling, const Location &loc);
    void readParameterNamesAndAttributes(FunctionNode *fn, CXCursor cursor);
    Aggregate *getSemanticParent(CXCursor cursor);
};

/*!
  Visits a cursor in the .cpp file.
  This fills the declMap_
 */
CXChildVisitResult ClangVisitor::visitSource(CXCursor cursor, CXSourceLocation loc)
{
    auto kind = clang_getCursorKind(cursor);
    if (clang_isDeclaration(kind)) {
        SimpleLoc l;
        clang_getPresumedLocation(loc, nullptr, &l.line, &l.column);
        declMap_.insert(l, cursor);
        return CXChildVisit_Recurse;
    }
    return CXChildVisit_Continue;
}

/*!
  If the semantic and lexical parent cursors of \a cursor are
  not the same, find the Aggregate node for the semantic parent
  cursor and return it. Otherwise return the current parent.
 */
Aggregate *ClangVisitor::getSemanticParent(CXCursor cursor)
{
    CXCursor sp = clang_getCursorSemanticParent(cursor);
    CXCursor lp = clang_getCursorLexicalParent(cursor);
    if (!clang_equalCursors(sp, lp) && clang_isDeclaration(clang_getCursorKind(sp))) {
        Node *spn = findNodeForCursor(qdb_, sp);
        if (spn && spn->isAggregate()) {
            return static_cast<Aggregate *>(spn);
        }
    }
    return parent_;
}

CXChildVisitResult ClangVisitor::visitFnSignature(CXCursor cursor, CXSourceLocation, Node **fnNode,
                                                  bool &ignoreSignature)
{
    switch (clang_getCursorKind(cursor)) {
    case CXCursor_Namespace:
        return CXChildVisit_Recurse;
    case CXCursor_FunctionDecl:
    case CXCursor_FunctionTemplate:
    case CXCursor_CXXMethod:
    case CXCursor_Constructor:
    case CXCursor_Destructor:
    case CXCursor_ConversionFunction: {
        ignoreSignature = false;
        if (ignoredSymbol(functionName(cursor))) {
            *fnNode = nullptr;
            ignoreSignature = true;
        } else {
            *fnNode = findNodeForCursor(qdb_, cursor);
            if (*fnNode) {
                if ((*fnNode)->isFunction(Node::CPP)) {
                    auto *fn = static_cast<FunctionNode *>(*fnNode);
                    readParameterNamesAndAttributes(fn, cursor);
                }
            } else { // Possibly an implicitly generated special member
                QString name = functionName(cursor);
                if (ignoredSymbol(name))
                    return CXChildVisit_Continue;
                Aggregate *semanticParent = getSemanticParent(cursor);
                if (semanticParent && semanticParent->isClass()) {
                    auto *candidate = new FunctionNode(nullptr, name);
                    processFunction(candidate, cursor);
                    if (!candidate->isSpecialMemberFunction()) {
                        delete candidate;
                        return CXChildVisit_Continue;
                    }
                    candidate->setDefault(true);
                    semanticParent->addChild(*fnNode = candidate);
                }
            }
        }
        break;
    }
    default:
        break;
    }
    return CXChildVisit_Continue;
}

CXChildVisitResult ClangVisitor::visitHeader(CXCursor cursor, CXSourceLocation loc)
{
    auto kind = clang_getCursorKind(cursor);
    QString templateString;
    switch (kind) {
    case CXCursor_TypeAliasTemplateDecl:
    case CXCursor_TypeAliasDecl: {
        QString aliasDecl = getSpelling(clang_getCursorExtent(cursor)).simplified();
        QStringList typeAlias = aliasDecl.split(QLatin1Char('='));
        if (typeAlias.size() == 2) {
            typeAlias[0] = typeAlias[0].trimmed();
            const QLatin1String usingString("using ");
            qsizetype usingPos = typeAlias[0].indexOf(usingString);
            if (usingPos != -1) {
                if (kind == CXCursor_TypeAliasTemplateDecl)
                    templateString = typeAlias[0].left(usingPos).trimmed();
                typeAlias[0].remove(0, usingPos + usingString.size());
                typeAlias[0] = typeAlias[0].split(QLatin1Char(' ')).first();
                typeAlias[1] = typeAlias[1].trimmed();
                auto *ta = new TypeAliasNode(parent_, typeAlias[0], typeAlias[1]);
                ta->setAccess(fromCX_CXXAccessSpecifier(clang_getCXXAccessSpecifier(cursor)));
                ta->setLocation(fromCXSourceLocation(clang_getCursorLocation(cursor)));
                ta->setTemplateDecl(templateString);
            }
        }
        return CXChildVisit_Continue;
    }
    case CXCursor_StructDecl:
    case CXCursor_UnionDecl:
        if (fromCXString(clang_getCursorSpelling(cursor)).isEmpty()) // anonymous struct or union
            return CXChildVisit_Continue;
        Q_FALLTHROUGH();
    case CXCursor_ClassTemplate:
        templateString = templateDecl(cursor);
        Q_FALLTHROUGH();
    case CXCursor_ClassDecl: {
        if (!clang_isCursorDefinition(cursor))
            return CXChildVisit_Continue;

        if (findNodeForCursor(qdb_, cursor)) // Was already parsed, probably in another TU
            return CXChildVisit_Continue;

        QString className = fromCXString(clang_getCursorSpelling(cursor));

        Aggregate *semanticParent = getSemanticParent(cursor);
        if (semanticParent && semanticParent->findNonfunctionChild(className, &Node::isClassNode)) {
            return CXChildVisit_Continue;
        }

        CXCursorKind actualKind = (kind == CXCursor_ClassTemplate) ?
                 clang_getTemplateCursorKind(cursor) : kind;

        Node::NodeType type = Node::Class;
        if (actualKind == CXCursor_StructDecl)
            type = Node::Struct;
        else if (actualKind == CXCursor_UnionDecl)
            type = Node::Union;

        auto *classe = new ClassNode(type, semanticParent, className);
        classe->setAccess(fromCX_CXXAccessSpecifier(clang_getCXXAccessSpecifier(cursor)));
        classe->setLocation(fromCXSourceLocation(clang_getCursorLocation(cursor)));

        if (kind == CXCursor_ClassTemplate)
            classe->setTemplateDecl(templateString);

        QScopedValueRollback<Aggregate *> setParent(parent_, classe);
        return visitChildren(cursor);
    }
    case CXCursor_CXXBaseSpecifier: {
        if (!parent_->isClassNode())
            return CXChildVisit_Continue;
        auto access = fromCX_CXXAccessSpecifier(clang_getCXXAccessSpecifier(cursor));
        auto type = clang_getCursorType(cursor);
        auto baseCursor = clang_getTypeDeclaration(type);
        auto baseNode = findNodeForCursor(qdb_, baseCursor);
        auto classe = static_cast<ClassNode *>(parent_);
        if (baseNode == nullptr || !baseNode->isClassNode()) {
            QString bcName = reconstructQualifiedPathForCursor(baseCursor);
            classe->addUnresolvedBaseClass(access,
                                           bcName.split(QLatin1String("::"), Qt::SkipEmptyParts));
            return CXChildVisit_Continue;
        }
        auto baseClasse = static_cast<ClassNode *>(baseNode);
        classe->addResolvedBaseClass(access, baseClasse);
        return CXChildVisit_Continue;
    }
    case CXCursor_Namespace: {
        QString namespaceName = fromCXString(clang_getCursorDisplayName(cursor));
        NamespaceNode *ns = nullptr;
        if (parent_)
            ns = static_cast<NamespaceNode *>(
                    parent_->findNonfunctionChild(namespaceName, &Node::isNamespace));
        if (!ns) {
            ns = new NamespaceNode(parent_, namespaceName);
            ns->setAccess(Access::Public);
            ns->setLocation(fromCXSourceLocation(clang_getCursorLocation(cursor)));
        }
        QScopedValueRollback<Aggregate *> setParent(parent_, ns);
        return visitChildren(cursor);
    }
    case CXCursor_FunctionTemplate:
        templateString = templateDecl(cursor);
        Q_FALLTHROUGH();
    case CXCursor_FunctionDecl:
    case CXCursor_CXXMethod:
    case CXCursor_Constructor:
    case CXCursor_Destructor:
    case CXCursor_ConversionFunction: {
        if (findNodeForCursor(qdb_, cursor)) // Was already parsed, probably in another TU
            return CXChildVisit_Continue;
        QString name = functionName(cursor);
        if (ignoredSymbol(name))
            return CXChildVisit_Continue;

        auto *fn = new FunctionNode(parent_, name);
        CXSourceRange range = clang_Cursor_getCommentRange(cursor);
        if (!clang_Range_isNull(range)) {
            QString comment = getSpelling(range);
            if (comment.startsWith("//!")) {
                qsizetype tag = comment.indexOf(QChar('['));
                if (tag > 0) {
                    qsizetype end = comment.indexOf(QChar(']'), ++tag);
                    if (end > 0)
                        fn->setTag(comment.mid(tag, end - tag));
                }
            }
        }
        processFunction(fn, cursor);
        fn->setTemplateDecl(templateString);
        return CXChildVisit_Continue;
    }
#if CINDEX_VERSION >= 36
    case CXCursor_FriendDecl: {
        QScopedValueRollback<bool> setFriend(m_friendDecl, true);
        // Visit the friend functions
        return visitChildren(cursor);
    }
#endif
    case CXCursor_EnumDecl: {
        auto *en = static_cast<EnumNode *>(findNodeForCursor(qdb_, cursor));
        if (en && en->items().size())
            return CXChildVisit_Continue; // Was already parsed, probably in another TU
        QString enumTypeName = fromCXString(clang_getCursorSpelling(cursor));
        if (enumTypeName.isEmpty()) {
            enumTypeName = "anonymous";
            if (parent_ && (parent_->isClassNode() || parent_->isNamespace())) {
                Node *n = parent_->findNonfunctionChild(enumTypeName, &Node::isEnumType);
                if (n)
                    en = static_cast<EnumNode *>(n);
            }
        }
        if (!en) {
            en = new EnumNode(parent_, enumTypeName, clang_EnumDecl_isScoped(cursor));
            en->setAccess(fromCX_CXXAccessSpecifier(clang_getCXXAccessSpecifier(cursor)));
            en->setLocation(fromCXSourceLocation(clang_getCursorLocation(cursor)));
        }

        // Enum values
        visitChildrenLambda(cursor, [&](CXCursor cur) {
            if (clang_getCursorKind(cur) != CXCursor_EnumConstantDecl)
                return CXChildVisit_Continue;

            QString value;
            visitChildrenLambda(cur, [&](CXCursor cur) {
                if (clang_isExpression(clang_getCursorKind(cur))) {
                    value = getSpelling(clang_getCursorExtent(cur));
                    return CXChildVisit_Break;
                }
                return CXChildVisit_Continue;
            });
            if (value.isEmpty()) {
                QLatin1String hex("0x");
                if (!en->items().isEmpty() && en->items().last().value().startsWith(hex)) {
                    value = hex + QString::number(clang_getEnumConstantDeclValue(cur), 16);
                } else {
                    value = QString::number(clang_getEnumConstantDeclValue(cur));
                }
            }

            en->addItem(EnumItem(fromCXString(clang_getCursorSpelling(cur)), value));
            return CXChildVisit_Continue;
        });
        return CXChildVisit_Continue;
    }
    case CXCursor_FieldDecl:
    case CXCursor_VarDecl: {
        if (findNodeForCursor(qdb_, cursor)) // Was already parsed, probably in another TU
            return CXChildVisit_Continue;

        auto access = fromCX_CXXAccessSpecifier(clang_getCXXAccessSpecifier(cursor));
        auto var = new VariableNode(parent_, fromCXString(clang_getCursorSpelling(cursor)));
        var->setAccess(access);
        var->setLocation(fromCXSourceLocation(clang_getCursorLocation(cursor)));
        var->setLeftType(fromCXString(clang_getTypeSpelling(clang_getCursorType(cursor))));
        var->setStatic(kind == CXCursor_VarDecl && parent_->isClassNode());
        return CXChildVisit_Continue;
    }
    case CXCursor_TypedefDecl: {
        if (findNodeForCursor(qdb_, cursor)) // Was already parsed, probably in another TU
            return CXChildVisit_Continue;
        auto *td = new TypedefNode(parent_, fromCXString(clang_getCursorSpelling(cursor)));
        td->setAccess(fromCX_CXXAccessSpecifier(clang_getCXXAccessSpecifier(cursor)));
        td->setLocation(fromCXSourceLocation(clang_getCursorLocation(cursor)));
        // Search to see if this is a Q_DECLARE_FLAGS  (if the type is QFlags<ENUM>)
        visitChildrenLambda(cursor, [&](CXCursor cur) {
            if (clang_getCursorKind(cur) != CXCursor_TemplateRef
                || fromCXString(clang_getCursorSpelling(cur)) != QLatin1String("QFlags"))
                return CXChildVisit_Continue;
            // Found QFlags<XXX>
            visitChildrenLambda(cursor, [&](CXCursor cur) {
                if (clang_getCursorKind(cur) != CXCursor_TypeRef)
                    return CXChildVisit_Continue;
                auto *en =
                        findNodeForCursor(qdb_, clang_getTypeDeclaration(clang_getCursorType(cur)));
                if (en && en->isEnumType())
                    static_cast<EnumNode *>(en)->setFlagsType(td);
                return CXChildVisit_Break;
            });
            return CXChildVisit_Break;
        });
        return CXChildVisit_Continue;
    }
    default:
        if (clang_isDeclaration(kind) && parent_->isClassNode()) {
            // may be a property macro or a static_assert
            // which is not exposed from the clang API
            parseProperty(getSpelling(clang_getCursorExtent(cursor)),
                          fromCXSourceLocation(loc));
        }
        return CXChildVisit_Continue;
    }
}

void ClangVisitor::readParameterNamesAndAttributes(FunctionNode *fn, CXCursor cursor)
{
    Parameters &parameters = fn->parameters();
    // Visit the parameters and attributes
    int i = 0;
    visitChildrenLambda(cursor, [&](CXCursor cur) {
        auto kind = clang_getCursorKind(cur);
        if (kind == CXCursor_AnnotateAttr) {
            QString annotation = fromCXString(clang_getCursorDisplayName(cur));
            if (annotation == QLatin1String("qt_slot")) {
                fn->setMetaness(FunctionNode::Slot);
            } else if (annotation == QLatin1String("qt_signal")) {
                fn->setMetaness(FunctionNode::Signal);
            }
            if (annotation == QLatin1String("qt_invokable"))
                fn->setInvokable(true);
        } else if (kind == CXCursor_CXXOverrideAttr) {
            fn->setOverride(true);
        } else if (kind == CXCursor_ParmDecl) {
            if (i >= parameters.count())
                return CXChildVisit_Break; // Attributes comes before parameters so we can break.
            QString name = fromCXString(clang_getCursorSpelling(cur));
            if (!name.isEmpty()) {
                parameters[i].setName(name);
                // Find the default value
                visitChildrenLambda(cur, [&](CXCursor cur) {
                    if (clang_isExpression(clang_getCursorKind(cur))) {
                        QString defaultValue = getSpelling(clang_getCursorExtent(cur));
                        if (defaultValue.startsWith('=')) // In some cases, the = is part of the range.
                            defaultValue = QStringView{defaultValue}.mid(1).trimmed().toString();
                        if (defaultValue.isEmpty())
                            defaultValue = QStringLiteral("...");
                        parameters[i].setDefaultValue(defaultValue);
                        return CXChildVisit_Break;
                    }
                    return CXChildVisit_Continue;
                });
            }
            ++i;
        }
        return CXChildVisit_Continue;
    });
}

void ClangVisitor::processFunction(FunctionNode *fn, CXCursor cursor)
{
    CXCursorKind kind = clang_getCursorKind(cursor);
    CXType funcType = clang_getCursorType(cursor);
    fn->setAccess(fromCX_CXXAccessSpecifier(clang_getCXXAccessSpecifier(cursor)));
    fn->setLocation(fromCXSourceLocation(clang_getCursorLocation(cursor)));
    if (kind == CXCursor_Constructor
        // a constructor template is classified as CXCursor_FunctionTemplate
        || (kind == CXCursor_FunctionTemplate && fn->name() == parent_->name()))
        fn->setMetaness(FunctionNode::Ctor);
    else if (kind == CXCursor_Destructor)
        fn->setMetaness(FunctionNode::Dtor);
    else
        fn->setReturnType(adjustTypeName(
                fromCXString(clang_getTypeSpelling(clang_getResultType(funcType)))));

    fn->setStatic(clang_CXXMethod_isStatic(cursor));
    fn->setConst(clang_CXXMethod_isConst(cursor));
    fn->setVirtualness(!clang_CXXMethod_isVirtual(cursor)
                               ? FunctionNode::NonVirtual
                               : clang_CXXMethod_isPureVirtual(cursor)
                                       ? FunctionNode::PureVirtual
                                       : FunctionNode::NormalVirtual);
    CXRefQualifierKind refQualKind = clang_Type_getCXXRefQualifier(funcType);
    if (refQualKind == CXRefQualifier_LValue)
        fn->setRef(true);
    else if (refQualKind == CXRefQualifier_RValue)
        fn->setRefRef(true);
    // For virtual functions, determine what it overrides
    // (except for destructor for which we do not want to classify as overridden)
    if (!fn->isNonvirtual() && kind != CXCursor_Destructor)
        setOverridesForFunction(fn, cursor);

    int numArg = clang_getNumArgTypes(funcType);
    Parameters &parameters = fn->parameters();
    parameters.clear();
    parameters.reserve(numArg);
    for (int i = 0; i < numArg; ++i) {
        CXType argType = clang_getArgType(funcType, i);
        if (fn->isCtor()) {
            if (fromCXString(clang_getTypeSpelling(clang_getPointeeType(argType))) == fn->name()) {
                if (argType.kind == CXType_RValueReference)
                    fn->setMetaness(FunctionNode::MCtor);
                else if (argType.kind == CXType_LValueReference)
                    fn->setMetaness(FunctionNode::CCtor);
            }
        } else if ((kind == CXCursor_CXXMethod) && (fn->name() == QLatin1String("operator="))) {
            if (argType.kind == CXType_RValueReference)
                fn->setMetaness(FunctionNode::MAssign);
            else if (argType.kind == CXType_LValueReference)
                fn->setMetaness(FunctionNode::CAssign);
        }
        parameters.append(adjustTypeName(fromCXString(clang_getTypeSpelling(argType))));
        if (argType.kind == CXType_Typedef || argType.kind == CXType_Elaborated) {
            parameters.last().setCanonicalType(fromCXString(
                clang_getTypeSpelling(clang_getCanonicalType(argType))));
        }
    }
    if (parameters.count() > 0) {
        if (parameters.last().type().endsWith(QLatin1String("QPrivateSignal"))) {
            parameters.pop_back(); // remove the QPrivateSignal argument
            parameters.setPrivateSignal();
        }
    }
    if (clang_isFunctionTypeVariadic(funcType))
        parameters.append(QStringLiteral("..."));
    readParameterNamesAndAttributes(fn, cursor);
    // Friend functions are not members
    if (m_friendDecl)
        fn->setRelatedNonmember(true);
}

bool ClangVisitor::parseProperty(const QString &spelling, const Location &loc)
{
    if (!spelling.startsWith(QLatin1String("Q_PROPERTY"))
        && !spelling.startsWith(QLatin1String("QDOC_PROPERTY"))
        && !spelling.startsWith(QLatin1String("Q_OVERRIDE")))
        return false;

    qsizetype lpIdx = spelling.indexOf(QChar('('));
    qsizetype rpIdx = spelling.lastIndexOf(QChar(')'));
    if (lpIdx <= 0 || rpIdx <= lpIdx)
        return false;

    QString signature = spelling.mid(lpIdx + 1, rpIdx - lpIdx - 1);
    signature = signature.simplified();

    QString type;
    QString name;
    QStringList parts = signature.split(QChar(' '), Qt::SkipEmptyParts);
    if (parts.size() < 2)
        return false;
    if (parts.first() == QLatin1String("enum"))
        parts.removeFirst(); // QTBUG-80027

    type = parts.takeFirst();
    if (type == QLatin1String("const") && !parts.empty())
        type += " " + parts.takeFirst();

    if (!parts.empty())
        name = parts.takeFirst();
    else
        return false;

    if (name.front() == QChar('*')) {
        type.append(QChar('*'));
        name.remove(0, 1);
    }
    auto *property = new PropertyNode(parent_, name);
    property->setAccess(Access::Public);
    property->setLocation(loc);
    property->setDataType(type);

    int i = 0;
    while (i < parts.size()) {
        const QString &key = parts.at(i++);
        // Keywords with no associated values
        if (key == "CONSTANT") {
            property->setConstant();
        } else if (key == "REQUIRED") {
            property->setRequired();
        }
        if (i < parts.size()) {
            QString value = parts.at(i++);
            if (key == "READ") {
                qdb_->addPropertyFunction(property, value, PropertyNode::FunctionRole::Getter);
            } else if (key == "WRITE") {
                qdb_->addPropertyFunction(property, value, PropertyNode::FunctionRole::Setter);
                property->setWritable(true);
            } else if (key == "STORED") {
                property->setStored(value.toLower() == "true");
            } else if (key == "BINDABLE") {
                property->setPropertyType(PropertyNode::PropertyType::BindableProperty);
                qdb_->addPropertyFunction(property, value, PropertyNode::FunctionRole::Bindable);
            } else if (key == "RESET") {
                qdb_->addPropertyFunction(property, value, PropertyNode::FunctionRole::Resetter);
            } else if (key == "NOTIFY") {
                qdb_->addPropertyFunction(property, value, PropertyNode::FunctionRole::Notifier);
            }
        }
    }
    return true;
}

/*!
  Given a comment at location \a loc, return a Node for this comment
  \a nextCommentLoc is the location of the next comment so the declaration
  must be inbetween.
  Returns nullptr if no suitable declaration was found between the two comments.
 */
Node *ClangVisitor::nodeForCommentAtLocation(CXSourceLocation loc, CXSourceLocation nextCommentLoc)
{
    ClangVisitor::SimpleLoc docloc;
    clang_getPresumedLocation(loc, nullptr, &docloc.line, &docloc.column);
    auto decl_it = declMap_.upperBound(docloc);
    if (decl_it == declMap_.end())
        return nullptr;

    unsigned int declLine = decl_it.key().line;
    unsigned int nextCommentLine;
    clang_getPresumedLocation(nextCommentLoc, nullptr, &nextCommentLine, nullptr);
    if (nextCommentLine < declLine)
        return nullptr; // there is another comment before the declaration, ignore it.

    // make sure the previous decl was finished.
    if (decl_it != declMap_.begin()) {
        CXSourceLocation prevDeclEnd = clang_getRangeEnd(clang_getCursorExtent(*(std::prev(decl_it))));
        unsigned int prevDeclLine;
        clang_getPresumedLocation(prevDeclEnd, nullptr, &prevDeclLine, nullptr);
        if (prevDeclLine >= docloc.line) {
            // The previous declaration was still going. This is only valid if the previous
            // declaration is a parent of the next declaration.
            auto parent = clang_getCursorLexicalParent(*decl_it);
            if (!clang_equalCursors(parent, *(std::prev(decl_it))))
                return nullptr;
        }
    }
    auto *node = findNodeForCursor(qdb_, *decl_it);
    // borrow the parameter name from the definition
    if (node && node->isFunction(Node::CPP))
        readParameterNamesAndAttributes(static_cast<FunctionNode *>(node), *decl_it);
    return node;
}

/*!
  Get the include paths from the qdoc configuration database
  \a config. Call the initializeParser() in the base class.
  Get the defines list from the qdocconf database.

  \note on \macos, we try to also query the system/framework
  include paths from the compiler.
 */
void ClangCodeParser::initializeParser()
{
    Config &config = Config::instance();
    m_version = config.getString(CONFIG_VERSION);
    auto args = config.getCanonicalPathList(CONFIG_INCLUDEPATHS,
                                            Config::IncludePaths);
#ifdef Q_OS_MACOS
    args.append(Utilities::getInternalIncludePaths(QStringLiteral("clang++")));
#endif
    m_includePaths.clear();
    for (const auto &path : qAsConst(args)) {
        if (!path.isEmpty())
            m_includePaths.append(path.toUtf8());
    }
    m_includePaths.erase(std::unique(m_includePaths.begin(), m_includePaths.end()),
                         m_includePaths.end());
    CppCodeParser::initializeParser();
    m_pchFileDir.reset(nullptr);
    m_allHeaders.clear();
    m_pchName.clear();
    m_defines.clear();
    QSet<QString> accepted;
    {
        const QStringList tmpDefines = config.getStringList(CONFIG_CLANGDEFINES);
        for (const QString &def : tmpDefines) {
            if (!accepted.contains(def)) {
                QByteArray tmp("-D");
                tmp.append(def.toUtf8());
                m_defines.append(tmp.constData());
                accepted.insert(def);
            }
        }
    }
    {
        const QStringList tmpDefines = config.getStringList(CONFIG_DEFINES);
        for (const QString &def : tmpDefines) {
            if (!accepted.contains(def) && !def.contains(QChar('*'))) {
                QByteArray tmp("-D");
                tmp.append(def.toUtf8());
                m_defines.append(tmp.constData());
                accepted.insert(def);
            }
        }
    }
    qCDebug(lcQdoc).nospace() << __FUNCTION__ << " Clang v" << CINDEX_VERSION_MAJOR << '.'
                              << CINDEX_VERSION_MINOR;
}

/*!
 */
void ClangCodeParser::terminateParser()
{
    CppCodeParser::terminateParser();
}

/*!
 */
QString ClangCodeParser::language()
{
    return "Clang";
}

/*!
  Returns a list of extensions for header files.
 */
QStringList ClangCodeParser::headerFileNameFilter()
{
    return QStringList() << "*.ch"
                         << "*.h"
                         << "*.h++"
                         << "*.hh"
                         << "*.hpp"
                         << "*.hxx";
}

/*!
  Returns a list of extensions for source files, i.e. not
  header files.
 */
QStringList ClangCodeParser::sourceFileNameFilter()
{
    return QStringList() << "*.c++"
                         << "*.cc"
                         << "*.cpp"
                         << "*.cxx"
                         << "*.mm";
}

/*!
  Parse the C++ header file identified by \a filePath and add
  the parsed contents to the database. The \a location is used
  for reporting errors.
 */
void ClangCodeParser::parseHeaderFile(const Location & /*location*/, const QString &filePath)
{
    QFileInfo fi(filePath);
    const QString &fileName = fi.fileName();
    const QString &canonicalPath = fi.canonicalPath();

    if (m_allHeaders.contains(fileName, canonicalPath))
        return;

    m_allHeaders.insert(fileName, canonicalPath);
}

static const char *defaultArgs_[] = {
    "-std=c++20",
#ifndef Q_OS_WIN
    "-fPIC",
#else
    "-fms-compatibility-version=19",
#endif
    "-DQ_QDOC",
    "-DQ_CLANG_QDOC",
    "-DQT_DISABLE_DEPRECATED_UP_TO=0",
    "-DQT_ANNOTATE_CLASS(type,...)=static_assert(sizeof(#__VA_ARGS__),#type);",
    "-DQT_ANNOTATE_CLASS2(type,a1,a2)=static_assert(sizeof(#a1,#a2),#type);",
    "-DQT_ANNOTATE_FUNCTION(a)=__attribute__((annotate(#a)))",
    "-DQT_ANNOTATE_ACCESS_SPECIFIER(a)=__attribute__((annotate(#a)))",
    "-Wno-constant-logical-operand",
    "-Wno-macro-redefined",
    "-Wno-nullability-completeness",
    "-fvisibility=default",
    "-ferror-limit=0",
    ("-I" CLANG_RESOURCE_DIR)
};

/*!
  Load the default arguments and the defines into \a args.
  Clear \a args first.
 */
void ClangCodeParser::getDefaultArgs()
{
    m_args.clear();
    m_args.insert(m_args.begin(), std::begin(defaultArgs_), std::end(defaultArgs_));
    // Add the defines from the qdocconf file.
    for (const auto &p : qAsConst(m_defines))
        m_args.push_back(p.constData());
}

static QList<QByteArray> includePathsFromHeaders(const QMultiHash<QString, QString> &allHeaders)
{
    QList<QByteArray> result;
    for (auto it = allHeaders.cbegin(); it != allHeaders.cend(); ++it) {
        const QByteArray path = "-I" + it.value().toLatin1();
        const QByteArray parent =
                "-I" + QDir::cleanPath(it.value() + QLatin1String("/../")).toLatin1();
        if (!result.contains(path))
            result.append(path);
        if (!result.contains(parent))
            result.append(parent);
    }
    return result;
}

/*!
  Load the include paths into \a moreArgs. If no include paths
  were provided, try to guess reasonable include paths.
 */
void ClangCodeParser::getMoreArgs()
{
    if (m_includePaths.isEmpty()) {
        /*
          The include paths provided are inadequate. Make a list
          of reasonable places to look for include files and use
          that list instead.
         */
        qCWarning(lcQdoc) << "No include paths passed to qdoc; guessing reasonable include paths";

        QString basicIncludeDir = QDir::cleanPath(QString(Config::installDir + "/../include"));
        m_moreArgs += "-I" + basicIncludeDir.toLatin1();
        m_moreArgs += includePathsFromHeaders(m_allHeaders);
    } else {
        m_moreArgs = m_includePaths;
    }
}

/*!
  Building the PCH must be possible when there are no .cpp
  files, so it is moved here to its own member function, and
  it is called after the list of header files is complete.
 */
void ClangCodeParser::buildPCH()
{
    if (!m_pchFileDir && !moduleHeader().isEmpty()) {
        m_pchFileDir.reset(new QTemporaryDir(QDir::tempPath() + QLatin1String("/qdoc_pch")));
        if (m_pchFileDir->isValid()) {
            const QByteArray module = moduleHeader().toUtf8();
            QByteArray header;
            QByteArray privateHeaderDir;
            qCDebug(lcQdoc) << "Build and visit PCH for" << moduleHeader();
            // A predicate for std::find_if() to locate a path to the module's header
            // (e.g. QtGui/QtGui) to be used as pre-compiled header
            struct FindPredicate
            {
                enum SearchType { Any, Module, Private };
                QByteArray &candidate_;
                const QByteArray &module_;
                SearchType type_;
                FindPredicate(QByteArray &candidate, const QByteArray &module,
                              SearchType type = Any)
                    : candidate_(candidate), module_(module), type_(type)
                {
                }

                bool operator()(const QByteArray &p) const
                {
                    if (type_ != Any && !p.endsWith(module_))
                        return false;
                    candidate_ = p + "/";
                    switch (type_) {
                    case Any:
                    case Module:
                        candidate_.append(module_);
                        break;
                    case Private:
                        candidate_.append("private");
                        break;
                    default:
                        break;
                    }
                    if (p.startsWith("-I"))
                        candidate_ = candidate_.mid(2);
                    return QFile::exists(QString::fromUtf8(candidate_));
                }
            };

            // First, search for an include path that contains the module name, then any path
            QByteArray candidate;
            auto it = std::find_if(m_includePaths.begin(), m_includePaths.end(),
                                   FindPredicate(candidate, module, FindPredicate::Module));
            if (it == m_includePaths.end())
                it = std::find_if(m_includePaths.begin(), m_includePaths.end(),
                                  FindPredicate(candidate, module, FindPredicate::Any));
            if (it != m_includePaths.end())
                header = candidate;

            // Find the path to module's private headers - currently unused
            it = std::find_if(m_includePaths.begin(), m_includePaths.end(),
                              FindPredicate(candidate, module, FindPredicate::Private));
            if (it != m_includePaths.end())
                privateHeaderDir = candidate;

            if (header.isEmpty()) {
                qWarning() << "(qdoc) Could not find the module header in include paths for module"
                           << module << "  (include paths: " << m_includePaths << ")";
                qWarning() << "       Artificial module header built from header dirs in qdocconf "
                              "file";
            }
            m_args.push_back("-xc++");
            CXTranslationUnit tu;
            QString tmpHeader = m_pchFileDir->path() + "/" + module;
            QFile tmpHeaderFile(tmpHeader);
            if (tmpHeaderFile.open(QIODevice::Text | QIODevice::WriteOnly)) {
                QTextStream out(&tmpHeaderFile);
                if (header.isEmpty()) {
                    for (auto it = m_allHeaders.constKeyValueBegin();
                         it != m_allHeaders.constKeyValueEnd(); ++it) {
                        if (!(*it).first.endsWith(QLatin1String("_p.h"))
                            && !(*it).first.startsWith(QLatin1String("moc_"))) {
                            QString line = QLatin1String("#include \"") + (*it).second
                                    + QLatin1String("/") + (*it).first + QLatin1String("\"");
                            out << line << "\n";
                        }
                    }
                } else {
                    QFileInfo headerFile(header);
                    if (!headerFile.exists()) {
                        qWarning() << "Could not find module header file" << header;
                        return;
                    }
                    out << QLatin1String("#include \"") + header + QLatin1String("\"");
                }
                tmpHeaderFile.close();
            }

            CXErrorCode err =
                    clang_parseTranslationUnit2(index_, tmpHeader.toLatin1().data(), m_args.data(),
                                                static_cast<int>(m_args.size()), nullptr, 0,
                                                flags_ | CXTranslationUnit_ForSerialization, &tu);
            qCDebug(lcQdoc) << __FUNCTION__ << "clang_parseTranslationUnit2(" << tmpHeader << m_args
                            << ") returns" << err;

            printDiagnostics(tu);

            if (!err && tu) {
                m_pchName = m_pchFileDir->path().toUtf8() + "/" + module + ".pch";
                auto error = clang_saveTranslationUnit(tu, m_pchName.constData(),
                                                       clang_defaultSaveOptions(tu));
                if (error) {
                    qCCritical(lcQdoc) << "Could not save PCH file for" << moduleHeader();
                    m_pchName.clear();
                } else {
                    // Visit the header now, as token from pre-compiled header won't be visited
                    // later
                    CXCursor cur = clang_getTranslationUnitCursor(tu);
                    ClangVisitor visitor(m_qdb, m_allHeaders);
                    visitor.visitChildren(cur);
                    qCDebug(lcQdoc) << "PCH built and visited for" << moduleHeader();
                }
            } else {
                m_pchFileDir->remove();
                qCCritical(lcQdoc) << "Could not create PCH file for " << moduleHeader();
            }
            clang_disposeTranslationUnit(tu);
            m_args.pop_back(); // remove the "-xc++";
        }
    }
}

/*!
  Precompile the header files for the current module.
 */
void ClangCodeParser::precompileHeaders()
{
    getDefaultArgs();
    getMoreArgs();
    for (const auto &p : qAsConst(m_moreArgs))
        m_args.push_back(p.constData());

    flags_ = static_cast<CXTranslationUnit_Flags>(CXTranslationUnit_Incomplete
                                                  | CXTranslationUnit_SkipFunctionBodies
                                                  | CXTranslationUnit_KeepGoing);

    index_ = clang_createIndex(1, kClangDontDisplayDiagnostics);

    buildPCH();
    clang_disposeIndex(index_);
}

static float getUnpatchedVersion(QString t)
{
    if (t.count(QChar('.')) > 1)
        t.truncate(t.lastIndexOf(QChar('.')));
    return t.toFloat();
}

/*!
  Get ready to parse the C++ cpp file identified by \a filePath
  and add its parsed contents to the database. \a location is
  used for reporting errors.

  Call matchDocsAndStuff() to do all the parsing and tree building.
 */
void ClangCodeParser::parseSourceFile(const Location & /*location*/, const QString &filePath)
{
    /*
      The set of open namespaces is cleared before parsing
      each source file. The word "source" here means cpp file.
     */
    m_qdb->clearOpenNamespaces();
    m_currentFile = filePath;
    flags_ = static_cast<CXTranslationUnit_Flags>(CXTranslationUnit_Incomplete
                                                  | CXTranslationUnit_SkipFunctionBodies
                                                  | CXTranslationUnit_KeepGoing);

    index_ = clang_createIndex(1, kClangDontDisplayDiagnostics);

    getDefaultArgs();
    if (!m_pchName.isEmpty() && !filePath.endsWith(".mm")) {
        m_args.push_back("-w");
        m_args.push_back("-include-pch");
        m_args.push_back(m_pchName.constData());
    }
    getMoreArgs();
    for (const auto &p : qAsConst(m_moreArgs))
        m_args.push_back(p.constData());

    CXTranslationUnit tu;
    CXErrorCode err =
            clang_parseTranslationUnit2(index_, filePath.toLocal8Bit(), m_args.data(),
                                        static_cast<int>(m_args.size()), nullptr, 0, flags_, &tu);
    qCDebug(lcQdoc) << __FUNCTION__ << "clang_parseTranslationUnit2(" << filePath << m_args
                    << ") returns" << err;
    printDiagnostics(tu);

    if (err || !tu) {
        qWarning() << "(qdoc) Could not parse source file" << filePath << " error code:" << err;
        clang_disposeTranslationUnit(tu);
        clang_disposeIndex(index_);
        return;
    }

    CXCursor tuCur = clang_getTranslationUnitCursor(tu);
    ClangVisitor visitor(m_qdb, m_allHeaders);
    visitor.visitChildren(tuCur);

    CXToken *tokens;
    unsigned int numTokens = 0;
    const QSet<QString> &commands = topicCommands() + metaCommands();
    clang_tokenize(tu, clang_getCursorExtent(tuCur), &tokens, &numTokens);

    for (unsigned int i = 0; i < numTokens; ++i) {
        if (clang_getTokenKind(tokens[i]) != CXToken_Comment)
            continue;
        QString comment = fromCXString(clang_getTokenSpelling(tu, tokens[i]));
        if (!comment.startsWith("/*!"))
            continue;

        auto commentLoc = clang_getTokenLocation(tu, tokens[i]);
        auto loc = fromCXSourceLocation(commentLoc);
        auto end_loc = fromCXSourceLocation(clang_getRangeEnd(clang_getTokenExtent(tu, tokens[i])));
        Doc::trimCStyleComment(loc, comment);

        // Doc constructor parses the comment.
        Doc doc(loc, end_loc, comment, commands, topicCommands());
        if (hasTooManyTopics(doc))
            continue;

        DocList docs;
        QString topic;
        NodeList nodes;
        const TopicList &topics = doc.topicsUsed();
        if (!topics.isEmpty())
            topic = topics[0].m_topic;

        if (topic.isEmpty()) {
            Node *n = nullptr;
            if (i + 1 < numTokens) {
                // Try to find the next declaration.
                CXSourceLocation nextCommentLoc = commentLoc;
                while (i + 2 < numTokens && clang_getTokenKind(tokens[i + 1]) != CXToken_Comment)
                    ++i; // already skip all the tokens that are not comments
                nextCommentLoc = clang_getTokenLocation(tu, tokens[i + 1]);
                n = visitor.nodeForCommentAtLocation(commentLoc, nextCommentLoc);
            }

            if (n) {
                nodes.append(n);
                docs.append(doc);
            } else if (CodeParser::isWorthWarningAbout(doc)) {
                bool future = false;
                if (doc.metaCommandsUsed().contains(COMMAND_SINCE)) {
                    QString sinceVersion = doc.metaCommandArgs(COMMAND_SINCE)[0].first;
                    if (getUnpatchedVersion(sinceVersion) > getUnpatchedVersion(m_version))
                        future = true;
                }
                if (!future) {
                    doc.location().warning(
                            QStringLiteral("Cannot tie this documentation to anything"),
                            QStringLiteral("qdoc found a /*! ... */ comment, but there was no "
                                           "topic command (e.g., '\\%1', '\\%2') in the "
                                           "comment and no function definition following "
                                           "the comment.")
                                    .arg(COMMAND_FN, COMMAND_PAGE));
                }
            }
        } else {
            // Store the namespace scope from lexical parents of the comment
            m_namespaceScope.clear();
            CXCursor cur = clang_getCursor(tu, commentLoc);
            while (true) {
                CXCursorKind kind = clang_getCursorKind(cur);
                if (clang_isTranslationUnit(kind) || clang_isInvalid(kind))
                    break;
                if (kind == CXCursor_Namespace)
                    m_namespaceScope << fromCXString(clang_getCursorSpelling(cur));
                cur = clang_getCursorLexicalParent(cur);
            }
            processTopicArgs(doc, topic, nodes, docs);
        }
        processMetaCommands(nodes, docs);
    }

    clang_disposeTokens(tu, tokens, numTokens);
    clang_disposeTranslationUnit(tu);
    clang_disposeIndex(index_);
    m_namespaceScope.clear();
    s_fn.clear();
}

/*!
  Use clang to parse the function signature from a function
  command. \a location is used for reporting errors. \a fnSignature
  is the string to parse. It is always a function decl.
 */
Node *ClangCodeParser::parseFnArg(const Location &location, const QString &fnSignature, const QString &idTag)
{
    Node *fnNode = nullptr;
    /*
      If the \fn command begins with a tag, then don't try to
      parse the \fn command with clang. Use the tag to search
      for the correct function node. It is an error if it can
      not be found. Return 0 in that case.
    */
    if (!idTag.isEmpty()) {
        fnNode = m_qdb->findFunctionNodeForTag(idTag);
        if (!fnNode) {
            location.error(
                    QStringLiteral("tag \\fn [%1] not used in any include file in current module").arg(idTag));
        } else {
            /*
              The function node was found. Use the formal
              parameter names from the \fn command, because
              they will be the names used in the documentation.
             */
            auto *fn = static_cast<FunctionNode *>(fnNode);
            QStringList leftParenSplit = fnSignature.mid(fnSignature.indexOf(fn->name())).split('(');
            if (leftParenSplit.size() > 1) {
                QStringList rightParenSplit = leftParenSplit[1].split(')');
                if (!rightParenSplit.empty()) {
                    QString params = rightParenSplit[0];
                    if (!params.isEmpty()) {
                        QStringList commaSplit = params.split(',');
                        Parameters &parameters = fn->parameters();
                        if (parameters.count() == commaSplit.size()) {
                            for (int i = 0; i < parameters.count(); ++i) {
                                QStringList blankSplit = commaSplit[i].split(' ', Qt::SkipEmptyParts);
                                if (blankSplit.size() > 1) {
                                    QString pName = blankSplit.last();
                                    // Remove any non-letters from the start of parameter name
                                    auto it = std::find_if(std::begin(pName), std::end(pName),
                                            [](const QChar &c) { return c.isLetter(); });
                                    parameters[i].setName(
                                            pName.remove(0, std::distance(std::begin(pName), it)));
                                }
                            }
                        }
                    }
                }
            }
        }
        return fnNode;
    }
    auto flags = static_cast<CXTranslationUnit_Flags>(CXTranslationUnit_Incomplete
                                                      | CXTranslationUnit_SkipFunctionBodies
                                                      | CXTranslationUnit_KeepGoing);

    CXIndex index = clang_createIndex(1, kClangDontDisplayDiagnostics);

    std::vector<const char *> args(std::begin(defaultArgs_), std::end(defaultArgs_));
    // Add the defines from the qdocconf file.
    for (const auto &p : qAsConst(m_defines))
        args.push_back(p.constData());
    if (!m_pchName.isEmpty()) {
        args.push_back("-w");
        args.push_back("-include-pch");
        args.push_back(m_pchName.constData());
    }
    CXTranslationUnit tu;
    s_fn.clear();
    for (const auto &ns : qAsConst(m_namespaceScope))
        s_fn.prepend("namespace " + ns.toUtf8() + " {");
    s_fn += fnSignature.toUtf8();
    if (!s_fn.endsWith(";"))
        s_fn += "{ }";
    s_fn.append(m_namespaceScope.size(), '}');

    const char *dummyFileName = fnDummyFileName;
    CXUnsavedFile unsavedFile { dummyFileName, s_fn.constData(),
                                static_cast<unsigned long>(s_fn.size()) };
    CXErrorCode err = clang_parseTranslationUnit2(index, dummyFileName, args.data(),
                                                  int(args.size()), &unsavedFile, 1, flags, &tu);
    qCDebug(lcQdoc) << __FUNCTION__ << "clang_parseTranslationUnit2(" << dummyFileName << args
                    << ") returns" << err;
    printDiagnostics(tu);
    if (err || !tu) {
        location.error(QStringLiteral("clang could not parse \\fn %1").arg(fnSignature));
        clang_disposeTranslationUnit(tu);
        clang_disposeIndex(index);
        return fnNode;
    } else {
        /*
          Always visit the tu if one is constructed, because
          it might be possible to find the correct node, even
          if clang detected diagnostics. Only bother to report
          the diagnostics if they stop us finding the node.
         */
        CXCursor cur = clang_getTranslationUnitCursor(tu);
        ClangVisitor visitor(m_qdb, m_allHeaders);
        bool ignoreSignature = false;
        visitor.visitFnArg(cur, &fnNode, ignoreSignature);
        /*
          If the visitor couldn't find a FunctionNode for the
          signature, then print the clang diagnostics if there
          were any.
         */
        if (fnNode == nullptr) {
            unsigned diagnosticCount = clang_getNumDiagnostics(tu);
            const auto &config = Config::instance();
            if (diagnosticCount > 0 && (!config.preparing() || config.singleExec())) {
                bool report = true;
                QStringList signature = fnSignature.split(QChar('('));
                if (signature.size() > 1) {
                    QStringList qualifiedName = signature.at(0).split(QChar(' '));
                    qualifiedName = qualifiedName.last().split(QLatin1String("::"));
                    if (qualifiedName.size() > 1) {
                        QString qualifier = qualifiedName.at(0);
                        int i = 0;
                        while (qualifier.size() > i && !qualifier.at(i).isLetter())
                            qualifier[i++] = QChar(' ');
                        if (i > 0)
                            qualifier = qualifier.simplified();
                        ClassNode *cn = m_qdb->findClassNode(QStringList(qualifier));
                        if (cn && cn->isInternal())
                            report = false;
                    }
                }
                if (report) {
                    location.warning(
                            QStringLiteral("clang couldn't find function when parsing \\fn %1").arg(fnSignature));
                }
            }
        }
    }
    clang_disposeTranslationUnit(tu);
    clang_disposeIndex(index);
    return fnNode;
}

void ClangCodeParser::printDiagnostics(const CXTranslationUnit &translationUnit) const
{
    if (!lcQdocClang().isDebugEnabled())
        return;

    static const auto displayOptions = CXDiagnosticDisplayOptions::CXDiagnostic_DisplaySourceLocation
                                     | CXDiagnosticDisplayOptions::CXDiagnostic_DisplayColumn
                                     | CXDiagnosticDisplayOptions::CXDiagnostic_DisplayOption;

    for (unsigned i = 0, numDiagnostics = clang_getNumDiagnostics(translationUnit); i < numDiagnostics; ++i) {
        auto diagnostic = clang_getDiagnostic(translationUnit, i);
        auto formattedDiagnostic = clang_formatDiagnostic(diagnostic, displayOptions);
        qCDebug(lcQdocClang) << clang_getCString(formattedDiagnostic);
        clang_disposeString(formattedDiagnostic);
        clang_disposeDiagnostic(diagnostic);
    }
}

QT_END_NAMESPACE