aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/cppeditor/cppmodelmanager.cpp
blob: d5d6842e00fe4fc055c5dde73aed9893dcb25358 (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
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "cppmodelmanager.h"

#include "abstracteditorsupport.h"
#include "baseeditordocumentprocessor.h"
#include "compileroptionsbuilder.h"
#include "cppbuiltinmodelmanagersupport.h"
#include "cppcanonicalsymbol.h"
#include "cppcodemodelinspectordumper.h"
#include "cppcodemodelsettings.h"
#include "cppeditorconstants.h"
#include "cppeditortr.h"
#include "cppeditorwidget.h"
#include "cppfindreferences.h"
#include "cppincludesfilter.h"
#include "cppindexingsupport.h"
#include "cpplocatordata.h"
#include "cpplocatorfilter.h"
#include "cppprojectfile.h"
#include "cppsourceprocessor.h"
#include "cpptoolsjsextension.h"
#include "cpptoolsreuse.h"
#include "editordocumenthandle.h"
#include "symbolfinder.h"
#include "symbolsfindfilter.h"

#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/documentmanager.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/find/searchresultwindow.h>
#include <coreplugin/icore.h>
#include <coreplugin/jsexpander.h>
#include <coreplugin/messagemanager.h>
#include <coreplugin/progressmanager/futureprogress.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <coreplugin/vcsmanager.h>

#include <cplusplus/ASTPath.h>
#include <cplusplus/ExpressionUnderCursor.h>
#include <cplusplus/TypeOfExpression.h>

#include <extensionsystem/pluginmanager.h>

#include <coreplugin/session.h>

#include <projectexplorer/buildconfiguration.h>
#include <projectexplorer/gcctoolchain.h>
#include <projectexplorer/kitaspects.h>
#include <projectexplorer/kitmanager.h>
#include <projectexplorer/project.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/projectmanager.h>
#include <projectexplorer/projectmacro.h>
#include <projectexplorer/projectnodes.h>
#include <projectexplorer/projecttree.h>
#include <projectexplorer/target.h>

#include <texteditor/textdocument.h>
#include <texteditor/textdocumentlayout.h>

#include <utils/algorithm.h>
#include <utils/environment.h>
#include <utils/fileutils.h>
#include <utils/hostosinfo.h>
#include <utils/qtcprocess.h>
#include <utils/qtcassert.h>
#include <utils/savefile.h>
#include <utils/synchronizedvalue.h>
#include <utils/temporarydirectory.h>

#include <QAction>
#include <QCoreApplication>
#include <QDebug>
#include <QDir>
#include <QFutureWatcher>
#include <QMutexLocker>
#include <QReadLocker>
#include <QReadWriteLock>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
#include <QTextBlock>
#include <QThread>
#include <QThreadPool>
#include <QTimer>
#include <QWriteLocker>

#include <memory>

#if defined(QTCREATOR_WITH_DUMP_AST) && defined(Q_CC_GNU)
#define WITH_AST_DUMP
#include <iostream>
#include <sstream>
#endif

using namespace Core;
using namespace CPlusPlus;
using namespace ProjectExplorer;
using namespace Utils;

static const bool DumpProjectInfo = qtcEnvironmentVariable("QTC_DUMP_PROJECT_INFO") == "1";

#ifdef QTCREATOR_WITH_DUMP_AST

#include <cxxabi.h>

class DumpAST: protected ASTVisitor
{
public:
    int depth;

    explicit DumpAST(Control *control)
        : ASTVisitor(control), depth(0)
    { }

    void operator()(AST *ast)
    { accept(ast); }

protected:
    virtual bool preVisit(AST *ast)
    {
        std::ostringstream s;
        PrettyPrinter pp(control(), s);
        pp(ast);
        QString code = QString::fromStdString(s.str());
        code.replace('\n', ' ');
        code.replace(QRegularExpression("\\s+"), " ");

        const char *name = abi::__cxa_demangle(typeid(*ast).name(), 0, 0, 0) + 11;

        QByteArray ind(depth, ' ');
        ind += name;

        printf("%-40s %s\n", ind.constData(), qPrintable(code));
        ++depth;
        return true;
    }

    virtual void postVisit(AST *)
    { --depth; }
};

#endif // QTCREATOR_WITH_DUMP_AST

namespace CppEditor {

namespace Internal {

static CppModelManager *m_instance;

class ProjectData
{
public:
    ProjectInfo::ConstPtr projectInfo;
    QFutureWatcher<void> *indexer = nullptr;
    bool fullyIndexed = false;
};

class CppModelManagerPrivate
{
public:
    void setupWatcher(const QFuture<void> &future, Project *project,
                      ProjectData *projectData, CppModelManager *q);

    // Snapshot
    mutable QMutex m_snapshotMutex;
    Snapshot m_snapshot;

    // Project integration
    struct SyncedProjectData
    {
        QHash<Project *, ProjectData> m_projectData;
        QMap<FilePath, QList<ProjectPart::ConstPtr>> m_fileToProjectParts;
        QMap<QString, ProjectPart::ConstPtr> m_projectPartIdToProjectProjectPart;

        // The members below are cached/(re)calculated from the projects and/or their project parts
        bool m_dirty{true};
        FilePaths m_projectFiles;
        HeaderPaths m_headerPaths;
        Macros m_definedMacros;
    };

    Utils::SynchronizedValue<SyncedProjectData> m_lockedProjectData;

    // Editor integration
    mutable QMutex m_cppEditorDocumentsMutex;
    QMap<QString, CppEditorDocumentHandle *> m_cppEditorDocuments;
    QSet<AbstractEditorSupport *> m_extraEditorSupports;

    // Model Manager Supports for e.g. completion and highlighting
    BuiltinModelManagerSupport m_builtinModelManagerSupport;
    std::unique_ptr<ModelManagerSupport> m_extendedModelManagerSupport;
    ModelManagerSupport *m_activeModelManagerSupport = &m_builtinModelManagerSupport;

    // Indexing
    CppIndexingSupport *m_internalIndexingSupport;
    bool m_indexerEnabled;

    QMutex m_fallbackProjectPartMutex;
    ProjectPart::ConstPtr m_fallbackProjectPart;

    CppFindReferences *m_findReferences;

    SymbolFinder m_symbolFinder;
    QThreadPool m_threadPool;

    bool m_enableGC;
    QTimer m_delayedGcTimer;
    QTimer m_fallbackProjectPartTimer;

    CppLocatorData m_locatorData;
    std::unique_ptr<ILocatorFilter> m_locatorFilter;
    std::unique_ptr<ILocatorFilter> m_classesFilter;
    std::unique_ptr<ILocatorFilter> m_includesFilter;
    std::unique_ptr<ILocatorFilter> m_functionsFilter;
    std::unique_ptr<IFindFilter> m_symbolsFindFilter;
    std::unique_ptr<ILocatorFilter> m_currentDocumentFilter;

    QList<Document::DiagnosticMessage> m_diagnosticMessages;

    static void recalculateProjectPartMappings(SyncedProjectData &ld);
    static void ensureUpdated(SyncedProjectData &ld);
    static Utils::FilePaths internalProjectFiles(SyncedProjectData &ld);
    static ProjectExplorer::HeaderPaths internalHeaderPaths(SyncedProjectData &ld);
    static ProjectExplorer::Macros internalDefinedMacros(SyncedProjectData &ld);
};

static CppModelManagerPrivate *d;

} // namespace Internal
using namespace Internal;

const char pp_configuration[] =
    "# 1 \"<configuration>\"\n"
    "#define Q_CREATOR_RUN 1\n"
    "#define __cplusplus 1\n"
    "#define __extension__\n"
    "#define __context__\n"
    "#define __range__\n"
    "#define   restrict\n"
    "#define __restrict\n"
    "#define __restrict__\n"

    "#define __complex__\n"
    "#define __imag__\n"
    "#define __real__\n"

    "#define __builtin_va_arg(a,b) ((b)0)\n"

    "#define _Pragma(x)\n" // C99 _Pragma operator

    "#define __func__ \"\"\n"

    // ### add macros for gcc
    "#define __PRETTY_FUNCTION__ \"\"\n"
    "#define __FUNCTION__ \"\"\n"

    // ### add macros for win32
    "#define __cdecl\n"
    "#define __stdcall\n"
    "#define __thiscall\n"
    "#define QT_WA(x) x\n"
    "#define CALLBACK\n"
    "#define STDMETHODCALLTYPE\n"
    "#define __RPC_FAR\n"
    "#define __declspec(a)\n"
    "#define STDMETHOD(method) virtual HRESULT STDMETHODCALLTYPE method\n"
    "#define __try try\n"
    "#define __except catch\n"
    "#define __finally\n"
    "#define __inline inline\n"
    "#define __forceinline inline\n"
    "#define __pragma(x)\n"
    "#define __w64\n"
    "#define __int64 long long\n"
    "#define __int32 long\n"
    "#define __int16 short\n"
    "#define __int8 char\n"
    "#define __ptr32\n"
    "#define __ptr64\n";

QSet<FilePath> CppModelManager::timeStampModifiedFiles(const QList<Document::Ptr> &documentsToCheck)
{
    QSet<FilePath> sourceFiles;

    for (const Document::Ptr &doc : documentsToCheck) {
        const QDateTime lastModified = doc->lastModified();

        if (!lastModified.isNull()) {
            const FilePath filePath = doc->filePath();

            if (filePath.exists() && filePath.lastModified() != lastModified)
                sourceFiles.insert(filePath);
        }
    }

    return sourceFiles;
}

/*!
 * \brief createSourceProcessor Create a new source processor, which will signal the
 * model manager when a document has been processed.
 *
 * Indexed file is truncated version of fully parsed document: copy of source
 * code and full AST will be dropped when indexing is done.
 *
 * \return a new source processor object, which the caller needs to delete when finished.
 */
CppSourceProcessor *CppModelManager::createSourceProcessor()
{
    return new CppSourceProcessor(snapshot(), [](const Document::Ptr &doc) {
        const Document::Ptr previousDocument = document(doc->filePath());
        const unsigned newRevision = previousDocument.isNull()
                ? 1U
                : previousDocument->revision() + 1;
        doc->setRevision(newRevision);
        emitDocumentUpdated(doc);
        doc->releaseSourceAndAST();
    });
}

const FilePath &CppModelManager::editorConfigurationFileName()
{
    static const FilePath config = FilePath::fromPathPart(u"<per-editor-defines>");
    return config;
}

ModelManagerSupport *CppModelManager::modelManagerSupport(Backend backend)
{
    return backend == Backend::Builtin
            ? &d->m_builtinModelManagerSupport : d->m_activeModelManagerSupport;
}

void CppModelManager::startLocalRenaming(const CursorInEditor &data,
                                         const ProjectPart *projectPart,
                                         RenameCallback &&renameSymbolsCallback,
                                         Backend backend)
{
    modelManagerSupport(backend)
            ->startLocalRenaming(data, projectPart, std::move(renameSymbolsCallback));
}

void CppModelManager::globalRename(const CursorInEditor &data, const QString &replacement,
                                   const std::function<void()> &callback, Backend backend)
{
    modelManagerSupport(backend)->globalRename(data, replacement, callback);
}

void CppModelManager::findUsages(const CursorInEditor &data, Backend backend)
{
    modelManagerSupport(backend)->findUsages(data);
}

void CppModelManager::switchHeaderSource(bool inNextSplit, Backend backend)
{
    const IDocument *currentDocument = EditorManager::currentDocument();
    QTC_ASSERT(currentDocument, return);
    modelManagerSupport(backend)->switchHeaderSource(currentDocument->filePath(), inNextSplit);
}

void CppModelManager::showPreprocessedFile(bool inNextSplit)
{
    const IDocument *doc = EditorManager::currentDocument();
    QTC_ASSERT(doc, return);

    static const auto showError = [](const QString &reason) {
        MessageManager::writeFlashing(Tr::tr("Cannot show preprocessed file: %1")
                                          .arg(reason));
    };
    static const auto showFallbackWarning = [](const QString &reason) {
        MessageManager::writeSilently(Tr::tr("Falling back to built-in preprocessor: %1")
                                          .arg(reason));
    };
    static const auto saveAndOpen = [](const FilePath &filePath, const QByteArray &contents,
                                       bool inNextSplit) {
        SaveFile f(filePath);
        if (!f.open()) {
            showError(Tr::tr("Failed to open output file \"%1\".").arg(filePath.toUserOutput()));
            return;
        }
        f.write(contents);
        if (!f.commit()) {
            showError(Tr::tr("Failed to write output file \"%1\".").arg(filePath.toUserOutput()));
            return;
        }
        f.close();
        openEditor(filePath, inNextSplit, Core::Constants::K_DEFAULT_TEXT_EDITOR_ID);
    };

    const FilePath &filePath = doc->filePath();
    const QString outFileName = filePath.completeBaseName() + "_preprocessed." + filePath.suffix();
    const auto outFilePath = FilePath::fromString(
                TemporaryDirectory::masterTemporaryDirectory()->filePath(outFileName));
    const auto useBuiltinPreprocessor = [filePath, outFilePath, inNextSplit,
                                         contents = doc->contents()] {
        const Document::Ptr preprocessedDoc = snapshot()
                .preprocessedDocument(contents, filePath);
        QByteArray content = R"(/* Created using Qt Creator's built-in preprocessor. */
/* See Tools -> Debug Qt Creator -> Inspect C++ Code Model for the parameters used.
 * Adapt the respective setting in Edit -> Preferences -> C++ -> Code Model to invoke
 * the actual compiler instead.
 */
)";
        saveAndOpen(outFilePath, content.append(preprocessedDoc->utf8Source()), inNextSplit);
    };

    if (CppCodeModelSettings::settingsForFile(filePath).useBuiltinPreprocessor()) {
        useBuiltinPreprocessor();
        return;
    }

    const Project * const project = ProjectTree::currentProject();
    if (!project || !project->activeTarget()
            || !project->activeTarget()->activeBuildConfiguration()) {
        showFallbackWarning(Tr::tr("Could not determine which compiler to invoke."));
        useBuiltinPreprocessor();
        return;
    }

    const Toolchain * tc = nullptr;
    const ProjectFile classifier(filePath, ProjectFile::classify(filePath.toString()));
    if (classifier.isC()) {
        tc = ToolchainKitAspect::cToolchain(project->activeTarget()->kit());
    } else if (classifier.isCxx() || classifier.isHeader()) {
        tc = ToolchainKitAspect::cxxToolchain(project->activeTarget()->kit());
    } else {
        showFallbackWarning(Tr::tr("Could not determine which compiler to invoke."));
        useBuiltinPreprocessor();
        return;
    }

    const bool isGcc = dynamic_cast<const GccToolchain *>(tc);
    const bool isMsvc = !isGcc
            && (tc->typeId() == ProjectExplorer::Constants::MSVC_TOOLCHAIN_TYPEID
                || tc->typeId() == ProjectExplorer::Constants::CLANG_CL_TOOLCHAIN_TYPEID);
    if (!isGcc && !isMsvc) {
        showFallbackWarning(Tr::tr("Could not determine compiler command line."));
        useBuiltinPreprocessor();
        return;
    }

    const ProjectPart::ConstPtr projectPart = Utils::findOrDefault(
                CppModelManager::projectPart(filePath), [](const ProjectPart::ConstPtr &pp) {
        return pp->belongsToProject(ProjectTree::currentProject());
    });
    if (!projectPart) {
        showFallbackWarning(Tr::tr("Could not determine compiler command line."));
        useBuiltinPreprocessor();
        return;
    }

    CompilerOptionsBuilder optionsBuilder(*projectPart);
    optionsBuilder.setNativeMode();
    optionsBuilder.setClStyle(isMsvc);
    optionsBuilder.build(classifier.kind, UsePrecompiledHeaders::No);
    QStringList compilerArgs = optionsBuilder.options();
    if (isGcc)
        compilerArgs.append({"-E", "-o", outFilePath.toUserOutput()});
    else
        compilerArgs.append("/E");
    compilerArgs.append(filePath.toUserOutput());
    const CommandLine compilerCommandLine(tc->compilerCommand(), compilerArgs);
    const auto compiler = new Process(instance());
    compiler->setCommand(compilerCommandLine);
    compiler->setEnvironment(project->activeTarget()->activeBuildConfiguration()->environment());
    connect(compiler, &Process::done, instance(), [compiler, outFilePath, inNextSplit,
                                                      useBuiltinPreprocessor, isMsvc] {
        compiler->deleteLater();
        if (compiler->result() != ProcessResult::FinishedWithSuccess) {
            showFallbackWarning("Compiler failed to run");
            useBuiltinPreprocessor();
            return;
        }
        if (isMsvc)
            saveAndOpen(outFilePath, compiler->rawStdOut(), inNextSplit);
        else
            openEditor(outFilePath, inNextSplit, Core::Constants::K_DEFAULT_TEXT_EDITOR_ID);
    });
    compiler->start();
}

static void foldOrUnfoldComments(bool unfold)
{
    IEditor * const currentEditor = EditorManager::currentEditor();
    if (!currentEditor)
        return;
    const auto editorWidget = qobject_cast<CppEditorWidget*>(currentEditor->widget());
    if (!editorWidget)
        return;
    TextEditor::TextDocument * const textDoc = editorWidget->textDocument();
    QTC_ASSERT(textDoc, return);

    const Document::Ptr cppDoc = CppModelManager::snapshot().preprocessedDocument(
        textDoc->contents(), textDoc->filePath());
    QTC_ASSERT(cppDoc, return);
    cppDoc->tokenize();
    TranslationUnit * const tu = cppDoc->translationUnit();
    if (!tu || !tu->isTokenized())
        return;

    for (int commentTokIndex = 0; commentTokIndex < tu->commentCount(); ++commentTokIndex) {
        const Token &tok = tu->commentAt(commentTokIndex);
        if (tok.kind() != T_COMMENT && tok.kind() != T_DOXY_COMMENT)
            continue;
        const int tokenPos = tu->getTokenPositionInDocument(tok, textDoc->document());
        const int tokenEndPos = tu->getTokenEndPositionInDocument(tok, textDoc->document());
        const QTextBlock tokenBlock = textDoc->document()->findBlock(tokenPos);
        if (!tokenBlock.isValid())
            continue;
        const QTextBlock nextBlock = tokenBlock.next();
        if (!nextBlock.isValid())
            continue;
        if (tokenEndPos < nextBlock.position())
            continue;
        if (TextEditor::TextDocumentLayout::foldingIndent(tokenBlock)
            >= TextEditor::TextDocumentLayout::foldingIndent(nextBlock)) {
            continue;
        }
        if (unfold)
            editorWidget->unfold(tokenBlock);
        else
            editorWidget->fold(tokenBlock);
    }
}

void CppModelManager::foldComments() { foldOrUnfoldComments(false); }
void CppModelManager::unfoldComments() { foldOrUnfoldComments(true); }

class FindUnusedActionsEnabledSwitcher
{
public:
    FindUnusedActionsEnabledSwitcher()
        : actions{ActionManager::command("CppTools.FindUnusedFunctions"),
                  ActionManager::command("CppTools.FindUnusedFunctionsInSubProject")}
    {
        for (Command * const action : actions)
            action->action()->setEnabled(false);
    }
    ~FindUnusedActionsEnabledSwitcher()
    {
        for (Command * const action : actions)
            action->action()->setEnabled(true);
    }
private:
    const QList<Command *> actions;
};
using FindUnusedActionsEnabledSwitcherPtr = std::shared_ptr<FindUnusedActionsEnabledSwitcher>;

static void checkNextFunctionForUnused(
        const QPointer<SearchResult> &search,
        const std::shared_ptr<QFutureInterface<bool>> &findRefsFuture,
        const FindUnusedActionsEnabledSwitcherPtr &actionsSwitcher)
{
    if (!search || findRefsFuture->isCanceled())
        return;
    QVariantMap data = search->userData().toMap();
    QVariant &remainingLinks = data["remaining"];
    QVariantList remainingLinksList = remainingLinks.toList();
    QVariant &activeLinks = data["active"];
    QVariantList activeLinksList = activeLinks.toList();
    if (remainingLinksList.isEmpty()) {
        if (activeLinksList.isEmpty()) {
            search->finishSearch(false);
            findRefsFuture->reportFinished();
        }
        return;
    }
    const auto link = qvariant_cast<Link>(remainingLinksList.takeFirst());
    activeLinksList << QVariant::fromValue(link);
    remainingLinks = remainingLinksList;
    activeLinks = activeLinksList;
    search->setUserData(data);
    CppModelManager::modelManagerSupport(CppModelManager::Backend::Best)
            ->checkUnused(link, search, [search, link, findRefsFuture, actionsSwitcher](const Link &) {
        if (!search || findRefsFuture->isCanceled())
            return;
        const int newProgress = findRefsFuture->progressValue() + 1;
        findRefsFuture->setProgressValueAndText(newProgress,
                                                Tr::tr("Checked %1 of %n function(s)",
                                                       nullptr,
                                                       findRefsFuture->progressMaximum())
                                                    .arg(newProgress));
        QVariantMap data = search->userData().toMap();
        QVariant &activeLinks = data["active"];
        QVariantList activeLinksList = activeLinks.toList();
        QTC_CHECK(activeLinksList.removeOne(QVariant::fromValue(link)));
        activeLinks = activeLinksList;
        search->setUserData(data);
        checkNextFunctionForUnused(search, findRefsFuture, actionsSwitcher);
    });
}

void CppModelManager::findUnusedFunctions(const FilePath &folder)
{
    const auto actionsSwitcher = std::make_shared<FindUnusedActionsEnabledSwitcher>();

    // Step 1: Employ locator to find all functions
    LocatorMatcher *matcher = new LocatorMatcher;
    matcher->setTasks(LocatorMatcher::matchers(MatcherType::Functions));
    const QPointer<SearchResult> search
        = SearchResultWindow::instance()->startNewSearch(Tr::tr("Find Unused Functions"),
                             {},
                             {},
                             SearchResultWindow::SearchOnly,
                             SearchResultWindow::PreserveCaseDisabled,
                             "CppEditor");
    matcher->setParent(search);
    connect(search, &SearchResult::activated, [](const SearchResultItem &item) {
        EditorManager::openEditorAtSearchResult(item);
    });
    SearchResultWindow::instance()->popup(IOutputPane::ModeSwitch | IOutputPane::WithFocus);
    connect(search, &SearchResult::canceled, matcher, [matcher] { delete matcher; });
    connect(matcher, &LocatorMatcher::done, search,
            [matcher, search, folder, actionsSwitcher](bool success) {
        matcher->deleteLater();
        if (!success) {
            search->finishSearch(true);
            return;
        }
        Links links;
        const LocatorFilterEntries entries = matcher->outputData();
        for (const LocatorFilterEntry &entry : entries) {
            static const QStringList prefixBlacklist{"main(", "~", "qHash(", "begin()", "end()",
                    "cbegin()", "cend()", "constBegin()", "constEnd()"};
            if (Utils::anyOf(prefixBlacklist, [&entry](const QString &prefix) {
                    return entry.displayName.startsWith(prefix); })) {
                continue;
            }
            if (!entry.linkForEditor)
                continue;
            const Link link = *entry.linkForEditor;
            if (link.hasValidTarget() && link.targetFilePath.isReadableFile()
                    && (folder.isEmpty() || link.targetFilePath.isChildOf(folder))
                    && ProjectManager::projectForFile(link.targetFilePath)) {
                links << link;
            }
        }
        if (links.isEmpty()) {
            search->finishSearch(false);
            return;
        }
        QVariantMap remainingAndActiveLinks;
        remainingAndActiveLinks.insert("active", QVariantList());
        remainingAndActiveLinks.insert("remaining",
            Utils::transform<QVariantList>(links, [](const Link &l) { return QVariant::fromValue(l);
        }));
        search->setUserData(remainingAndActiveLinks);
        const auto findRefsFuture = std::make_shared<QFutureInterface<bool>>();
        FutureProgress *const progress = ProgressManager::addTask(findRefsFuture->future(),
                                                          Tr::tr("Finding Unused Functions"),
                                                          "CppEditor.FindUnusedFunctions");
        connect(progress,
                &FutureProgress::canceled,
                search,
                [search, future = std::weak_ptr<QFutureInterface<bool>>(findRefsFuture)] {
            search->finishSearch(true);
            if (const auto f = future.lock()) {
                f->cancel();
                f->reportFinished();
            }
        });
        findRefsFuture->setProgressRange(0, links.size());
        connect(search, &SearchResult::canceled, [findRefsFuture] {
            findRefsFuture->cancel();
            findRefsFuture->reportFinished();
        });

        // Step 2: Forward search results one by one to backend to check which functions are unused.
        //         We keep several requests in flight for decent throughput.
        const int inFlightCount = std::min(QThread::idealThreadCount() / 2 + 1, int(links.size()));
        for (int i = 0; i < inFlightCount; ++i)
            checkNextFunctionForUnused(search, findRefsFuture, actionsSwitcher);
    });
    matcher->start();
}

void CppModelManager::checkForUnusedSymbol(SearchResult *search,
                                           const Link &link,
                                           CPlusPlus::Symbol *symbol,
                                           const CPlusPlus::LookupContext &context,
                                           const LinkHandler &callback)
{
    d->m_findReferences->checkUnused(search, link, symbol, context, callback);
}

int argumentPositionOf(const AST *last, const CallAST *callAst)
{
    if (!callAst || !callAst->expression_list)
        return false;

    int num = 0;
    for (ExpressionListAST *it = callAst->expression_list; it; it = it->next) {
        ++num;
        const ExpressionAST *const arg = it->value;
        if (arg->firstToken() <= last->firstToken()
            && arg->lastToken() >= last->lastToken()) {
            return num;
        }
    }
    return 0;
}

SignalSlotType CppModelManager::getSignalSlotType(const FilePath &filePath,
                                                  const QByteArray &content,
                                                  int position)
{
    if (content.isEmpty())
        return SignalSlotType::None;

    // Insert a dummy prefix if we don't have a real one. Otherwise the AST path will not contain
    // anything after the CallAST.
    QByteArray fixedContent = content;
    if (position > 2 && content.mid(position - 2, 2) == "::")
        fixedContent.insert(position, 'x');

    const Snapshot snapshot = CppModelManager::snapshot();
    const Document::Ptr document = snapshot.preprocessedDocument(fixedContent, filePath);
    document->check();
    QTextDocument textDocument(QString::fromUtf8(fixedContent));
    QTextCursor cursor(&textDocument);
    cursor.setPosition(position);

    const QList<AST *> path = ASTPath(document)(cursor);
    if (path.isEmpty())
        return SignalSlotType::None;
    const CallAST *callAst = nullptr;
    for (auto it = path.crbegin(); it != path.crend(); ++it) {
        if ((callAst = (*it)->asCall()))
            break;
    }

    if (!callAst || !callAst->base_expression)
        return SignalSlotType::None;

    const int argumentPosition = argumentPositionOf(path.last(), callAst);
    if (argumentPosition != 2 && argumentPosition != 4)
        return SignalSlotType::None;

    const NameAST *nameAst = nullptr;
    if (const IdExpressionAST * const idAst = callAst->base_expression->asIdExpression())
        nameAst = idAst->name;
    else if (const MemberAccessAST * const ast = callAst->base_expression->asMemberAccess())
        nameAst = ast->member_name;
    if (!nameAst || !nameAst->name)
        return SignalSlotType::None;
    const Identifier * const id = nameAst->name->identifier();
    if (!id)
        return SignalSlotType::None;
    const QString funcName = QString::fromUtf8(id->chars(), id->size());
    if (funcName != "connect" && funcName != "disconnect")
        return SignalSlotType::None;

    Scope *scope = document->globalNamespace();
    for (auto it = path.crbegin(); it != path.crend(); ++it) {
        if (const CompoundStatementAST * const stmtAst = (*it)->asCompoundStatement()) {
            scope = stmtAst->symbol;
            break;
        }
    }
    const LookupContext context(document, snapshot);
    if (const MemberAccessAST * const ast = callAst->base_expression->asMemberAccess()) {
        TypeOfExpression exprType;
        exprType.setExpandTemplates(true);
        exprType.init(document, snapshot);
        const QList<LookupItem> typeMatches = exprType(ast->base_expression, document, scope);
        if (typeMatches.isEmpty())
            return SignalSlotType::None;
        const std::function<const NamedType *(const FullySpecifiedType &)> getNamedType
                = [&getNamedType](const FullySpecifiedType &type ) -> const NamedType * {
            Type * const t = type.type();
            if (const auto namedType = t->asNamedType())
                return namedType;
            if (const auto pointerType = t->asPointerType())
                return getNamedType(pointerType->elementType());
            if (const auto refType = t->asReferenceType())
                return getNamedType(refType->elementType());
            return nullptr;
        };
        const NamedType *namedType = getNamedType(typeMatches.first().type());
        if (!namedType && typeMatches.first().declaration())
            namedType = getNamedType(typeMatches.first().declaration()->type());
        if (!namedType)
            return SignalSlotType::None;
        const ClassOrNamespace * const result = context.lookupType(namedType->name(), scope);
        if (!result)
            return SignalSlotType::None;
        scope = result->rootClass();
        if (!scope)
            return SignalSlotType::None;
    }

    // Is the function a member function of QObject?
    const QList<LookupItem> matches = context.lookup(nameAst->name, scope);
    for (const LookupItem &match : matches) {
        if (!match.scope())
            continue;
        const Class *klass = match.scope()->asClass();
        if (!klass || !klass->name())
            continue;
        const Identifier * const classId = klass->name()->identifier();
        if (classId && QString::fromUtf8(classId->chars(), classId->size()) == "QObject") {
            QString expression;
            LanguageFeatures features = LanguageFeatures::defaultFeatures();
            CPlusPlus::ExpressionUnderCursor expressionUnderCursor(features);
            for (int i = cursor.position(); i > 0; --i)
                if (textDocument.characterAt(i) == '(') {
                    cursor.setPosition(i);
                    break;
                }

            expression = expressionUnderCursor(cursor);

            if (expression.endsWith(QLatin1String("SIGNAL"))
                    || (expression.endsWith(QLatin1String("SLOT")) && argumentPosition == 4))
                return SignalSlotType::OldStyleSignal;

            if (argumentPosition == 2)
                return SignalSlotType::NewStyleSignal;
        }
    }
    return SignalSlotType::None;
}

FollowSymbolUnderCursor &CppModelManager::builtinFollowSymbol()
{
    return d->m_builtinModelManagerSupport.followSymbolInterface();
}

template<class FilterClass>
static void setFilter(std::unique_ptr<FilterClass> &filter,
                      std::unique_ptr<FilterClass> &&newFilter)
{
    QTC_ASSERT(newFilter, return;);
    filter = std::move(newFilter);
}

void CppModelManager::setLocatorFilter(std::unique_ptr<ILocatorFilter> &&filter)
{
    setFilter(d->m_locatorFilter, std::move(filter));
}

void CppModelManager::setClassesFilter(std::unique_ptr<ILocatorFilter> &&filter)
{
    setFilter(d->m_classesFilter, std::move(filter));
}

void CppModelManager::setIncludesFilter(std::unique_ptr<ILocatorFilter> &&filter)
{
    setFilter(d->m_includesFilter, std::move(filter));
}

void CppModelManager::setFunctionsFilter(std::unique_ptr<ILocatorFilter> &&filter)
{
    setFilter(d->m_functionsFilter, std::move(filter));
}

void CppModelManager::setSymbolsFindFilter(std::unique_ptr<IFindFilter> &&filter)
{
    setFilter(d->m_symbolsFindFilter, std::move(filter));
}

void CppModelManager::setCurrentDocumentFilter(std::unique_ptr<ILocatorFilter> &&filter)
{
    setFilter(d->m_currentDocumentFilter, std::move(filter));
}

ILocatorFilter *CppModelManager::locatorFilter()
{
    return d->m_locatorFilter.get();
}

ILocatorFilter *CppModelManager::classesFilter()
{
    return d->m_classesFilter.get();
}

ILocatorFilter *CppModelManager::includesFilter()
{
    return d->m_includesFilter.get();
}

ILocatorFilter *CppModelManager::functionsFilter()
{
    return d->m_functionsFilter.get();
}

IFindFilter *CppModelManager::symbolsFindFilter()
{
    return d->m_symbolsFindFilter.get();
}

ILocatorFilter *CppModelManager::currentDocumentFilter()
{
    return d->m_currentDocumentFilter.get();
}

const FilePath &CppModelManager::configurationFileName()
{
    return Preprocessor::configurationFileName();
}

void CppModelManager::updateModifiedSourceFiles()
{
    const Snapshot snapshot = CppModelManager::snapshot();
    QList<Document::Ptr> documentsToCheck;
    for (const Document::Ptr &document : snapshot)
        documentsToCheck << document;

    updateSourceFiles(timeStampModifiedFiles(documentsToCheck));
}

/*!
    \class CppEditor::CppModelManager
    \brief The CppModelManager keeps tracks of the source files the code model is aware of.

    The CppModelManager manages the source files in a Snapshot object.

    The snapshot is updated in case e.g.
        * New files are opened/edited (Editor integration)
        * A project manager pushes updated project information (Project integration)
        * Files are garbage collected
*/

CppModelManager *CppModelManager::instance()
{
    QTC_ASSERT(m_instance, return nullptr;);
    return m_instance;
}

void CppModelManager::registerJsExtension()
{
    JsExpander::registerGlobalObject("Cpp", [] {
        return new CppToolsJsExtension(&d->m_locatorData);
    });
}

void CppModelManager::initCppTools()
{
    // Objects
    connect(VcsManager::instance(), &VcsManager::repositoryChanged,
            m_instance, &CppModelManager::updateModifiedSourceFiles);
    connect(DocumentManager::instance(), &DocumentManager::filesChangedInternally,
            m_instance, [](const FilePaths &filePaths) {
        updateSourceFiles(toSet(filePaths));
    });

    connect(m_instance, &CppModelManager::documentUpdated,
            &d->m_locatorData, &CppLocatorData::onDocumentUpdated);

    connect(m_instance, &CppModelManager::aboutToRemoveFiles,
            &d->m_locatorData, &CppLocatorData::onAboutToRemoveFiles);

    // Set up builtin filters
    setLocatorFilter(std::make_unique<CppAllSymbolsFilter>());
    setClassesFilter(std::make_unique<CppClassesFilter>());
    setIncludesFilter(std::make_unique<CppIncludesFilter>());
    setFunctionsFilter(std::make_unique<CppFunctionsFilter>());
    setSymbolsFindFilter(std::make_unique<SymbolsFindFilter>());
    setCurrentDocumentFilter(std::make_unique<CppCurrentDocumentFilter>());
    // Setup matchers
    LocatorMatcher::addMatcherCreator(MatcherType::AllSymbols, [] {
        return cppMatchers(MatcherType::AllSymbols);
    });
    LocatorMatcher::addMatcherCreator(MatcherType::Classes, [] {
        return cppMatchers(MatcherType::Classes);
    });
    LocatorMatcher::addMatcherCreator(MatcherType::Functions, [] {
        return cppMatchers(MatcherType::Functions);
    });
    LocatorMatcher::addMatcherCreator(MatcherType::CurrentDocumentSymbols, [] {
        return cppMatchers(MatcherType::CurrentDocumentSymbols);
    });
}

CppModelManager::CppModelManager()
{
    d = new CppModelManagerPrivate;
    m_instance = this;

    CppModelManagerBase::registerSetExtraDiagnosticsCallback(&CppModelManager::setExtraDiagnostics);
    CppModelManagerBase::registerSnapshotCallback(&CppModelManager::snapshot);

    // Used for weak dependency in VcsBaseSubmitEditor
    setObjectName("CppModelManager");
    ExtensionSystem::PluginManager::addObject(this);

    d->m_enableGC = true;

    // Visual C++ has 1MiB, macOSX has 512KiB
    if (HostOsInfo::isWindowsHost() || HostOsInfo::isMacHost())
        d->m_threadPool.setStackSize(2 * 1024 * 1024);

    qRegisterMetaType<QSet<QString> >();
    connect(this, &CppModelManager::sourceFilesRefreshed,
            this, &CppModelManager::onSourceFilesRefreshed);

    d->m_findReferences = new CppFindReferences(this);
    d->m_indexerEnabled = qtcEnvironmentVariable("QTC_NO_CODE_INDEXER") != "1";

    d->m_delayedGcTimer.setObjectName(QLatin1String("CppModelManager::m_delayedGcTimer"));
    d->m_delayedGcTimer.setSingleShot(true);
    connect(&d->m_delayedGcTimer, &QTimer::timeout, this, &CppModelManager::GC);

    auto projectManager = ProjectManager::instance();
    connect(projectManager, &ProjectManager::projectAdded,
            this, &CppModelManager::onProjectAdded);
    connect(projectManager, &ProjectManager::aboutToRemoveProject,
            this, &CppModelManager::onAboutToRemoveProject);
    connect(SessionManager::instance(), &SessionManager::aboutToLoadSession,
            this, &CppModelManager::onAboutToLoadSession);
    connect(projectManager, &ProjectManager::startupProjectChanged,
            this, &CppModelManager::onActiveProjectChanged);

    connect(EditorManager::instance(), &EditorManager::currentEditorChanged,
            this, &CppModelManager::onCurrentEditorChanged);

    connect(ProjectExplorerPlugin::instance(), &ProjectExplorerPlugin::filesRenamed,
            this, &CppModelManager::renameIncludes);

    connect(ICore::instance(), &ICore::coreAboutToClose,
            this, &CppModelManager::onCoreAboutToClose);

    connect(&CppCodeModelSettings::globalInstance(), &CppCodeModelSettings::changed,
            this, &CppModelManager::onSettingsChange);

    d->m_fallbackProjectPartTimer.setSingleShot(true);
    d->m_fallbackProjectPartTimer.setInterval(5000);
    connect(&d->m_fallbackProjectPartTimer, &QTimer::timeout,
            this, &CppModelManager::setupFallbackProjectPart);
    connect(KitManager::instance(), &KitManager::kitsChanged,
            &d->m_fallbackProjectPartTimer, qOverload<>(&QTimer::start));
    connect(this, &CppModelManager::projectPartsRemoved,
            &d->m_fallbackProjectPartTimer, qOverload<>(&QTimer::start));
    connect(this, &CppModelManager::projectPartsUpdated,
            &d->m_fallbackProjectPartTimer, qOverload<>(&QTimer::start));
    setupFallbackProjectPart();

    qRegisterMetaType<CPlusPlus::Document::Ptr>("CPlusPlus::Document::Ptr");
    qRegisterMetaType<QList<Document::DiagnosticMessage>>(
                "QList<CPlusPlus::Document::DiagnosticMessage>");

    d->m_internalIndexingSupport = new CppIndexingSupport;

    initCppTools();
}

CppModelManager::~CppModelManager()
{
    ExtensionSystem::PluginManager::removeObject(this);

    delete d->m_internalIndexingSupport;
    delete d;
}

Snapshot CppModelManager::snapshot()
{
    QMutexLocker locker(&d->m_snapshotMutex);
    return d->m_snapshot;
}

Document::Ptr CppModelManager::document(const FilePath &filePath)
{
    QMutexLocker locker(&d->m_snapshotMutex);
    return d->m_snapshot.document(filePath);
}

/// Replace the document in the snapshot.
///
/// Returns true if successful, false if the new document is out-dated.
bool CppModelManager::replaceDocument(Document::Ptr newDoc)
{
    QMutexLocker locker(&d->m_snapshotMutex);

    Document::Ptr previous = d->m_snapshot.document(newDoc->filePath());
    if (previous && (newDoc->revision() != 0 && newDoc->revision() < previous->revision()))
        // the new document is outdated
        return false;

    d->m_snapshot.insert(newDoc);
    return true;
}

void CppModelManagerPrivate::ensureUpdated(SyncedProjectData &ld)
{
    if (!ld.m_dirty)
        return;

    ld.m_projectFiles = internalProjectFiles(ld);
    ld.m_headerPaths = internalHeaderPaths(ld);
    ld.m_definedMacros = internalDefinedMacros(ld);
    ld.m_dirty = false;
}

FilePaths CppModelManagerPrivate::internalProjectFiles(SyncedProjectData &ld)
{
    FilePaths files;
    for (const ProjectData &projectData : std::as_const(ld.m_projectData)) {
        for (const ProjectPart::ConstPtr &part : projectData.projectInfo->projectParts()) {
            for (const ProjectFile &file : part->files)
                files += file.path;
        }
    }
    FilePath::removeDuplicates(files);
    return files;
}

HeaderPaths CppModelManagerPrivate::internalHeaderPaths(SyncedProjectData &ld)
{
    HeaderPaths headerPaths;
    for (const ProjectData &projectData : std::as_const(ld.m_projectData)) {
        for (const ProjectPart::ConstPtr &part : projectData.projectInfo->projectParts()) {
            for (const HeaderPath &path : part->headerPaths) {
                HeaderPath hp(QDir::cleanPath(path.path), path.type);
                if (!headerPaths.contains(hp))
                    headerPaths.push_back(std::move(hp));
            }
        }
    }
    return headerPaths;
}

static void addUnique(const Macros &newMacros, Macros &macros,
                      QSet<ProjectExplorer::Macro> &alreadyIn)
{
    for (const ProjectExplorer::Macro &macro : newMacros) {
        if (Utils::insert(alreadyIn, macro))
            macros += macro;
    }
}

Macros CppModelManagerPrivate::internalDefinedMacros(SyncedProjectData &ld)
{
    Macros macros;
    QSet<ProjectExplorer::Macro> alreadyIn;
    for (const ProjectData &projectData : std::as_const(ld.m_projectData)) {
        for (const ProjectPart::ConstPtr &part : projectData.projectInfo->projectParts()) {
            addUnique(part->toolchainMacros, macros, alreadyIn);
            addUnique(part->projectMacros, macros, alreadyIn);
        }
    }
    return macros;
}

/// This function will acquire mutexes!
void CppModelManager::dumpModelManagerConfiguration(const QString &logFileId)
{
    const Snapshot globalSnapshot = snapshot();
    const QString globalSnapshotTitle
        = QString::fromLatin1("Global/Indexing Snapshot (%1 Documents)").arg(globalSnapshot.size());

    CppCodeModelInspector::Dumper dumper(globalSnapshot, logFileId);
    dumper.dumpProjectInfos(projectInfos());
    dumper.dumpSnapshot(globalSnapshot, globalSnapshotTitle, /*isGlobalSnapshot=*/ true);
    dumper.dumpWorkingCopy(workingCopy());
    dumper.dumpMergedEntities(headerPaths(),
                              ProjectExplorer::Macro::toByteArray(definedMacros()));
}

QSet<AbstractEditorSupport *> CppModelManager::abstractEditorSupports()
{
    return d->m_extraEditorSupports;
}

void CppModelManager::addExtraEditorSupport(AbstractEditorSupport *editorSupport)
{
    d->m_extraEditorSupports.insert(editorSupport);
}

void CppModelManager::removeExtraEditorSupport(AbstractEditorSupport *editorSupport)
{
    d->m_extraEditorSupports.remove(editorSupport);
}

CppEditorDocumentHandle *CppModelManager::cppEditorDocument(const FilePath &filePath)
{
    if (filePath.isEmpty())
        return nullptr;

    QMutexLocker locker(&d->m_cppEditorDocumentsMutex);
    return d->m_cppEditorDocuments.value(filePath.toString(), 0);
}

BaseEditorDocumentProcessor *CppModelManager::cppEditorDocumentProcessor(const FilePath &filePath)
{
    const auto document = cppEditorDocument(filePath);
    return document ? document->processor() : nullptr;
}

void CppModelManager::registerCppEditorDocument(CppEditorDocumentHandle *editorDocument)
{
    QTC_ASSERT(editorDocument, return);
    const FilePath filePath = editorDocument->filePath();
    QTC_ASSERT(!filePath.isEmpty(), return);

    QMutexLocker locker(&d->m_cppEditorDocumentsMutex);
    QTC_ASSERT(d->m_cppEditorDocuments.value(filePath.toString(), 0) == 0, return);
    d->m_cppEditorDocuments.insert(filePath.toString(), editorDocument);
}

void CppModelManager::unregisterCppEditorDocument(const QString &filePath)
{
    QTC_ASSERT(!filePath.isEmpty(), return);

    static short closedCppDocuments = 0;
    int openCppDocuments = 0;

    {
        QMutexLocker locker(&d->m_cppEditorDocumentsMutex);
        QTC_ASSERT(d->m_cppEditorDocuments.value(filePath, 0), return);
        QTC_CHECK(d->m_cppEditorDocuments.remove(filePath) == 1);
        openCppDocuments = d->m_cppEditorDocuments.size();
    }

    ++closedCppDocuments;
    if (openCppDocuments == 0 || closedCppDocuments == 5) {
        closedCppDocuments = 0;
        delayedGC();
    }
}

QList<int> CppModelManager::references(Symbol *symbol, const LookupContext &context)
{
    return d->m_findReferences->references(symbol, context);
}

void CppModelManager::findUsages(Symbol *symbol, const LookupContext &context)
{
    if (symbol->identifier())
        d->m_findReferences->findUsages(symbol, context);
}

void CppModelManager::renameUsages(Symbol *symbol,
                                   const LookupContext &context,
                                   const QString &replacement,
                                   const std::function<void()> &callback)
{
    if (symbol->identifier())
        d->m_findReferences->renameUsages(symbol, context, replacement, callback);
}

void CppModelManager::renameUsages(const Document::Ptr &doc, const QTextCursor &cursor,
                                   const Snapshot &snapshot, const QString &replacement,
                                   const std::function<void ()> &callback)
{
    Internal::CanonicalSymbol cs(doc, snapshot);
    CPlusPlus::Symbol *canonicalSymbol = cs(cursor);
    if (canonicalSymbol)
        renameUsages(canonicalSymbol, cs.context(), replacement, callback);
}

void CppModelManager::findMacroUsages(const CPlusPlus::Macro &macro)
{
    d->m_findReferences->findMacroUses(macro);
}

void CppModelManager::renameMacroUsages(const CPlusPlus::Macro &macro, const QString &replacement)
{
    d->m_findReferences->renameMacroUses(macro, replacement);
}

void CppModelManager::replaceSnapshot(const Snapshot &newSnapshot)
{
    QMutexLocker snapshotLocker(&d->m_snapshotMutex);
    d->m_snapshot = newSnapshot;
}

WorkingCopy CppModelManager::buildWorkingCopyList()
{
    WorkingCopy workingCopy;

    const QList<CppEditorDocumentHandle *> cppEditorDocumentList = cppEditorDocuments();
    for (const CppEditorDocumentHandle *cppEditorDocument : cppEditorDocumentList) {
        workingCopy.insert(cppEditorDocument->filePath(),
                           cppEditorDocument->contents(),
                           cppEditorDocument->revision());
    }

    for (AbstractEditorSupport *es : std::as_const(d->m_extraEditorSupports))
        workingCopy.insert(es->filePath(), es->contents(), es->revision());

    // Add the project configuration file
    QByteArray conf = codeModelConfiguration();
    conf += ProjectExplorer::Macro::toByteArray(definedMacros());
    workingCopy.insert(configurationFileName(), conf);

    return workingCopy;
}

WorkingCopy CppModelManager::workingCopy()
{
    return buildWorkingCopyList();
}

QByteArray CppModelManager::codeModelConfiguration()
{
    return QByteArray::fromRawData(pp_configuration, qstrlen(pp_configuration));
}

CppLocatorData *CppModelManager::locatorData()
{
    return &d->m_locatorData;
}

static QSet<QString> filteredFilesRemoved(const QSet<QString> &files, int fileSizeLimitInMb,
                                          bool ignoreFiles,
                                          const QString& ignorePattern)
{
    if (fileSizeLimitInMb <= 0 && !ignoreFiles)
        return files;

    QSet<QString> result;
    QList<QRegularExpression> regexes;
    const QStringList wildcards = ignorePattern.split('\n');

    for (const QString &wildcard : wildcards)
        regexes.append(QRegularExpression::fromWildcard(wildcard, Qt::CaseInsensitive,
                                                        QRegularExpression::UnanchoredWildcardConversion));

    for (const QString &file : files) {
        const FilePath filePath = FilePath::fromString(file);
        if (fileSizeLimitInMb > 0 && fileSizeExceedsLimit(filePath, fileSizeLimitInMb))
            continue;
        bool skip = false;
        if (ignoreFiles) {
            for (const QRegularExpression &rx: std::as_const(regexes)) {
                QRegularExpressionMatch match = rx.match(filePath.absoluteFilePath().path());
                if (match.hasMatch()) {
                    const QString msg = Tr::tr("C++ Indexer: Skipping file \"%1\" "
                                               "because its path matches the ignore pattern.")
                                    .arg(filePath.displayName());
                    QMetaObject::invokeMethod(MessageManager::instance(),
                                              [msg] { MessageManager::writeSilently(msg); });
                    skip = true;
                    break;
                }
            }
        }

        if (!skip)
            result << filePath.toString();
    }

    return result;
}

QFuture<void> CppModelManager::updateSourceFiles(const QSet<FilePath> &sourceFiles,
                                                 ProgressNotificationMode mode)
{
    if (sourceFiles.isEmpty() || !d->m_indexerEnabled)
        return QFuture<void>();

    QHash<Project *, QSet<QString>> sourcesPerProject; // TODO: Work with QList from here on?
    for (const FilePath &fp : sourceFiles)
        sourcesPerProject[ProjectManager::projectForFile(fp)] << fp.toString();
    QSet<QString> filteredFiles;
    for (auto it = sourcesPerProject.cbegin(); it != sourcesPerProject.cend(); ++it) {
        const CppCodeModelSettings settings = CppCodeModelSettings::settingsForProject(it.key());
        filteredFiles.unite(filteredFilesRemoved(it.value(),
                                                 settings.effectiveIndexerFileSizeLimitInMb(),
                                                 settings.ignoreFiles(),
                                                 settings.ignorePattern()));
    }

    return d->m_internalIndexingSupport->refreshSourceFiles(filteredFiles, mode);
}

ProjectInfoList CppModelManager::projectInfos()
{
    return Utils::transform<QList<ProjectInfo::ConstPtr>>(d->m_lockedProjectData.readLocked()
                                                              ->m_projectData,
                                                          [](const ProjectData &d) {
                                                              return d.projectInfo;
                                                          });
}

ProjectInfo::ConstPtr CppModelManager::projectInfo(Project *project)
{
    return d->m_lockedProjectData.get<ProjectInfo::ConstPtr>(
        [project](const CppModelManagerPrivate::SyncedProjectData &ld) {
            return ld.m_projectData.value(project).projectInfo;
        });
}

/// \brief Remove all files and their includes (recursively) of given ProjectInfo from the snapshot.
void CppModelManager::removeProjectInfoFilesAndIncludesFromSnapshot(const ProjectInfo &projectInfo)
{
    QMutexLocker snapshotLocker(&d->m_snapshotMutex);
    for (const ProjectPart::ConstPtr &projectPart : projectInfo.projectParts()) {
        for (const ProjectFile &cxxFile : std::as_const(projectPart->files)) {
            const QSet<FilePath> filePaths = d->m_snapshot.allIncludesForDocument(cxxFile.path);
            for (const FilePath &filePath : filePaths)
                d->m_snapshot.remove(filePath);
            d->m_snapshot.remove(cxxFile.path);
        }
    }
}

const QList<CppEditorDocumentHandle *> CppModelManager::cppEditorDocuments()
{
    QMutexLocker locker(&d->m_cppEditorDocumentsMutex);
    return d->m_cppEditorDocuments.values();
}

/// \brief Remove all given files from the snapshot.
void CppModelManager::removeFilesFromSnapshot(const QSet<FilePath> &filesToRemove)
{
    QMutexLocker snapshotLocker(&d->m_snapshotMutex);
    for (const FilePath &file : filesToRemove)
        d->m_snapshot.remove(file);
}

class ProjectInfoComparer
{
public:
    ProjectInfoComparer(const ProjectInfo &oldProjectInfo,
                        const ProjectInfo &newProjectInfo)
        : m_old(oldProjectInfo)
        , m_oldSourceFiles(oldProjectInfo.sourceFiles())
        , m_new(newProjectInfo)
        , m_newSourceFiles(newProjectInfo.sourceFiles())
    {}

    bool definesChanged() const { return m_new.definesChanged(m_old); }
    bool configurationChanged() const { return m_new.configurationChanged(m_old); }
    bool configurationOrFilesChanged() const { return m_new.configurationOrFilesChanged(m_old); }

    QSet<FilePath> addedFiles() const
    {
        QSet<FilePath> addedFilesSet = m_newSourceFiles;
        addedFilesSet.subtract(m_oldSourceFiles);
        return addedFilesSet;
    }

    QSet<FilePath> removedFiles() const
    {
        QSet<FilePath> removedFilesSet = m_oldSourceFiles;
        removedFilesSet.subtract(m_newSourceFiles);
        return removedFilesSet;
    }

    QStringList removedProjectParts()
    {
        QSet<QString> removed = projectPartIds(m_old.projectParts());
        removed.subtract(projectPartIds(m_new.projectParts()));
        return Utils::toList(removed);
    }

    /// Returns a list of common files that have a changed timestamp.
    QSet<FilePath> timeStampModifiedFiles(const Snapshot &snapshot) const
    {
        QSet<FilePath> commonSourceFiles = m_newSourceFiles;
        commonSourceFiles.intersect(m_oldSourceFiles);

        QList<Document::Ptr> documentsToCheck;
        for (const FilePath &file : commonSourceFiles) {
            if (Document::Ptr document = snapshot.document(file))
                documentsToCheck << document;
        }

        return CppModelManager::timeStampModifiedFiles(documentsToCheck);
    }

private:
    static QSet<QString> projectPartIds(const QVector<ProjectPart::ConstPtr> &projectParts)
    {
        QSet<QString> ids;

        for (const ProjectPart::ConstPtr &projectPart : projectParts)
            ids.insert(projectPart->id());

        return ids;
    }

private:
    const ProjectInfo &m_old;
    const QSet<FilePath> m_oldSourceFiles;

    const ProjectInfo &m_new;
    const QSet<FilePath> m_newSourceFiles;
};

void CppModelManagerPrivate::recalculateProjectPartMappings(SyncedProjectData &ld)
{
    ld.m_projectPartIdToProjectProjectPart.clear();
    ld.m_fileToProjectParts.clear();
    for (const ProjectData &projectData : std::as_const(ld.m_projectData)) {
        for (const ProjectPart::ConstPtr &projectPart : projectData.projectInfo->projectParts()) {
            ld.m_projectPartIdToProjectProjectPart[projectPart->id()] = projectPart;
            for (const ProjectFile &cxxFile : projectPart->files) {
                ld.m_fileToProjectParts[cxxFile.path].append(projectPart);
                if (FilePath canonical = cxxFile.path.canonicalPath(); canonical != cxxFile.path)
                    ld.m_fileToProjectParts[canonical].append(projectPart);
            }
        }
    }

    d->m_symbolFinder.clearCache();
}

void CppModelManagerPrivate::setupWatcher(const QFuture<void> &future, Project *project,
                                          ProjectData *projectData, CppModelManager *q)
{
    projectData->indexer = new QFutureWatcher<void>(q);
    const auto handleFinished = [project, watcher = projectData->indexer, q] {
        d->m_lockedProjectData.write([watcher, project](auto &ld) {
            const auto it = ld.m_projectData.find(project);
            if (it != ld.m_projectData.end() && it->indexer == watcher) {
                it->indexer = nullptr;
                it->fullyIndexed = !watcher->isCanceled();
            }
        });

        watcher->disconnect(q);
        watcher->deleteLater();
    };
    q->connect(projectData->indexer, &QFutureWatcher<void>::canceled, q, handleFinished);
    q->connect(projectData->indexer, &QFutureWatcher<void>::finished, q, handleFinished);
    projectData->indexer->setFuture(future);
}

void CppModelManager::updateCppEditorDocuments(bool projectsUpdated)
{
    // Refresh visible documents
    QSet<IDocument *> visibleCppEditorDocuments;
    const QList<IEditor *> editors = EditorManager::visibleEditors();
    for (IEditor *editor: editors) {
        if (IDocument *document = editor->document()) {
            const FilePath filePath = document->filePath();
            if (CppEditorDocumentHandle *theCppEditorDocument = cppEditorDocument(filePath)) {
                visibleCppEditorDocuments.insert(document);
                theCppEditorDocument->processor()->run(projectsUpdated);
            }
        }
    }

    // Mark invisible documents dirty
    QSet<IDocument *> invisibleCppEditorDocuments
        = Utils::toSet(DocumentModel::openedDocuments());
    invisibleCppEditorDocuments.subtract(visibleCppEditorDocuments);
    for (IDocument *document : std::as_const(invisibleCppEditorDocuments)) {
        const FilePath filePath = document->filePath();
        if (CppEditorDocumentHandle *theCppEditorDocument = cppEditorDocument(filePath)) {
            const CppEditorDocumentHandle::RefreshReason refreshReason = projectsUpdated
                    ? CppEditorDocumentHandle::ProjectUpdate
                    : CppEditorDocumentHandle::Other;
            theCppEditorDocument->setRefreshReason(refreshReason);
        }
    }
}

QFuture<void> CppModelManager::updateProjectInfo(const ProjectInfo::ConstPtr &newProjectInfo,
                                                 const QSet<FilePath> &additionalFiles)
{
    if (!newProjectInfo)
        return {};

    QSet<FilePath> filesToReindex;
    QStringList removedProjectParts;
    bool filesRemoved = false;

    Project * const project = projectForProjectInfo(*newProjectInfo);
    if (!project)
        return {};

    ProjectData *projectData = nullptr;

    d->m_lockedProjectData.write([&newProjectInfo,
                                  project,
                                  &filesToReindex,
                                  &removedProjectParts,
                                  &filesRemoved,
                                  &projectData](auto &ld) {
        const QSet<FilePath> newSourceFiles = newProjectInfo->sourceFiles();

        // Check if we can avoid a full reindexing
        const auto it = ld.m_projectData.find(project);
        if (it != ld.m_projectData.end() && it->projectInfo && it->fullyIndexed) {
            ProjectInfoComparer comparer(*it->projectInfo, *newProjectInfo);
            if (comparer.configurationOrFilesChanged()) {
                ld.m_dirty = true;

                // If the project configuration changed, do a full reindexing
                if (comparer.configurationChanged()) {
                    removeProjectInfoFilesAndIncludesFromSnapshot(*it->projectInfo);
                    filesToReindex.unite(newSourceFiles);

                    // The "configuration file" includes all defines and therefore should be updated
                    if (comparer.definesChanged()) {
                        QMutexLocker snapshotLocker(&d->m_snapshotMutex);
                        d->m_snapshot.remove(configurationFileName());
                    }

                // Otherwise check for added and modified files
                } else {
                    const QSet<FilePath> addedFiles = comparer.addedFiles();
                    filesToReindex.unite(addedFiles);

                    const QSet<FilePath> modifiedFiles = comparer.timeStampModifiedFiles(snapshot());
                    filesToReindex.unite(modifiedFiles);
                }

                // Announce and purge the removed files from the snapshot
                const QSet<FilePath> removedFiles = comparer.removedFiles();
                if (!removedFiles.isEmpty()) {
                    filesRemoved = true;
                    emit m_instance->aboutToRemoveFiles(transform<QStringList>(removedFiles, &FilePath::toString));
                    removeFilesFromSnapshot(removedFiles);
                }
            }

            removedProjectParts = comparer.removedProjectParts();

        // A new project was opened/created, do a full indexing
        } else {
            ld.m_dirty = true;
            filesToReindex.unite(newSourceFiles);
        }

        // Update Project/ProjectInfo and File/ProjectPart table
        if (it != ld.m_projectData.end()) {
            if (it->indexer)
                it->indexer->cancel();
            it->projectInfo = newProjectInfo;
            it->fullyIndexed = false;
        }
        projectData = it == ld.m_projectData.end() ? &(
                          ld.m_projectData[project] = ProjectData{newProjectInfo, nullptr, false})
                                                   : &(*it);
        CppModelManagerPrivate::recalculateProjectPartMappings(ld);
    });

    // If requested, dump everything we got
    if (DumpProjectInfo)
        dumpModelManagerConfiguration(QLatin1String("updateProjectInfo"));

    // Remove files from snapshot that are not reachable any more
    if (filesRemoved)
        GC();

    // Announce removed project parts
    if (!removedProjectParts.isEmpty())
        emit m_instance->projectPartsRemoved(removedProjectParts);

    // Announce added project parts
    emit m_instance->projectPartsUpdated(project);

    // Ideally, we would update all the editor documents that depend on the 'filesToReindex'.
    // However, on e.g. a session restore first the editor documents are created and then the
    // project updates come in. That is, there are no reasonable dependency tables based on
    // resolved includes that we could rely on.
    updateCppEditorDocuments(/*projectsUpdated = */ true);

    filesToReindex.unite(additionalFiles);
    // Trigger reindexing
    const QFuture<void> indexingFuture = updateSourceFiles(filesToReindex,
                                                           ForcedProgressNotification);

    // It's safe to do this here, as only the UI thread writes to the map and no other thread
    // uses the indexer value.
    d->setupWatcher(indexingFuture, project, projectData, m_instance);

    return indexingFuture;
}

ProjectPart::ConstPtr CppModelManager::projectPartForId(const QString &projectPartId)
{
    return d->m_lockedProjectData.get<ProjectPart::ConstPtr>(
        [projectPartId](const CppModelManagerPrivate::SyncedProjectData &ld) {
            return ld.m_projectPartIdToProjectProjectPart.value(projectPartId);
        });
}

QList<ProjectPart::ConstPtr> CppModelManager::projectPart(const FilePath &fileName)
{
    std::optional<QList<ProjectPart::ConstPtr>> result;

    d->m_lockedProjectData.read(
        [&fileName, &result](const CppModelManagerPrivate::SyncedProjectData &sd) {
            const auto it = sd.m_fileToProjectParts.constFind(fileName);
            if (it != sd.m_fileToProjectParts.constEnd())
                result = *it;
        });

    if (result)
        return *result;

    const FilePath canonicalPath = fileName.canonicalPath();

    d->m_lockedProjectData.write(
        [&fileName, &canonicalPath, &result](CppModelManagerPrivate::SyncedProjectData &sd) {
            const auto it = sd.m_fileToProjectParts.constFind(canonicalPath);
            if (it == sd.m_fileToProjectParts.constEnd())
                return;
            sd.m_fileToProjectParts.insert(fileName, it.value());
            result = it.value();
        });

    return result.value_or(QList<ProjectPart::ConstPtr>{});
}

QList<ProjectPart::ConstPtr> CppModelManager::projectPartFromDependencies(
        const FilePath &fileName)
{
    QSet<ProjectPart::ConstPtr> parts;
    const FilePaths deps = snapshot().filesDependingOn(fileName);

    for (const FilePath &dep : deps)
        parts.unite(Utils::toSet(projectPart(dep)));

    return parts.values();
}

ProjectPart::ConstPtr CppModelManager::fallbackProjectPart()
{
    QMutexLocker locker(&d->m_fallbackProjectPartMutex);
    return d->m_fallbackProjectPart;
}

bool CppModelManager::isCppEditor(IEditor *editor)
{
    return editor->context().contains(ProjectExplorer::Constants::CXX_LANGUAGE_ID);
}

std::optional<QVersionNumber> CppModelManager::usesClangd(const TextEditor::TextDocument *document)
{
    return d->m_activeModelManagerSupport->usesClangd(document);
}

bool CppModelManager::isClangCodeModelActive()
{
    return d->m_activeModelManagerSupport != &d->m_builtinModelManagerSupport;
}

void CppModelManager::emitDocumentUpdated(Document::Ptr doc)
{
    if (replaceDocument(doc))
        emit m_instance->documentUpdated(doc);
}

void CppModelManager::emitAbstractEditorSupportContentsUpdated(const QString &filePath,
                                                               const QString &sourcePath,
                                                               const QByteArray &contents)
{
    emit m_instance->abstractEditorSupportContentsUpdated(filePath, sourcePath, contents);
}

void CppModelManager::emitAbstractEditorSupportRemoved(const QString &filePath)
{
    emit m_instance->abstractEditorSupportRemoved(filePath);
}

void CppModelManager::onProjectAdded(Project *)
{
    d->m_lockedProjectData.writeLocked()->m_dirty = true;
}

void CppModelManager::delayedGC()
{
    if (d->m_enableGC)
        d->m_delayedGcTimer.start(500);
}

static QStringList removedProjectParts(const QStringList &before, const QStringList &after)
{
    QSet<QString> b = Utils::toSet(before);
    b.subtract(Utils::toSet(after));

    return Utils::toList(b);
}

void CppModelManager::onAboutToRemoveProject(Project *project)
{
    QStringList idsOfRemovedProjectParts;

    d->m_lockedProjectData.write([project, &idsOfRemovedProjectParts](
                                     CppModelManagerPrivate::SyncedProjectData &sd) {
        sd.m_dirty = true;
        const QStringList projectPartsIdsBefore = sd.m_projectPartIdToProjectProjectPart.keys();

        sd.m_projectData.remove(project);
        CppModelManagerPrivate::recalculateProjectPartMappings(sd);

        const QStringList projectPartsIdsAfter = sd.m_projectPartIdToProjectProjectPart.keys();
        idsOfRemovedProjectParts = removedProjectParts(projectPartsIdsBefore, projectPartsIdsAfter);
    });

    if (!idsOfRemovedProjectParts.isEmpty())
        emit m_instance->projectPartsRemoved(idsOfRemovedProjectParts);

    delayedGC();
}

void CppModelManager::onActiveProjectChanged(Project *project)
{
    if (!project)
        return; // Last project closed.

    if (!d->m_lockedProjectData.readLocked()->m_projectData.contains(project))
        return; // Not yet known to us.

    updateCppEditorDocuments();
}

void CppModelManager::onSourceFilesRefreshed()
{
    if (CppIndexingSupport::isFindErrorsIndexingActive()) {
        QTimer::singleShot(1, QCoreApplication::instance(), &QCoreApplication::quit);
        qDebug("FindErrorsIndexing: Done, requesting Qt Creator to quit.");
    }
}

void CppModelManager::onCurrentEditorChanged(IEditor *editor)
{
    if (!editor || !editor->document())
        return;

    const FilePath filePath = editor->document()->filePath();
    if (CppEditorDocumentHandle *theCppEditorDocument = cppEditorDocument(filePath)) {
        const CppEditorDocumentHandle::RefreshReason refreshReason
                = theCppEditorDocument->refreshReason();
        if (refreshReason != CppEditorDocumentHandle::None) {
            const bool projectsChanged = refreshReason == CppEditorDocumentHandle::ProjectUpdate;
            theCppEditorDocument->setRefreshReason(CppEditorDocumentHandle::None);
            theCppEditorDocument->processor()->run(projectsChanged);
        }
    }
}

void CppModelManager::onAboutToLoadSession()
{
    if (d->m_delayedGcTimer.isActive())
        d->m_delayedGcTimer.stop();
    GC();
}

QSet<QString> CppModelManager::dependingInternalTargets(const FilePath &file)
{
    QSet<QString> result;
    const Snapshot snapshot = CppModelManager::snapshot();
    QTC_ASSERT(snapshot.contains(file), return result);
    bool wasHeader;
    const FilePath correspondingFile
            = correspondingHeaderOrSource(file, &wasHeader, CacheUsage::ReadOnly);
    const FilePaths dependingFiles = snapshot.filesDependingOn(
                wasHeader ? file : correspondingFile);
    for (const FilePath &fn : std::as_const(dependingFiles)) {
        for (const ProjectPart::ConstPtr &part : projectPart(fn))
            result.insert(part->buildSystemTarget);
    }
    return result;
}

QSet<QString> CppModelManager::internalTargets(const FilePath &filePath)
{
    QTC_ASSERT(m_instance, return {});

    const QList<ProjectPart::ConstPtr> projectParts = projectPart(filePath);
    // if we have no project parts it's most likely a header with declarations only and CMake based
    if (projectParts.isEmpty())
        return dependingInternalTargets(filePath);
    QSet<QString> targets;
    for (const ProjectPart::ConstPtr &part : projectParts) {
        targets.insert(part->buildSystemTarget);
        if (part->buildTargetType != BuildTargetType::Executable)
            targets.unite(dependingInternalTargets(filePath));
    }
    return targets;
}

// Note: This function assumes that neither the project tree nor the code model are aware of
//       the renamings yet, i.e. they still refer to the old file paths.
void CppModelManager::renameIncludes(const QList<std::pair<FilePath, FilePath>> &oldAndNewPaths)
{
    for (const auto &[oldFilePath, newFilePath] : oldAndNewPaths) {
        if (oldFilePath.isEmpty() || newFilePath.isEmpty())
            continue;

        const TextEditor::PlainRefactoringFileFactory changes;

        QString oldFileName = oldFilePath.fileName();
        QString newFileName = newFilePath.fileName();
        const bool isUiFile = oldFilePath.suffix() == "ui" && newFilePath.suffix() == "ui";
        const bool moved = oldFilePath.absolutePath() != newFilePath.absolutePath();
        if (isUiFile) {
            if (moved)
                return; // This is out of scope.
            oldFileName = "ui_" + oldFilePath.baseName() + ".h";
            newFileName = "ui_" + newFilePath.baseName() + ".h";
        }
        static const auto getProductNode = [](const FilePath &filePath) -> const Node * {
            const Node * const fileNode = ProjectTree::nodeForFile(filePath);
            if (!fileNode)
                return nullptr;
            const ProjectNode *productNode = fileNode->parentProjectNode();
            while (productNode && !productNode->isProduct())
                productNode = productNode->parentProjectNode();
            if (!productNode)
                productNode = fileNode->getProject()->rootProjectNode();
            return productNode;
        };
        const Node * const productNodeForUiFile = isUiFile ? getProductNode(oldFilePath) : nullptr;
        if (isUiFile && !productNodeForUiFile)
            continue;

        const QList<Snapshot::IncludeLocation> locations = snapshot().includeLocationsOfDocument(
            isUiFile ? FilePath::fromString(oldFileName) : oldFilePath);
        for (const Snapshot::IncludeLocation &loc : locations) {
            const FilePath includingFileOld = loc.first->filePath();
            FilePath includingFileNew = includingFileOld;
            for (const auto &pathPair : oldAndNewPaths) {
                if (includingFileNew == pathPair.first) {
                    includingFileNew = pathPair.second;
                    break;
                }
            }

            // Larger projects can easily have more than one ui file with the same name.
            // Replace only if ui file and including source file belong to the same product.
            if (isUiFile && getProductNode(includingFileOld) != productNodeForUiFile)
                continue;

            TextEditor::RefactoringFilePtr file = changes.file(includingFileNew);
            const QTextBlock &block = file->document()->findBlockByNumber(loc.second - 1);
            const FilePath relPathOld = FilePath::fromString(FilePath::calcRelativePath(
                oldFilePath.toString(), includingFileOld.parentDir().toString()));
            const FilePath relPathNew = FilePath::fromString(FilePath::calcRelativePath(
                newFilePath.toString(), includingFileNew.parentDir().toString()));
            int replaceStart = block.text().indexOf(relPathOld.toString());
            QString oldString;
            QString newString;
            if (isUiFile || replaceStart == -1) {
                replaceStart = block.text().indexOf(oldFileName);
                oldString = oldFileName;
                newString = newFileName;
            } else {
                oldString = relPathOld.toString();
                newString = relPathNew.toString();
            }
            if (replaceStart > -1 && oldString != newString) {
                ChangeSet changeSet;
                changeSet.replace(block.position() + replaceStart,
                                  block.position() + replaceStart + oldString.length(),
                                  newString);
                file->setChangeSet(changeSet);
                file->apply();
            }
        }
    }
}

// Return the class name which function belongs to
static const char *belongingClassName(const Function *function)
{
    if (!function)
        return nullptr;

    if (auto funcName = function->name()) {
        if (auto qualifiedNameId = funcName->asQualifiedNameId()) {
            if (const Name *funcBaseName = qualifiedNameId->base()) {
                if (auto identifier = funcBaseName->identifier())
                    return identifier->chars();
            }
        }
    }

    return nullptr;
}

QSet<QString> CppModelManager::symbolsInFiles(const QSet<FilePath> &files) const
{
    QSet<QString> uniqueSymbols;
    const Snapshot cppSnapShot = snapshot();

    // Iterate over the files and get interesting symbols
    for (const FilePath &file : files) {
        // Add symbols from the C++ code model
        const CPlusPlus::Document::Ptr doc = cppSnapShot.document(file);
        if (!doc.isNull() && doc->control()) {
            const CPlusPlus::Control *ctrl = doc->control();
            CPlusPlus::Symbol **symPtr = ctrl->firstSymbol(); // Read-only
            while (symPtr != ctrl->lastSymbol()) {
                const CPlusPlus::Symbol *sym = *symPtr;

                const CPlusPlus::Identifier *symId = sym->identifier();
                // Add any class, function or namespace identifiers
                if ((sym->asClass() || sym->asFunction() || sym->asNamespace()) && symId
                    && symId->chars()) {
                    uniqueSymbols.insert(QString::fromUtf8(symId->chars()));
                }

                // Handle specific case : get "Foo" in "void Foo::function() {}"
                if (sym->asFunction() && !sym->asFunction()->asDeclaration()) {
                    const char *className = belongingClassName(sym->asFunction());
                    if (className)
                        uniqueSymbols.insert(QString::fromUtf8(className));
                }

                ++symPtr;
            }
        }
    }
    return uniqueSymbols;
}

void CppModelManager::onCoreAboutToClose()
{
    d->m_fallbackProjectPartTimer.disconnect();
    d->m_fallbackProjectPartTimer.stop();
    ProgressManager::cancelTasks(Constants::TASK_INDEX);
    d->m_enableGC = false;
}

void CppModelManager::onSettingsChange(Project *project)
{
    ProjectInfoList info;
    if (project)
        info << projectInfo(project);
    else
        info << projectInfos();
    for (const ProjectInfo::ConstPtr &pi : std::as_const(info)) {
        const CppCodeModelSettings newSettings = CppCodeModelSettings::settingsForProject(
            pi->projectFilePath());
        if (pi->settings().data() != newSettings.data())
            updateProjectInfo(ProjectInfo::cloneWithNewSettings(pi, newSettings));
    }
}

void CppModelManager::setupFallbackProjectPart()
{
    ToolchainInfo tcInfo;
    RawProjectPart rpp;
    rpp.setMacros(definedMacros());
    rpp.setHeaderPaths(headerPaths());
    rpp.setQtVersion(QtMajorVersion::Qt5);

    // Do not activate ObjectiveCExtensions since this will lead to the
    // "objective-c++" language option for a project-less *.cpp file.
    LanguageExtensions langExtensions = LanguageExtension::All;
    langExtensions &= ~LanguageExtensions(LanguageExtension::ObjectiveC);

    // TODO: Use different fallback toolchain for different kinds of files?
    const Kit * const defaultKit = KitManager::isLoaded() ? KitManager::defaultKit() : nullptr;
    const Toolchain * const defaultTc = defaultKit
            ? ToolchainKitAspect::cxxToolchain(defaultKit) : nullptr;
    if (defaultKit && defaultTc) {
        FilePath sysroot = SysRootKitAspect::sysRoot(defaultKit);
        if (sysroot.isEmpty())
            sysroot = FilePath::fromString(defaultTc->sysRoot());
        Utils::Environment env = defaultKit->buildEnvironment();
        tcInfo = ToolchainInfo(defaultTc, sysroot, env);
        const auto macroInspectionWrapper = [runner = tcInfo.macroInspectionRunner](
                const QStringList &flags) {
            Toolchain::MacroInspectionReport report = runner(flags);
            report.languageVersion = LanguageVersion::LatestCxx;
            return report;
        };
        tcInfo.macroInspectionRunner = macroInspectionWrapper;
    }

    const auto part = ProjectPart::create({}, rpp, {}, {}, {}, langExtensions, {}, tcInfo);
    {
        QMutexLocker locker(&d->m_fallbackProjectPartMutex);
        d->m_fallbackProjectPart = part;
    }
    emit m_instance->fallbackProjectPartUpdated();
}

void CppModelManager::GC()
{
    if (!d->m_enableGC)
        return;

    // Collect files of opened editors and editor supports (e.g. ui code model)
    FilePaths filesInEditorSupports;
    const QList<CppEditorDocumentHandle *> editorDocuments = cppEditorDocuments();
    for (const CppEditorDocumentHandle *editorDocument : editorDocuments)
        filesInEditorSupports << editorDocument->filePath();

    const QSet<AbstractEditorSupport *> abstractEditorSupportList = abstractEditorSupports();
    for (AbstractEditorSupport *abstractEditorSupport : abstractEditorSupportList)
        filesInEditorSupports << abstractEditorSupport->filePath();

    Snapshot currentSnapshot = snapshot();
    QSet<FilePath> reachableFiles;
    // The configuration file is part of the project files, which is just fine.
    // If single files are open, without any project, then there is no need to
    // keep the configuration file around.
    FilePaths todo = filesInEditorSupports + projectFiles();

    // Collect all files that are reachable from the project files
    while (!todo.isEmpty()) {
        const FilePath filePath = todo.last();
        todo.removeLast();

        if (!Utils::insert(reachableFiles, filePath))
            continue;

        if (Document::Ptr doc = currentSnapshot.document(filePath))
            todo += doc->includedFiles();
    }

    // Find out the files in the current snapshot that are not reachable from the project files
    QStringList notReachableFiles;
    Snapshot newSnapshot;
    for (Snapshot::const_iterator it = currentSnapshot.begin(); it != currentSnapshot.end(); ++it) {
        const FilePath &fileName = it.key();

        if (reachableFiles.contains(fileName))
            newSnapshot.insert(it.value());
        else
            notReachableFiles.append(fileName.toString());
    }

    // Announce removing files and replace the snapshot
    emit m_instance->aboutToRemoveFiles(notReachableFiles);
    replaceSnapshot(newSnapshot);
    emit m_instance->gcFinished();
}

void CppModelManager::finishedRefreshingSourceFiles(const QSet<QString> &files)
{
    emit m_instance->sourceFilesRefreshed(files);
}

void CppModelManager::activateClangCodeModel(
        std::unique_ptr<ModelManagerSupport> &&modelManagerSupport)
{
    d->m_extendedModelManagerSupport = std::move(modelManagerSupport);
    d->m_activeModelManagerSupport = d->m_extendedModelManagerSupport.get();
}

CppCompletionAssistProvider *CppModelManager::completionAssistProvider()
{
    return d->m_builtinModelManagerSupport.completionAssistProvider();
}

TextEditor::BaseHoverHandler *CppModelManager::createHoverHandler()
{
    return d->m_builtinModelManagerSupport.createHoverHandler();
}

void CppModelManager::followSymbol(const CursorInEditor &data,
                                   const LinkHandler &processLinkCallback,
                                   bool resolveTarget, bool inNextSplit,
                                   FollowSymbolMode mode, Backend backend)
{
    modelManagerSupport(backend)->followSymbol(data, processLinkCallback, mode,
                                               resolveTarget, inNextSplit);
}

void CppModelManager::followSymbolToType(const CursorInEditor &data,
                                         const LinkHandler &processLinkCallback,
                                         bool inNextSplit, Backend backend)
{
    modelManagerSupport(backend)->followSymbolToType(data, processLinkCallback,
                                                                 inNextSplit);
}

void CppModelManager::switchDeclDef(const CursorInEditor &data,
                                    const LinkHandler &processLinkCallback,
                                    Backend backend)
{
    modelManagerSupport(backend)->switchDeclDef(data, processLinkCallback);
}

BaseEditorDocumentProcessor *CppModelManager::createEditorDocumentProcessor(
    TextEditor::TextDocument *baseTextDocument)
{
    return d->m_activeModelManagerSupport->createEditorDocumentProcessor(baseTextDocument);
}

CppIndexingSupport *CppModelManager::indexingSupport()
{
    return d->m_internalIndexingSupport;
}

FilePaths CppModelManager::projectFiles()
{
    return d->m_lockedProjectData.update<FilePaths>(
        [](CppModelManagerPrivate::SyncedProjectData &sd) {
            CppModelManagerPrivate::ensureUpdated(sd);
            return sd.m_projectFiles;
        });
}

HeaderPaths CppModelManager::headerPaths()
{
    return d->m_lockedProjectData.update<HeaderPaths>(
        [](CppModelManagerPrivate::SyncedProjectData &sd) {
            CppModelManagerPrivate::ensureUpdated(sd);
            return sd.m_headerPaths;
        });
}

void CppModelManager::setHeaderPaths(const HeaderPaths &headerPaths)
{
    d->m_lockedProjectData.writeLocked()->m_headerPaths = headerPaths;
}

Macros CppModelManager::definedMacros()
{
    return d->m_lockedProjectData.update<Macros>([](CppModelManagerPrivate::SyncedProjectData &sd) {
        CppModelManagerPrivate::ensureUpdated(sd);
        return sd.m_definedMacros;
    });
}

void CppModelManager::enableGarbageCollector(bool enable)
{
    d->m_delayedGcTimer.stop();
    d->m_enableGC = enable;
}

SymbolFinder *CppModelManager::symbolFinder()
{
    return &d->m_symbolFinder;
}

QThreadPool *CppModelManager::sharedThreadPool()
{
    return &d->m_threadPool;
}

bool CppModelManager::setExtraDiagnostics(const FilePath &filePath,
                                          const QString &kind,
                                          const QList<Document::DiagnosticMessage> &diagnostics)
{
    d->m_diagnosticMessages = diagnostics;
    emit m_instance->diagnosticsChanged(filePath, kind);
    return true;
}

const QList<Document::DiagnosticMessage> CppModelManager::diagnosticMessages()
{
    return d->m_diagnosticMessages;
}

} // namespace CppEditor