cpp_code_analysis 0.2.0

The analysis layer of cpp_ls: the preprocessor, symbol scopes, type inference and the semantic checks.
Documentation
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
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
//! What each name in a file is — the classifications a highlighter draws colours from.
//!
//! The interesting cases are the ones where two kinds look alike from the text: a parameter against a local, a
//! member function against a free one, an enumerator against a variable, and a macro (which is not a declaration
//! in the C++ tree at all). Each of them is pinned here, and so is the refusal: a name this analysis cannot place
//! gets **no** classification rather than a plausible one.

use cpp_code_analysis::semantic::{Name, NameKind, Provenance};
use cpp_code_analysis::{
    CompilerConfig, MemoryFiles, OpenDocuments, Session, SessionFiles, WatchFilter,
};
use cpp_code_analysis::{DeclKind, DeclModifiers, Known};

fn session_with(files: &[(&str, &str)]) -> Session<MemoryFiles> {
    let mut memory = MemoryFiles::new();
    for (path, source) in files {
        memory = memory.with_file(*path, *source);
    }

    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files(
        files
            .iter()
            .map(|(path, _)| std::path::PathBuf::from(*path)),
    );

    // **The ask, and then the pump** - see `tests/completion.rs`'s `cooked_view`. A view is of the file's *cooked
    // reading*, and a rendering is built because something asked for it.
    for (path, _) in files {
        session.want_cooked_reading(std::path::Path::new(path));
    }
    session.index_everything();

    session
}

/// Every classification in one file, as `(text, kind, is a declaration)` in source order.
fn classified(source: &str) -> Vec<(String, NameKind, bool)> {
    let session = session_with(&[("/p/a.cpp", source)]);
    let view = session.view("/p/a.cpp").expect("the file is held");

    session
        .classified_names(&view)
        .into_iter()
        .map(|name: Name| {
            (
                source[name.range.start_offset..name.range.end_offset()].to_string(),
                name.kind,
                name.declaration,
            )
        })
        .collect()
}

/// The one classification of a spelling, if there is exactly one.
fn kind_of(source: &str, spelling: &str) -> Option<NameKind> {
    let found: Vec<NameKind> = classified(source)
        .into_iter()
        .filter(|(text, _, _)| text == spelling)
        .map(|(_, kind, _)| kind)
        .collect();

    found.first().copied()
}

/// Every classification of one spelling, as `(kind, is a declaration)` in source order.
fn all_of(source: &str, spelling: &str) -> Vec<(NameKind, bool)> {
    classified(source)
        .into_iter()
        .filter(|(text, _, _)| text == spelling)
        .map(|(_, kind, declaration)| (kind, declaration))
        .collect()
}

/// **Every kind the model can tell apart**, in one file: the cases that look alike from the text are the ones
/// worth pinning, and they are all here.
#[test]
fn each_kind_of_name_is_classified_by_what_declares_it() {
    let source = "\
#define LIMIT 8
namespace ns {
enum Color { Red, Green };
struct Widget {
    int size;
    int scaled(int factor) const;
};
int count(int total) {
    int local = total;
    return local;
}
}
";
    let cases = [
        ("LIMIT", Some(NameKind::Macro)),
        ("ns", Some(NameKind::Namespace)),
        ("Color", Some(NameKind::Type)),
        ("Widget", Some(NameKind::Type)),
        ("Red", Some(NameKind::EnumMember)),
        // A parameter and a local are both `Variable` bindings; the scope they were bound in is what separates
        // them, and it is the scope model's own distinction rather than a second reading.
        ("factor", Some(NameKind::Parameter)),
        ("total", Some(NameKind::Parameter)),
        ("local", Some(NameKind::Variable)),
        ("size", Some(NameKind::Variable)),
        // A function declared inside a class is a method, and the same shape outside one is not.
        ("scaled", Some(NameKind::Method)),
        ("count", Some(NameKind::Function)),
    ];

    for (spelling, expected) in cases {
        assert_eq!(kind_of(source, spelling), expected, "`{spelling}`");
    }
}

/// The declaration's own name and a use of it are the same kind, and only one of them is a declaration.
#[test]
fn a_use_is_classified_like_the_declaration_it_names() {
    let source = "\
int size(int value);
int f() { return size(1); }
";
    let size: Vec<(String, NameKind, bool)> = classified(source)
        .into_iter()
        .filter(|(text, _, _)| text == "size")
        .collect();

    assert_eq!(size.len(), 2, "the declaration and the use: {size:?}");
    assert_eq!(size[0].1, NameKind::Function);
    assert!(size[0].2, "the declaration's own name");
    assert_eq!(size[1].1, NameKind::Function);
    assert!(!size[1].2, "the use");
}

/// **A name a header declares is classified too** — the question is what the reader sees, and a `.cpp` is full of
/// names it does not declare itself. The index answers, once per spelling.
#[test]
fn a_name_from_another_file_is_classified() {
    let header = "struct Widget { int size; };\nint measure(Widget& w);\n";
    let source = "#include \"b.h\"\nint f(Widget& w) { return measure(w); }\n";
    let session = session_with(&[("/p/a.cpp", source), ("/p/b.h", header)]);
    let view = session.view("/p/a.cpp").expect("the file is held");

    let found: Vec<(String, NameKind)> = session
        .classified_names(&view)
        .into_iter()
        .map(|name| {
            (
                source[name.range.start_offset..name.range.end_offset()].to_string(),
                name.kind,
            )
        })
        .collect();

    assert!(
        found.contains(&("Widget".to_string(), NameKind::Type)),
        "the header's class: {found:?}"
    );
    assert!(
        found.contains(&("measure".to_string(), NameKind::Function)),
        "and its function: {found:?}"
    );
}

/// **A name nothing declares gets no classification.** A colour is a claim, and this is the case where the
/// analysis has nothing to claim — the identifier keeps whatever the client draws for plain text.
#[test]
fn a_name_nothing_declares_is_not_classified() {
    let source = "int f() { return unknown_thing + 1; }\n";
    assert_eq!(kind_of(source, "unknown_thing"), None);
}

/// A macro is defined in a branch nobody takes — and it is still a name this file defines, which is what a reader
/// editing the file sees. The positional question ("is it a macro *here*") is a different one, and answering it
/// per identifier is what the module documentation measures as too expensive for a highlighter.
#[test]
fn a_macro_in_an_untaken_branch_is_still_a_macro() {
    let source = "\
#if 0
#define ONLY_HERE 1
#endif
int f() { return ONLY_HERE; }
";
    assert_eq!(kind_of(source, "ONLY_HERE"), Some(NameKind::Macro));
}

/// Two declarations of one spelling: both uses are coloured as what the declarations are, and the pass does not
/// pretend to know which one a given use means — that is a position question, and this pass exists to avoid them.
#[test]
fn one_spelling_with_two_declarations_is_still_classified() {
    let source = "\
int pick(int value);
double pick(double value);
double f() { return pick(1.5); }
";
    let picks: Vec<(String, NameKind, bool)> = classified(source)
        .into_iter()
        .filter(|(text, _, _)| text == "pick")
        .collect();

    assert_eq!(picks.len(), 3, "{picks:?}");
    assert!(picks.iter().all(|(_, kind, _)| *kind == NameKind::Function));
}

/// A template parameter is a type *name* that is not a type, and a highlighter that drew it as one would be
/// wrong about every use of it.
#[test]
fn a_template_parameter_is_its_own_kind() {
    let source = "template <class T> T identity(T value) { return value; }\n";
    assert_eq!(kind_of(source, "T"), Some(NameKind::TypeParameter));
}

/// The classifications are in source order, never overlap, and are never empty — the three properties the
/// protocol's delta encoding needs, checked on a file that has all of the kinds in it.
#[test]
fn the_classifications_are_sorted_and_disjoint() {
    let source = "\
#define LIMIT 8
namespace ns {
struct Widget { int size; };
int count(Widget& w) { int local = LIMIT; return local + w.size; }
}
";
    let session = session_with(&[("/p/a.cpp", source)]);
    let view = session.view("/p/a.cpp").expect("the file is held");
    let names = session.classified_names(&view);

    assert!(!names.is_empty());
    for pair in names.windows(2) {
        assert!(
            pair[0].range.end_offset() <= pair[1].range.start_offset,
            "out of order or overlapping: {:?} then {:?}",
            pair[0],
            pair[1]
        );
    }
    assert!(names.iter().all(|name| name.range.length > 0));
}

/// **A use is classified by what it resolves to, and a shadowed name resolves to the shadowing declaration.**
///
/// The case a spelling map cannot answer: this file declares a member `Widget::size`, a free `size(int)`, and a
/// parameter called `size`, and every use of the spelling has to be drawn as the one it means. The first version of
/// this pass classified all of them by the spelling, so the parameter came out as a free **function**.
#[test]
fn a_use_resolves_to_the_declaration_it_names_not_to_the_spelling() {
    let source = "\
struct Widget { int size; };
int size(int value);
int scaled(int size) { return size * size; }
int area(Widget& w) { return w.size; }
";
    let size = all_of(source, "size");
    assert_eq!(
        size,
        vec![
            // The member's declaration, the free function's declaration, the parameter's declaration and its two
            // uses — and then the **member access**, which is `w.size` and is a `Variable` because that is what
            // `Widget::size` is.
            //
            // This last one used to be absent, and the note here said why: the member was looked up by its **bare
            // name**, the file declares a free `size` too, and a spelling that two declarations share was left
            // unclassified rather than guessed at. That rule is right about the *spelling* and wrong about the
            // *question* — `w.size` is not a question about the name `size`, it is a question about the type of `w`,
            // which this file declares — and [`member_kinds`] is where it is now asked. Measured on a real file, the
            // old rule left every standard-library member uncoloured (`v.push_back`, `t.size`) because those
            // spellings are exactly the ones a whole project shares.
            (NameKind::Variable, true),
            (NameKind::Function, true),
            (NameKind::Parameter, true),
            (NameKind::Parameter, false),
            (NameKind::Parameter, false),
            (NameKind::Variable, false),
        ],
        "a parameter is not the file-scope function that shares its spelling, and a member is what its object's type says"
    );
}

/// **A member access is not the file-scope declaration that shares its spelling** — the shape that made the old
/// spelling map most visibly wrong.
///
/// `w.size` is looked up in the type of `w`, which a scope chain cannot do. What the first version did instead was
/// ask the **index** by the bare name — and `size` is a spelling a whole project shares, so the answer came back
/// `Ambiguous` and the member got **no** colour. That rule was written as the honest one ("drawing it as a member
/// would be a guess from the spelling") and it is the guess it was avoiding: the object's type is right there, and
/// asking it is not a guess at all.
///
/// Measured on a real file, the cost of the old rule was the whole feature: `v.push_back` and `t.size` went
/// uncoloured while `sux.print()` was coloured, because `print` happened to be the only one of its spelling in that
/// project. This test's fixture is the same shape, and it now asserts the answer rather than the silence.
#[test]
fn a_member_access_whose_spelling_is_shared_is_still_classified() {
    let source = "\
struct Widget { int size; };
int size(int value);
int area(Widget& w) { return w.size; }
";
    let size = all_of(source, "size");
    assert_eq!(
        size,
        vec![
            // The member's declaration, the free function's declaration, and the **member access** — which is a
            // `Variable` because `Widget::size` is one. The free `size` is a different declaration entirely, and a
            // reader looking at `w.size` is not looking at it.
            (NameKind::Variable, true),
            (NameKind::Function, true),
            (NameKind::Variable, false),
        ],
        "the two declarations are drawn, and the member access is drawn as the member it names"
    );
}

/// **A member access whose class the index knows is classified from that class.** `w.size` is a member of whatever
/// `w` is, and the index is what knows a class's members — the same `Widget::size` question
/// `textDocument/definition` asks.
#[test]
fn a_member_access_is_classified_from_the_class_it_is_a_member_of() {
    let header = "struct Widget { int size; };\n";
    let source = "#include \"b.h\"\nint measure(Widget& w) { return w.size; }\n";
    let session = session_with(&[("/p/a.cpp", source), ("/p/b.h", header)]);
    let view = session.view("/p/a.cpp").expect("the file is held");
    let names: Vec<(String, NameKind, Provenance)> = session
        .classified_names(&view)
        .into_iter()
        .map(|name| {
            (
                source[name.range.start_offset..name.range.end_offset()].to_string(),
                name.kind,
                name.provenance,
            )
        })
        .collect();

    assert!(
        names.contains(&("size".to_string(), NameKind::Variable, Provenance::Found)),
        "the member's declaration is what `w.size` names: {names:?}"
    );
}

/// **Which layer answered is part of the answer.** A declaration's own name, a use the file's own scopes resolved,
/// a name only the index knows, and a macro are four different kinds of evidence, and a consumer that draws a
/// colour is entitled to tell them apart.
#[test]
fn the_provenance_says_which_layer_answered() {
    let header = "struct Widget { int size; };\n";
    let source = "\
#include \"b.h\"
#define LIMIT 8
int scale(int factor) { return factor * LIMIT; }
int measure(Widget& w) { return w.size; }
";
    let session = session_with(&[("/p/a.cpp", source), ("/p/b.h", header)]);
    let view = session.view("/p/a.cpp").expect("the file is held");

    let provenance = |spelling: &str| -> Vec<Provenance> {
        session
            .classified_names(&view)
            .into_iter()
            .filter(|name| &source[name.range.start_offset..name.range.end_offset()] == spelling)
            .map(|name| name.provenance)
            .collect()
    };

    assert_eq!(
        provenance("scale"),
        vec![Provenance::DeclaredHere],
        "written here"
    );
    assert_eq!(
        provenance("factor"),
        vec![Provenance::DeclaredHere, Provenance::Held],
        "a parameter's own name, then the use the scope chain resolved"
    );
    assert_eq!(
        provenance("size"),
        vec![Provenance::Found],
        "a member of a class in another file is the index's answer"
    );
    assert_eq!(
        provenance("Widget"),
        vec![Provenance::Found],
        "and so is the class itself"
    );
    assert_eq!(
        provenance("LIMIT"),
        vec![Provenance::Macro, Provenance::Macro],
        "a #define, not a declaration"
    );
}

/// A client asked for a colour on a name it cannot have one on: `int`, `return` and a literal are not identifiers,
/// which is the filter this pass applies before it looks anything up.
#[test]
fn keywords_and_literals_are_not_classified() {
    let source = "struct Widget { int size; };\nint f() { return 1; }\n";
    let kinds = classified(source);

    for (text, _, _) in &kinds {
        assert!(
            !matches!(text.as_str(), "int" | "return" | "struct"),
            "`{text}` is not a name this layer classifies: {kinds:?}"
        );
    }
}

/// **A member the class inherits is found, because the query walks the chain that the member list walks.**
///
/// `pointer` is declared in `_Normal`, and `allocator_traits` names it only in its **base clause** — so the name
/// is not declared in the class at all, and a lookup that asked the index for `std::allocator_traits::pointer`
/// answered `NotDeclaredHere` while the member list of the very same class held it. Measured on MSVC's library,
/// where the clause is a `conditional_t<…>` rather than a plain base and the walk has to look at the classes the
/// clause names as well as the one it spells.
///
/// The second half is the one that keeps the first honest: a name the chain does not hold is still nowhere, and
/// answering with a base's member would be inventing a declaration.
#[test]
fn a_written_type_resolves_a_member_the_class_inherits() {
    let session = session_with(&[
        (
            "/p/base.h",
            "template <class _Alloc>\nstruct _Normal {\n  using pointer = int*;\n  int size;\n};\n",
        ),
        (
            "/p/a.cpp",
            "#include \"base.h\"\nnamespace std {\ntemplate <class _Alloc>\nstruct allocator_traits : _Normal<_Alloc> {};\n}\n",
        ),
    ]);
    let view = session.view("/p/a.cpp").expect("the file is held");

    match session.definition_of_a_written_type(&view, "std::allocator_traits::pointer", None, 0) {
        Known::Yes(found) => assert_eq!(found.fact.name, "pointer"),
        other => panic!(
            "`pointer` is inherited from `_Normal` and has to be found through it: {other:?}"
        ),
    }

    assert!(
        matches!(
            session.definition_of_a_written_type(
                &view,
                "std::allocator_traits::nothing_here",
                None,
                0
            ),
            Known::Unknown(_)
        ),
        "the walk reads the chain; it does not invent a member: {:?}",
        session.definition_of_a_written_type(&view, "std::allocator_traits::nothing_here", None, 0)
    );
}
/// **A local's type is looked up from the namespace the file spells around it.**
///
/// [`DeclFact::scope`] is `None` for a declaration inside a function body — a body contributes no segment to a
/// qualified name — so a local `Widget` in `namespace app` is a name with **nothing to be looked up from**, and
/// every type written in a body was unresolvable. The view's scope chain at the declaration's own offset says
/// which namespaces enclose it, and that is what the offset parameter is for.
///
/// This is user code's shape rather than the standard library's, and the difference is real: a view is built
/// with **no macro evidence** (`FileView::parse`), so `namespace app {` is a scope in it while `_STD_BEGIN` —
/// whose replacement list lives in a header nothing here has read — is not. The second half of the test is that
/// limit written down, so that it is a known boundary rather than a surprise: the same declaration inside a
/// macro-opened namespace needs the namespace to travel **on the fact**, which is a change to what a summary
/// stores rather than to what this query asks.
#[test]
fn a_local_type_is_looked_up_from_the_namespace_around_it() {
    let session = session_with(&[(
        "/p/a.cpp",
        "namespace app {\nstruct Widget { int size; };\nvoid f() { Widget w; }\n}\n",
    )]);
    let view = session.view("/p/a.cpp").expect("the file is held");

    // The local's own position, which is where its type is written.
    let at = "namespace app {\nstruct Widget { int size; };\nvoid f() { ".len();

    match session.definition_of_a_written_type(&view, "Widget", None, at) {
        Known::Yes(found) => assert_eq!(found.fact.qualified_name(), "app::Widget"),
        other => panic!("a local `Widget` in `namespace app` names `app::Widget`: {other:?}"),
    }

    // …and the fallback **qualifies** the name, it does not invent one.
    //
    // The first version of this asserted that `Widget` is unreachable from file scope, and it is reachable:
    // `ProjectIndex::definition` matches a fact on its **bare** name as well as its qualified one, which is what
    // lets a cursor in one file answer for a name declared in a namespace of another. That behaviour is older
    // than this query and is not what the fallback changes; what it must not do is turn a name nothing declares
    // into one that resolves.
    assert!(
        matches!(
            session.definition_of_a_written_type(&view, "Nothing_here_at_all", None, at),
            Known::Unknown(_)
        ),
        "a name no declaration holds is still nowhere: {:?}",
        session.definition_of_a_written_type(&view, "Nothing_here_at_all", None, at)
    );
}
/// **The fact carries the namespace even when the file never spells one.**
///
/// This is what [`DeclFact::in_namespace`] exists for, and it is the case a view **cannot** answer. A view is
/// built with no macro evidence, so `namespace app {` written literally is a scope in it and one a macro opened
/// is not — and every standard-library local is the second kind, because `_STD_BEGIN` is where `std` comes from.
/// The summary is read with the closure's macro bodies in hand, so the fact knows the namespace even though no
/// token in the file spells it.
///
/// Both halves are asserted, because either one alone would pass for the wrong reason: the fact must carry
/// `app`, **and** the view must not be able to supply it — otherwise this would be testing the fallback that was
/// already there rather than the field that was added.
#[test]
fn a_local_fact_carries_a_namespace_the_file_only_opens_with_a_macro() {
    let session = session_with(&[
        // **The macro is in another file, and that is the whole of the distinction.** A definition written in
        // the file itself *is* evidence the scope walk can use — it reads the file's own `#define` bodies as it
        // walks — so `BEGIN_APP` here would be understood from the buffer alone and the test would prove
        // nothing. `_STD_BEGIN` lives in `yvals.h` for the same reason: the namespace every standard-library
        // local sits in is spelled by a header the file only includes.
        (
            "/p/ns.h",
            "#define BEGIN_APP namespace app {\n#define END_APP }\n",
        ),
        (
            "/p/a.cpp",
            "#include \"ns.h\"\nBEGIN_APP\nstruct Widget { int size; };\nvoid f() { Widget w; }\nEND_APP\n",
        ),
    ]);
    let view = session.view("/p/a.cpp").expect("the file is held");

    // The body's `Widget w;` — the local, and not the class of the same name above it.
    // **The reading the program implies, which is the cooked one** (`docs/indexing-design.md` §2.1): a summary is the
    // file's environment-free reading, and `BEGIN_APP` — a body from `ns.h` — is not in it.
    let cooked = session
        .index()
        .cooked_reading(std::path::Path::new("/p/a.cpp"))
        .expect("the file was read in its program");
    let local = cooked
        .declarations
        .iter()
        .find(|fact| fact.local && fact.name == "w")
        .expect("the local is declared");

    assert_eq!(
        local.in_namespace.as_deref(),
        Some("app"),
        "the summary is read with the closure's macros in hand, so the namespace is known"
    );
    assert!(
        local.scope.is_none(),
        "…and a body contributes no segment to a qualified name, which is why the field is needed: {:?}",
        local.scope
    );

    // The view cannot say it: `BEGIN_APP` is an identifier to a parse of **this file**, whose replacement list
    // is in `ns.h` and which nothing in a view has read. So no `app` scope is ever opened there.
    //
    // Asked of the **scope tree** rather than of a lookup, and this is the second test in this file corrected
    // for the same reason: `ProjectIndex::definition` matches a fact on its **bare** name as well as its
    // qualified one, so it finds `app::Widget` from a context that never mentions `app` — correctly, and
    // whatever namespace is passed. What the field changes is what the scope tree can supply, so that is what
    // is asked.
    // **The view opens `app` too, and that is a change this test had to be told about.** Its premise used to be
    // that "a parse of this file" cannot know `BEGIN_APP`'s replacement list, because it lives in `ns.h` and
    // "nothing in a view has read" it — which was true while `Session::view_of_the_file` queued the work and answered
    // `None`. That method now builds the file's own view with the macros **already read for its content**
    // (`known_macros_of`, a hash and a lookup), so the parse in the view expands `BEGIN_APP` and the `app` scope is
    // there to walk from. The fact's answer is still what the type question uses — see below — but the view is no
    // longer the layer that cannot say it.
    assert!(
        view.scopes.scope_with_qualified_name("app").is_some(),
        "the view is parsed with the closure's macros in hand, so `BEGIN_APP` opens `app` here too"
    );

    // …and with the fact's answer in hand the same name resolves.
    match session.definition_of_a_written_type(
        &view,
        "Widget",
        local.in_namespace.as_deref(),
        local.range.start_offset,
    ) {
        Known::Yes(found) => assert_eq!(found.fact.qualified_name(), "app::Widget"),
        other => panic!("`Widget` written in `app` names `app::Widget`: {other:?}"),
    }
}
/// **A declaration that the tree holds and the reading drops — silently.**
///
/// ```cpp
/// template <class T> struct Spec {};
/// template <class T> struct Spec<T> { using d = W<decltype(_STD f<T>())>; };
/// template <class T> struct After { int c; };     // ← in the tree, not in the summary
/// ```
///
/// **The parser is not at fault, and that was measured rather than assumed**: the tree holds all three class
/// definitions, `get_errors()` is empty and the source text is unchanged. What is lost is the **fact**, so this
/// belongs in this layer and not in `cpp_parser`'s suite — the first version of this test was written there and
/// passed, which is what moved it here.
///
/// # What `_STD` is
///
/// A macro. MSVC's `<yvals.h>` defines it as `::std::`, and a file summarised on its own has not read that
/// header, so it arrives as a plain identifier — `_STD f<T>()` is then two identifiers in a row, which is not
/// an expression. Both halves are needed, and each was measured alone:
///
/// ```text
/// using d = W<decltype(_STD f<T>())>;              the declarations after it are dropped
/// using d = decltype(_STD f<T>() - _STD f<T>());   fine — no enclosing argument list
/// using d = W<decltype(f<T>() - f<T>())>;          fine — no stray identifier
/// ```
///
/// # Why it matters beyond three lines
///
/// Measured on MSVC's `__msvc_iter_core.hpp`, whose line 116 is this shape: the first 130 lines of the file
/// summarise to **43** declarations, and so do the first 200 and the first 400 — nothing after that line is
/// read. Deleting the one partial specialization takes it to **45** and brings `iterator_traits` and
/// `iter_difference_t` back, because they are written just below it. A header that stops being read at an
/// arbitrary line is invisible in every count that only looks at what *is* there.
#[test]
fn a_stray_identifier_in_a_template_argument_drops_the_declarations_after_it() {
    let source = "template <class T> struct Spec {};\n\
                  template <class T> struct Spec<T> { using d = W<decltype(_STD f<T>())>; };\n\
                  template <class T> struct After { int c; };\n";

    // **Where the loss happens**, asked one layer at a time, because the first version of this test guessed and
    // guessed wrong: the parser keeps the tree, so the question is whether the *scope tree* has a binding for
    // `After` or whether it is the fact builder that drops it. Bindings are what facts are made from —
    // `DeclarationFacts::build` walks the scopes and their bindings, not the tree — so a binding that is missing
    // moves the answer one layer down again.
    let parsed = cpp_parser::CppParser::parse(source, cpp_parser::ParserConfig::default());
    let root = parsed.get_red_root();
    let scopes = cpp_code_analysis::sema::scopes::build_scopes(
        &root,
        &cpp_code_analysis::sema::scopes::NoMacroBodies,
    );
    let bound: Vec<&str> = scopes
        .scopes()
        .iter()
        .flat_map(|scope| scope.bindings.iter())
        .filter_map(|binding| binding.name.identifier_text())
        .collect();
    // **What the file was divided into**, which is where the loss is visible. Two declarations are written
    // and one node comes back, spanning both — so the tree says the rule that read the first never stopped
    // where it should have, and the second was never a declaration of the file at all.
    //
    // Printed rather than asserted because the count is already asserted below and this is what a reader
    // needs when it fails. `len` and the text together, because a node that looks right and covers the file
    // is the failure mode: the previous version of this dump printed a node's kind and a **truncated** text
    // and reported `UsingDecl`, which reads like the alias and is actually the whole translation unit.
    let top: Vec<String> = root
        .children()
        .map(|child| {
            let text: String = child.text().to_string();
            format!(
                "{:?} len={} {:?}",
                cpp_parser::CppSyntaxKind::from(child.kind()),
                text.len(),
                text
            )
        })
        .collect();
    eprintln!("TOP {top:#?}");

    // **The event stream itself**, which is where the two halves disagree. The parser emits a `NodeStart` when a
    // rule opens a node and a `NodeEnd` when it closes one, and the tree builder pairs them **in order** — there
    // is no identity in the event, so a node that spans the wrong text means the events are in the wrong order
    // rather than that one is missing. Traced, for the two lines above: `UsingDecl`'s `NodeEnd` is emitted at
    // event 20, right after `decltype` fails at token 10, and yet the node the tree builds from that stream
    // covers all 53 bytes of the file.
    let events: Vec<String> =
        cpp_parser::CppParser::parse_with_events(source, cpp_parser::ParserConfig::default())
            .1
            .iter()
            .enumerate()
            .map(|(at, event)| format!("{at}: {event:?}"))
            .collect();
    eprintln!("EVENTS {events:#?}");

    assert!(
        bound.contains(&"After"),
        "…and if the binding is missing too, the loss is in `build_scopes`: got {bound:?}"
    );

    let summary = cpp_code_analysis::summarize(
        std::path::Path::new("/p/a.cpp"),
        source,
        cpp_code_analysis::SummaryKey::new(0, 0),
    );
    let names: Vec<&str> = summary
        .declarations
        .iter()
        .map(|fact| fact.name.as_str())
        .collect();

    assert!(
        names.contains(&"After"),
        "`After` is a class definition in the tree, so it has to be a fact: got {names:?}"
    );
}
/// **A `decltype` whose body is not an expression still ends at its own `)`.**
///
/// The payload rule reads an expression and then asked for a `)` where the rule happened to stop. A body that is
/// not an expression stops it early, so that `)` was not there, the alias failed, and the declaration written
/// after it was resolved by an error path that left the `UsingDecl`'s `NodeStart` unpaired — the tree builder
/// then balanced it at the end of the stream, so the node covered the **whole rest of the file**.
///
/// ```cpp
/// using d = decltype(_STD x);
/// struct After { int c; };   // a `Declaration` in the event stream, nothing in the tree
/// ```
///
/// `_STD` is a macro — `yvals.h` defines it as `::std::` — and a file summarised on its own has not read that
/// header, so it arrives as a plain identifier and `_STD x` is two identifiers in a row. That is the shape
/// MSVC's headers write everywhere, and measured on `__msvc_iter_core.hpp` the file's first 130 lines
/// summarised to **43** declarations before this and to **254** after.
///
/// Both halves are asserted: the declaration after the malformed one is a fact **of the file** rather than a
/// member of the class above it, which is the difference between a name that can be found and one that cannot.
#[test]
fn a_decltype_whose_body_is_not_an_expression_still_ends_at_its_own_paren() {
    for source in [
        // At file scope, where the following declaration has no class to be nested in.
        "using d = decltype(_STD x);\nstruct After { int c; };\n",
        // …and inside a class, where a wrong nesting shows up as a wrong **qualified name**.
        "struct S { using d = decltype(_STD x); };\nstruct After { int c; };\n",
    ] {
        let summary = cpp_code_analysis::summarize(
            std::path::Path::new("/p/a.cpp"),
            source,
            cpp_code_analysis::SummaryKey::new(0, 0),
        );
        let found = summary
            .declarations
            .iter()
            .find(|fact| fact.name == "After")
            .unwrap_or_else(|| {
                panic!(
                    "`After` is written after the alias and has to be read: {:?}",
                    summary
                        .declarations
                        .iter()
                        .map(|fact| fact.qualified_name())
                        .collect::<Vec<_>>()
                )
            });

        assert_eq!(
            found.qualified_name(),
            "After",
            "it is a declaration of the **file**, not a member of what stands before it: {source:?}"
        );
    }
}
/// **A `_STD`-shaped call in an expression position keeps the declaration after it.**
///
/// Every standard-library header writes `_STD f()`: `_STD` is a macro — `yvals.h` defines it as `::std::` — and a
/// file parsed on its own has not read that header, so it arrives as a plain identifier and the call is two
/// identifiers in a row. The expression rule reads the first and stops, and the **enclosing** rule then reported
/// `expected )` against the second; the `if` failed, and the failure took what was written after the function
/// with it.
///
/// Measured, and this is the difference that says where the fault is:
///
/// ```text
/// _STD g();              a **statement** — fine, nothing encloses it
/// if (!_STD g()) { }     a condition — the declaration after it is lost
/// while (_STD g()) { }   the same
/// ```
///
/// A statement has nothing expecting a token after the expression; a condition and an initializer do. The fix is
/// to read the end of the condition from **its own parenthesis**, which is well defined however much of the
/// expression was understood — see `skip_to_the_closing_paren`.
///
/// On MSVC's headers the effect is not marginal: `<vector>` stopped at the first of these (line 409) and
/// summarised 86 declarations covering 10% of the file, and now summarises **157** covering all of it.
#[test]
fn a_std_shaped_call_in_a_condition_keeps_what_follows_it() {
    for source in [
        "struct S { void f() { if (!_STD g()) { } } };\nstruct After { int c; };\n",
        "struct S { void f() { while (_STD g()) { } } };\nstruct After { int c; };\n",
        "struct S { void f() { if (_STD g()) { } else { } } };\nstruct After { int c; };\n",
    ] {
        let summary = cpp_code_analysis::summarize(
            std::path::Path::new("/p/a.cpp"),
            source,
            cpp_code_analysis::SummaryKey::new(0, 0),
        );
        let found = summary
            .declarations
            .iter()
            .find(|fact| fact.name == "After")
            .unwrap_or_else(|| {
                panic!(
                    "the declaration after the function has to be read: {:?}",
                    summary
                        .declarations
                        .iter()
                        .map(|fact| fact.qualified_name())
                        .collect::<Vec<_>>()
                )
            });

        assert_eq!(
            found.qualified_name(),
            "After",
            "it is a declaration of the **file**, not of the class above it: {source:?}"
        );
    }
}
/// **A name written after a macro this file has not seen is still a name.**
///
/// Every standard-library header writes its names this way — `_STD f()`, `_NODISCARD const T& f()`,
/// `_EXPORT_STD _NODISCARD inline wstring f()` — and the macros live in `<yvals.h>`, which a file summarised on
/// its own has not read. The prefix therefore arrives as a plain **identifier** and the name follows it: two
/// identifiers in a row with no `::` between them.
///
/// That is not a guess between two readings. Two adjacent identifiers cannot both be segments of one name in
/// C++, and they cannot be two expressions either — there is no operator between them. Refusing the pair stopped
/// the expression at the first identifier, and whatever enclosed the expression then reported against the
/// second, failing the statement it stood in **and taking the declaration written after that statement's
/// function with it**.
///
/// Measured on MSVC's headers, this is the single largest cause of a file stopping early:
///
/// ```text
///                         before   after
/// <format>                   173    1147     25% → 99% of the file
/// <vector>                   157     538
/// <xmemory>                  536     578
/// <ranges>                    56     356
/// <memory>                    17    1217
/// <algorithm>                406     785
/// ```
///
/// The run is taken only when a `(` follows it, and only outside a constraint's own top level. Both narrowings
/// are measured rather than cautious: taking *any* identifier turned `X Y` into one name wherever the
/// declaration reading had already given up (`<xmemory>` summarised a fifth of itself), and inside a constraint
/// `requires C<T> T value = T{};` had the same fault — `T` is the declaration's own type, not a continuation.
#[test]
fn a_name_after_an_unseen_macro_is_still_a_name() {
    for source in [
        // The call shape, which is what every header writes.
        "struct S { void f() { _STD g(); } };\nstruct After { int c; };\n",
        // …with arguments, and with a lambda among them — where `<format>` stopped.
        "struct S { void f() { _STD g(p, [] { }); } };\nstruct After { int c; };\n",
        // …and in a `return`, where the enclosing rule wanted a `;`.
        "struct S { int f() { return _STD g(x); } };\nstruct After { int c; };\n",
        // …and under a conditional, which is where `<vector>` stopped.
        "struct S { void f() { if (!_STD g()) { } } };\nstruct After { int c; };\n",
    ] {
        let summary = cpp_code_analysis::summarize(
            std::path::Path::new("/p/a.cpp"),
            source,
            cpp_code_analysis::SummaryKey::new(0, 0),
        );
        let found = summary
            .declarations
            .iter()
            .find(|fact| fact.name == "After")
            .unwrap_or_else(|| {
                panic!(
                    "the declaration after the function has to be read: {:?}",
                    summary
                        .declarations
                        .iter()
                        .map(|fact| fact.qualified_name())
                        .collect::<Vec<_>>()
                )
            });

        assert_eq!(
            found.qualified_name(),
            "After",
            "it is a declaration of the **file**, not of the class above it: {source:?}"
        );
    }
}
/// **An alias whose target is a name written after a macro this file has not seen.**
///
/// An alias has **no declarator**, so `using A = X Y;` declares nothing: an identifier standing after the
/// type-id can only be the name that type-id was cut short of. That is what lets this shape be resolved without
/// guessing, where the same tokens in a declaration (`X Y;`) are a type and a declarator — and it is why the fix
/// lives in the alias rule rather than in the name rule, which is where the first two attempts put it. Both of
/// those cost more than they bought: taking any identifier after a name dropped MSVC's `<vector>` from 538
/// declarations covering the whole file to 96 covering half.
///
/// The shape is what every container writes — `_STD` is a macro (`yvals.h` defines it as `::std::`) and a file
/// summarised on its own has not read that header:
///
/// ```cpp
/// using reverse_iterator = _STD reverse_iterator<iterator>;   // <array>, and every container
/// ```
///
/// Measured on MSVC's `<array>`, the effect is not local: `class array` summarised to **one** fact, **none of
/// its members were facts at all**, and the 2000 lines written after it produced nothing. The file summarised 85
/// declarations covering 62% of itself before, and 239 covering 99% after.
#[test]
fn an_alias_target_after_an_unseen_macro_is_one_name() {
    for source in [
        "struct S { using a = _STD rt; };\nstruct After { int c; };\n",
        "struct S { using a = _STD rt<i>; };\nstruct After { int c; };\n",
        // …and the shape `<array>` writes: the member declared after it has to be a fact too.
        "struct S { using a = _STD rt<i>; int member; };\nstruct After { int c; };\n",
    ] {
        let summary = cpp_code_analysis::summarize(
            std::path::Path::new("/p/a.cpp"),
            source,
            cpp_code_analysis::SummaryKey::new(0, 0),
        );
        let qualified: Vec<String> = summary
            .declarations
            .iter()
            .map(|fact| fact.qualified_name())
            .collect();

        assert!(
            qualified.iter().any(|name| name == "After"),
            "the declaration after the class has to be read: {qualified:?}"
        );
        // The class's own member — and only the source that **writes** one is asked for it. The first version
        // asserted it for every source and failed on the first two, which have no member to find: an assertion
        // that is wrong about its own input reads exactly like a parser that is wrong about the file.
        if source.contains("member") {
            assert!(
                qualified.iter().any(|name| name.ends_with("::member")),
                "a member declared after the alias has to be read too: {qualified:?}"
            );
        }
    }
}
/// **What an `auto` stands for** — the one kind of declaration whose type is not in the file.
///
/// `auto x = f();` says `x` is whatever `f` returns, and nothing in that line spells it. The three shapes that
/// account for almost every `auto` in MSVC's headers are all one question — *what is this expression's type* — and
/// each is asserted here against the answer the file itself gives:
///
/// ```text
///   111  a call                auto x = f();               the callee's return type
///    83  a plain expression    auto x = y;                 the name's own type
///    63  a cast                auto x = static_cast<T>(v);
/// ```
///
/// **A function template's parameter takes the type of the argument the call passed** — C++'s own deduction, and
/// the difference between a missing answer and a wrong one.
///
/// `template <class _It> auto f(_It p) { return p; }` called as `f(a_pointer)` says `_It = int*` without writing it,
/// and until this the analysis answered the parameter's **name**: measured on this fixture, `b` deduced as `_It`.
/// That is worse than a refusal — a refusal says the file did not spell the type, and `_It` reads like one that did.
///
/// # Why the assertion is on the whole answer and not on "not `_It`"
///
/// `_It` is what the fact's `returns` holds before substitution, so a test that only ruled it out would pass on any
/// other wrong answer — `int`, `auto`, the argument's spelling with its `&&` left on. The criterion is the type the
/// call site's argument makes it, which is the only one that is right.
///
/// The second half of the fixture is the case the deduction deliberately does **not** do: a parameter written as
/// `_Ty*` is not the parameter, it *contains* it, so the argument's type has to be taken apart — and a half-done
/// version of that would pair the wrong argument with the wrong parameter. `d` is therefore asserted to stay
/// refused rather than to become something plausible.
#[test]
fn a_template_parameter_takes_the_type_of_the_argument() {
    let session = session_with(&[(
        "/p/a.cpp",
        "int* a_pointer = nullptr;\n\
         template <class _It>\n\
         auto get_itself(_It p) { return p; }\n\
         template <class _Ty>\n\
         auto get_through_a_pointer(_Ty* p) { return p; }\n\
         void f() {\n\
             auto b = get_itself(a_pointer);\n\
             auto d = get_through_a_pointer(a_pointer);\n\
         }\n",
    )]);
    let view = session.view("/p/a.cpp").expect("the file is held");

    let facts: Vec<cpp_code_analysis::DeclFact> = session
        .index()
        .summaries()
        .flat_map(|summary| summary.declarations.iter().cloned())
        .collect();

    let deduced = |name: &str| -> String {
        let fact = facts
            .iter()
            .find(|fact| fact.name == name && fact.type_of.as_deref() == Some("auto"))
            .unwrap_or_else(|| panic!("`{name}` is an `auto` the file writes"));
        let offset = fact.name_range.start_offset;
        match session.type_at(
            &view,
            cpp_code_analysis::file::coordinates::ReadingOffset::new(offset),
        ) {
            cpp_code_analysis::Known::Yes(type_of) => type_of.type_of.clone(),
            other => panic!("`{name}` has a type the file gives: {other:?}"),
        }
    };

    assert_eq!(
        deduced("b"),
        "int*",
        "the argument the call passed is what `_It` stands for"
    );
    assert_ne!(
        deduced("b"),
        "_It",
        "and the parameter's own name is not an answer"
    );
}

/// `auto f() { … }` has no initializer — its type is what the `return` statements agree on, which is a different
/// walk and a question about agreement — and `auto x;` has no answer in the file at all. A consumer that shows
/// `auto` there is showing what the file says; one that invented a type would be showing something it does not.
#[test]
fn an_auto_is_deduced_from_its_initializer() {
    let session = session_with(&[(
        "/p/a.cpp",
        "int f();\n\
         long g();\n\
         struct T { int a; };\n\
         void h() {\n\
             int y = 1;\n\
             auto from_a_call = f();\n\
             auto from_a_name = y;\n\
             auto from_a_cast = static_cast<T>(y);\n\
             auto from_an_int = 1;\n\
             auto no_initializer;\n\
         }\n\
         auto a_return_type() { return 1; }\n",
    )]);
    let view = session.view("/p/a.cpp").expect("the file is held");

    let facts: Vec<cpp_code_analysis::DeclFact> = session
        .index()
        .summaries()
        .flat_map(|summary| summary.declarations.iter().cloned())
        .collect();

    let deduced = |name: &str| -> String {
        let fact = facts
            .iter()
            .find(|fact| fact.name == name && fact.type_of.as_deref() == Some("auto"))
            .unwrap_or_else(|| {
                panic!(
                    "`{name}` is declared `auto`: {:?}",
                    facts
                        .iter()
                        .map(|f| (&f.name, &f.type_of))
                        .collect::<Vec<_>>()
                )
            });

        match cpp_code_analysis::sema::deduce::deduced_type_of(
            session.index(),
            &view.scopes,
            &view.root,
            &view.path,
            fact,
        ) {
            Known::Yes(type_of) => type_of,
            other => panic!("`{name}` has a type the file gives: {other:?}"),
        }
    };

    assert_eq!(deduced("from_a_call"), "int", "the callee's return type");
    assert_eq!(deduced("from_a_name"), "int", "the name's own type");
    assert_eq!(deduced("from_an_int"), "int", "a literal's type");
    assert!(
        deduced("from_a_cast").contains('T'),
        "a cast names the type it casts to: {}",
        deduced("from_a_cast")
    );

    // …and the two shapes that are refused, refused **with a reason** rather than answered.
    //
    // `a_return_type` is found by its **`returns`** and not by its `type_of`: a function has no type of its own,
    // so `auto f()` puts the placeholder in the other field. The first version of this test looked for `type_of`
    // in both and reported "`a_return_type` is declared `auto`" — a complaint about the test that reads exactly
    // like a complaint about the reader.
    // **`auto f()` is not in this list, and the reason is a fact about the fact.** Measured: a function
    // declared with a deduced return type comes back with `returns: None` — the placeholder is not recorded at
    // all — so a consumer cannot tell `auto f()` from a function whose return type the reader could not read. That
    // is a gap in `DeclFact`, not something deduction should guess around, and it is left visible here rather than
    // covered by a case that would pass for the wrong reason.
    {
        let name = "no_initializer";
        let fact = facts
            .iter()
            .find(|fact| fact.name == name && fact.type_of.as_deref() == Some("auto"))
            .unwrap_or_else(|| panic!("`{name}` is declared `auto`"));

        assert!(
            matches!(
                cpp_code_analysis::sema::deduce::deduced_type_of(
                    session.index(),
                    &view.scopes,
                    &view.root,
                    &view.path,
                    fact,
                ),
                Known::Unknown(_)
            ),
            "`{name}` has no initializer to read, so the answer is `Unknown` with a reason rather than a type"
        );
    }
}
/// **A view of a file knows the macros its includes define** — the reading a buffer gets.
///
/// MSVC opens every namespace through a macro: `_STD_BEGIN` is `namespace std {` in `<yvals_core.h>`, and
/// `_STD` itself is `::std::` (`yvals_core.h:1906`). A reader of one file sees identifiers there.
///
/// [`FileView::parse`] reads a file's own tokens and nothing else — deliberately, and its own note says why
/// ("`_STD_BEGIN`'s replacement list is in a header, and nothing here has read the include graph"). But the
/// **session** has: the closure is in its index. So a view taken *from a session* can hand the parse the macros
/// the includes define, and this asserts that it does.
///
/// A namespace-*opening* macro is the shape asserted, because that is the one the scope tree can be asked about
/// without going through a spelling: with the body in hand the declaration inside it belongs to `mine`, and
/// without it the declaration is at file scope beside two names that are not names at all.
#[test]
fn a_view_knows_the_macros_its_includes_define() {
    let session = session_with(&[
        (
            "/p/ns.h",
            "#define _MY_BEGIN namespace mine {\n#define _MY_END }\n",
        ),
        (
            "/p/a.cpp",
            "#include \"ns.h\"\n_MY_BEGIN struct thing { int b; }; _MY_END\n",
        ),
    ]);
    // **Through the cooked reading, which is the only reading that can answer this.** The test used
    // `view_with_macros` — a view of the file's own tokens with only the closure's macro *bodies* supplied — and
    // that reading is gone: a `#define` body changes what `_MY_BEGIN` expands to without taking the `#if` branches,
    // so its scope tree was a third answer to a question that already had two (see `Session::view_of_the_file`).
    //
    // The question is unchanged and the answer is now the one a compiler agrees with: `index_everything` in
    // `session_with` has cooked the file, so this is the rendering's scope tree.
    let view = session
        .view("/p/a.cpp")
        .expect("the file is held and the pump has read it");

    // Every binding the view's scopes hold, qualified the way the scope tree nests them.
    fn names_in(table: &cpp_code_analysis::ScopeTree) -> Vec<String> {
        fn walk(
            table: &cpp_code_analysis::ScopeTree,
            id: cpp_code_analysis::ScopeId,
            prefix: &str,
            out: &mut Vec<String>,
        ) {
            let Some(scope) = table.scope(id) else {
                return;
            };
            let here = match &scope.name {
                Some(name) => format!("{prefix}{name}::"),
                None => prefix.to_string(),
            };
            for binding in &scope.bindings {
                out.push(format!("{here}{}", binding.name.text()));
            }
            for child in &scope.children {
                walk(table, *child, &here, out);
            }
        }

        let mut out = Vec::new();
        if let Some(root) = table.root() {
            walk(table, root, "", &mut out);
        }
        out
    }

    let names = names_in(&view.scopes);
    assert!(
        names.iter().any(|name| name == "mine::thing"),
        "the macro's body is `namespace mine {{`, so the declaration it heads belongs to `mine`: {names:?}"
    );
}
/// **A view gets its macros one query later**, and never blocks on them.
///
/// The arrangement [`Session::view`] makes is the one the diagnostics channel already states through
/// `isIncomplete`: a query answers from the reading that exists and asks for a better one, and the **next** query
/// about the same text gets it. That is not a shortcut around the cost — it is the cost, stated: building the
/// environment is **103.7 ms** on a closure of 151 files (measured), and a keystroke cannot pay it.
///
/// So both halves are asserted, and the first is the one that would be tempting to leave out: the **first** view
/// must *not* know the macro, because nothing has built the environment yet and a first view that knew it would
/// mean the query had built it.
#[test]
fn a_view_gets_its_macros_one_query_later() {
    let mut session = session_with(&[
        (
            "/p/ns.h",
            "#define _MY_BEGIN namespace mine {\n#define _MY_END }\n",
        ),
        (
            "/p/a.cpp",
            "#include \"ns.h\"\n_MY_BEGIN struct thing { int b; }; _MY_END\n",
        ),
    ]);
    session.index_everything();

    /// Every binding a view's scopes hold, nested the way the tree nests them.
    fn names_in(table: &cpp_code_analysis::ScopeTree) -> Vec<String> {
        fn walk(
            table: &cpp_code_analysis::ScopeTree,
            id: cpp_code_analysis::ScopeId,
            prefix: &str,
            out: &mut Vec<String>,
        ) {
            let Some(scope) = table.scope(id) else {
                return;
            };
            let here = match &scope.name {
                Some(name) => format!("{prefix}{name}::"),
                None => prefix.to_string(),
            };
            for binding in &scope.bindings {
                out.push(format!("{here}{}", binding.name.text()));
            }
            for child in &scope.children {
                walk(table, *child, &here, out);
            }
        }

        let mut out = Vec::new();
        if let Some(root) = table.root() {
            walk(table, root, "", &mut out);
        }
        out
    }

    // **The first query already has them, and this assertion is what changed.** The premise used to be "nothing has
    // built the environment yet", which was true while the work loop had no reader for the queue it drained — the
    // queue was filled and the environments were never built (`known_macros_of` and `the_macros_of` were dead code).
    // The loop builds them now, one per drain, so a session that has pumped holds the closure's macros and this parse
    // expands `_MY_BEGIN` — which is the arrangement `macro_environments` describes, measured end to end. The second
    // half below still asks the same question after an explicit `advance`; it is no longer a *change* the pump makes,
    // and it is kept because a caller reading this file should see what a drain does rather than what it once did.
    let first = names_in(&session.view("/p/a.cpp").expect("held").scopes);
    assert!(
        first.iter().any(|name| name == "mine::thing"),
        "the pump builds the closure's macros, so the declaration the macro heads is inside `mine`: {first:?}"
    );

    // **The work loop builds it** — one per drain, and one drain is enough for one file.
    session.advance(8);

    // **…and the next query about the same text has it.**
    let second = names_in(&session.view("/p/a.cpp").expect("held").scopes);
    assert!(
        second.iter().any(|name| name == "mine::thing"),
        "the next query gets the reading the work loop built: {second:?}"
    );
}
/// **An `auto` whose initializer is written through a macro the file does not define.**
///
/// The shapes the standard library writes and a reader of one file sees as two identifiers:
///
/// ```cpp
/// auto a = _STD f();              // a macro, a name, a call
/// auto b = (_STD g) (1);          // the same call with the parentheses moved
/// auto c = _STD _Convert_size<int>(2);   // …and with template arguments
/// ```
///
/// The parse now reads each of them as **one name** — that is the fix that took `<xmemory>` from 153
/// declarations to 1175 — so the question this holds is the next one along: does the *type* of that name get
/// looked up, when the name the index knows is `f` and the spelling in the tree is `_STD f`.
#[test]
fn an_auto_written_through_a_macro_is_still_deduced() {
    let session = session_with(&[(
        "/p/a.cpp",
        "int f();\n\
         long g(int);\n\
         template <class T> T h();\n\
         void t() {\n\
             auto plain_a = f();\n\
             auto plain_b = g(1);\n\
             auto plain_c = h<int>();\n\
             auto a = _STD f();\n\
             auto b = (_STD g) (1);\n\
             auto c = _STD h<int>();\n\
         }\n",
    )]);
    let view = session.view("/p/a.cpp").expect("the file is held");

    let facts: Vec<cpp_code_analysis::DeclFact> = session
        .index()
        .summaries()
        .flat_map(|summary| summary.declarations.iter().cloned())
        .collect();

    let mut seen: Vec<String> = Vec::new();
    for (name, expected) in [
        ("plain_a", "int"),
        ("plain_b", "long"),
        ("plain_c", "int"),
        ("a", "int"),
        ("b", "long"),
        ("c", "int"),
    ] {
        let fact = facts
            .iter()
            .find(|fact| fact.name == name && fact.type_of.as_deref() == Some("auto"))
            .unwrap_or_else(|| {
                panic!(
                    "`{name}` is declared `auto`: {:?}",
                    facts
                        .iter()
                        .map(|fact| (&fact.name, &fact.type_of))
                        .collect::<Vec<_>>()
                )
            });

        match cpp_code_analysis::sema::deduce::deduced_type_of(
            session.index(),
            &view.scopes,
            &view.root,
            &view.path,
            fact,
        ) {
            // **The expectation is asserted, not just recorded.** It was a tuple the loop never read, so the six
            // types below were written down and then discarded — the test only checked the last line's `a=int`, and
            // a deduction that answered `long` for a `1` would have passed. A deduction that disagrees with what
            // the initializer says is the defect this file is about, whichever of the six it is.
            Known::Yes(type_of) => {
                assert_eq!(type_of, expected, "`{name}`'s deduced type");
                seen.push(format!("{name}={type_of}"));
            }
            other => seen.push(format!("{name}={other:?}")),
        }
    }

    assert!(
        seen.iter().any(|got| got == "a=int"),
        "a macro-prefixed call is a call: {seen:?}"
    );
}
/// **A view of the rendering sees no macro at all** — which is what a compiler's parser is handed.
///
/// `_MY_STD` is `::std::` to a compiler and an ordinary identifier to a reader of one file, so a parse of the file's
/// own tokens has to guess which of the two identifiers in `_MY_STD widget` is the name — and the grammar carries a
/// family of rules for that guess (`MacroCall`, `written_like_a_macro`, `is_a_macro`). A view of the **rendering**
/// needs none of them, because the file it parses has the macro already replaced:
///
/// ```text
/// the file writes     _MY_STD widget w;      the parser sees a name, then a name, then a name
/// the rendering has   ::std:: widget w;      the parser sees a qualified name and nothing to guess about
/// ```
///
/// Three things are asserted, and the third is the one that makes the view usable at all:
///
/// * the rendering's tree holds **no `MacroCall`** — the node every macro reading produces;
/// * the declaration it reads is in scope `mine`, because the body really is a namespace there;
/// * a position in the **file** and a position in the **rendering** map to each other, because a client speaks the
///   first and every offset in the view is the second.
#[test]
fn a_view_of_the_rendering_has_no_macros_left_to_guess_about() {
    let session = session_with(&[
        (
            "/p/ns.h",
            "#define _MY_BEGIN namespace mine {\n#define _MY_END }\n",
        ),
        (
            "/p/a.cpp",
            "#include \"ns.h\"\n_MY_BEGIN struct thing { int b; }; _MY_END\n",
        ),
    ]);
    let mut session = session;
    session.add_project_files(["/p/a.cpp".into(), "/p/ns.h".into()]);
    session.index_everything();

    let file = session
        .files()
        .held("/p/a.cpp")
        .expect("the file is held")
        .clone();
    let rendered = session
        .rendering_of("/p/a.cpp")
        .expect("the file's closure was read, so it renders");

    // **The text itself is the first evidence**: the macro is gone and the namespace it stood for is there.
    assert!(
        !rendered.text.contains("_MY_BEGIN"),
        "the rendering has no invocation left: {}",
        rendered.text
    );
    assert!(
        rendered.text.contains("namespace mine"),
        "…and what the macro stood for is written out: {}",
        rendered.text
    );

    let view = cpp_code_analysis::FileView::parse_rendering(&file, &rendered);

    let mut macro_calls = 0;
    let mut stack = vec![view.root.clone()];
    while let Some(node) = stack.pop() {
        if cpp_parser::CppSyntaxKind::from(node.kind()) == cpp_parser::CppSyntaxKind::MacroCall {
            macro_calls += 1;
        }
        stack.extend(node.children());
    }
    assert_eq!(
        macro_calls, 0,
        "a rendering has nothing for a macro rule to read: {macro_calls} MacroCall(s)"
    );

    // **The two coordinate systems, asserted by the text rather than by a direction.** The rendering is not simply
    // longer or shorter than the file — an `#include` line is gone from it and a macro's body is written out in
    // it, and the two move offsets opposite ways — so "smaller" and "larger" are both wrong as assertions, and the
    // first version of this test failed on its own arithmetic rather than on the mapping. What is true is that the
    // file offset the mapping gives points at the same **spelling**: the characters there are the first of
    // `struct thing`, which is what a client means by asking about that position.
    let at_struct = rendered
        .text
        .find("struct thing")
        .expect("the rendering has the declaration");
    let in_the_file = view
        .file_offset_of(cpp_code_analysis::file::coordinates::ReadingOffset::new(
            at_struct,
        ))
        .expect("a position in the rendering is a position in the file");

    let written = view
        .written_text()
        .expect("a view of a rendering holds the file's own text");
    assert!(
        written[in_the_file.get()..].starts_with("struct thing"),
        "the mapping points at the same spelling: file offset {in_the_file} is `{}`",
        &written[in_the_file.get()..(in_the_file.get() + 12).min(written.len())]
    );
    assert!(
        written.contains("_MY_BEGIN"),
        "…and the text it points into is the one the reader wrote, macro and all"
    );
}

/// **A function with no written return type returns what its `return` statements state.**
///
/// `auto f() { … }` records `returns: None`, and the reason has not changed: `auto` is not a class anything can be
/// looked up in. What the body says is a different question, and four of its shapes settle it without an inference —
/// a cast names its type, a literal is its own, a parameter is declared beside the body, and two operands that agree
/// need no conversion table. Every one of the five answers below was checked against the compiler before this test
/// was written (`static_assert(std::is_same_v<decltype(x), …>)` on each), which is the criterion a *type* deserves.
///
/// The refusal matters as much as the answers: `return b.p;` is a member access, whose type is declared in `beta` —
/// a lookup this layer cannot do — and a **guess** there would be worse than the refusal, because `returns` is what
/// the member lookup reads. A wrong type offers the wrong members; a missing one offers none.
#[test]
fn a_function_with_no_written_return_type_states_one_in_its_body() {
    let session = session_with(&[(
        "/p/a.cpp",
        "struct beta { int* p; };\n\
         auto a_literal() { return 1; }\n\
         auto a_cast(int n) { return static_cast<unsigned long long>(n); }\n\
         auto a_binary(int a, int b) { return a + b; }\n\
         auto a_compare(int a, int b) { return a < b; }\n\
         auto a_parameter(int* q) { return q; }\n\
         auto a_member(beta b) { return b.p; }\n\
         auto disagrees(int a, int* q) {\n\
             if (a) { return reinterpret_cast<int*>(q); }\n\
             return reinterpret_cast<const char*>(q);\n\
         }\n",
    )]);
    let view = session.view("/p/a.cpp").expect("the file is held");

    let returns = |name: &str| -> Option<String> {
        session
            .index()
            .summaries()
            .flat_map(|summary| summary.declarations.iter())
            .find(|fact| fact.name == name)
            .unwrap_or_else(|| panic!("`{name}` is declared"))
            .returns
            .clone()
    };

    assert_eq!(
        returns("a_literal").as_deref(),
        Some("int"),
        "a literal's type is its own"
    );
    assert_eq!(
        returns("a_cast").as_deref(),
        Some("unsigned long long"),
        "a cast names the type it produces"
    );
    assert_eq!(
        returns("a_binary").as_deref(),
        Some("int"),
        "two operands that agree need no conversion table"
    );
    assert_eq!(
        returns("a_compare").as_deref(),
        Some("bool"),
        "a comparison is `bool` whatever its operands are"
    );
    assert_eq!(
        returns("a_parameter").as_deref(),
        Some("int*"),
        "the parameter's own declaration is in the same tree"
    );

    let _ = &view;
    assert_eq!(
        returns("a_member"),
        None,
        "a member access needs the object's type, which is a lookup rather than a reading"
    );
    assert_eq!(
        returns("disagrees"),
        None,
        "`if constexpr` makes one branch per instantiation, and this layer does not instantiate"
    );
}

/// **`c ? a : b` is the type the arms agree on**, which is C++'s rule for the case this layer can decide.
///
/// The condition is a `bool` and never part of the answer, so the whole question is the two arms. When they have the
/// same type that is the type, whichever arm runs — measured: `_Val ? *_VbFirst : ~*_VbFirst` in MSVC's `<vector>`,
/// seven `auto` declarations whose arms are both the `_Vb_reference` the bit iterator's operators return.
///
/// # Why the mixed case is asserted to *stay* refused
///
/// `c ? 1 : 2.0` is a `double`, and the conversion is what decides. This layer does not rank conversions — the same
/// boundary the binary arm draws, for the same reason — so a test that only checked the agreeing arms would pass on
/// an implementation that answered "the first arm's type", and that answer is wrong exactly where `auto` matters.
#[test]
fn a_conditional_has_the_type_its_arms_agree_on() {
    let session = session_with(&[(
        "/p/a.cpp",
        "int a_value = 1;\n\
         int b_value = 2;\n\
         bool pick_it = true;\n\
         int* p = nullptr;\n\
         void f() {\n\
             auto from_ints = pick_it ? a_value : b_value;\n\
             auto from_a_pointer = pick_it ? p : p;\n\
             auto from_mixed = pick_it ? a_value : p;\n\
         }\n",
    )]);
    let view = session.view("/p/a.cpp").expect("the file is held");

    let facts: Vec<cpp_code_analysis::DeclFact> = session
        .index()
        .summaries()
        .flat_map(|summary| summary.declarations.iter().cloned())
        .collect();

    let deduced = |name: &str| -> String {
        let fact = facts
            .iter()
            .find(|fact| fact.name == name && fact.type_of.as_deref() == Some("auto"))
            .unwrap_or_else(|| panic!("`{name}` is an `auto` the file writes"));
        match session.type_at(
            &view,
            cpp_code_analysis::file::coordinates::ReadingOffset::new(fact.name_range.start_offset),
        ) {
            cpp_code_analysis::Known::Yes(type_of) => type_of.type_of.clone(),
            other => panic!("`{name}` has a type the file gives: {other:?}"),
        }
    };

    assert_eq!(deduced("from_ints"), "int", "both arms are `int`");
    assert_eq!(deduced("from_a_pointer"), "int*", "both arms are `int*`");

    let mixed = facts
        .iter()
        .find(|fact| fact.name == "from_mixed" && fact.type_of.as_deref() == Some("auto"))
        .expect("`from_mixed` is an `auto` the file writes");
    assert!(
        !matches!(
            session.type_at(
                &view,
                cpp_code_analysis::file::coordinates::ReadingOffset::new(
                    mixed.name_range.start_offset
                )
            ),
            cpp_code_analysis::Known::Yes(_)
        ),
        "the arms disagree, so the conversion decides — and this layer does not rank conversions"
    );
}

/// **`const` and `static` are drawn as modifiers, and a type is not.**
///
/// See [`NameModifier`]: a modifier is a claim about a declaration, read from the file's own specifier tokens —
/// the same table `access_at` uses. Three cases are pinned because two of them were wrong on the first attempt: a
/// `const` object and a `static` one must carry their modifier, and a **type** must carry neither, which is what a
/// first version got wrong (`struct Widget` came out `readonly static`, because it asked the shape table for
/// specifiers a type cannot have).
#[test]
fn a_modifier_is_read_from_the_declarations_own_specifiers() {
    use cpp_code_analysis::semantic::NameModifier;

    // **The nesting is the point, and it is why the type is inside a namespace.** The false positive this pins was
    // `struct Widget` coming out `readonly static`, and it came from asking the shape table for specifiers a type
    // cannot have: the walk finds the innermost shape that *has* specifiers, and a declaration inside a namespace
    // has that namespace's shapes above it. A bare `struct Widget { … };` at file scope has no specifiers anywhere
    // near it, so the first version of this test passed with the guard removed — it was testing nothing.
    let source = "namespace outer {\n\
                  struct Widget { static int count; };\n\
                  }\n\
                  const int limit = 3;\n\
                  static int file_scope = 0;\n\
                  int plain = 0;\n";
    let session = session_with(&[("/p/a.cpp", source)]);
    let view = session.view("/p/a.cpp").expect("the file is held");
    let names = session.classified_names(&view);

    let modifiers_of = |spelling: &str| -> Vec<NameModifier> {
        names
            .iter()
            .filter(|name| &source[name.range.start_offset..name.range.end_offset()] == spelling)
            .flat_map(|name| name.modifiers.clone())
            .collect()
    };

    assert!(
        modifiers_of("limit").contains(&NameModifier::ReadOnly),
        "`const int limit` is readonly"
    );
    assert!(
        modifiers_of("file_scope").contains(&NameModifier::Static),
        "`static int file_scope` is static"
    );
    assert!(
        modifiers_of("plain").is_empty(),
        "a plain `int` carries nothing"
    );
    assert!(
        modifiers_of("Widget").is_empty(),
        "a type is not readonly and not static — a modifier that cannot be true is a visible wrong claim"
    );
}

/// **A definition written with a qualified name is a definition**, and today it is not a fact at all.
///
/// `void LuaSource::From(int)` declares `LuaSource::From` outside its class — the shape every `.cpp` uses for every member
/// it defines. The scope walk binds nothing for it (a qualified declarator declares no name in the *enclosing* scope), so
/// `build_facts` produces no fact, and find-implementations has nothing on the definition side.
///
/// Measured on `LuaParser/src/File/LuaSource.cpp` (the document's example): 6507 bytes, 53 declarations parsed, and **0
/// facts**.
#[test]
fn a_qualified_definition_is_a_fact() {
    let session = session_with(&[(
        "/p/a.cpp",
        "class LuaSource {\npublic:\n    void From(int depth);\n};\nvoid LuaSource::From(int depth) {\n    (void)depth;\n}\n",
    )]);
    let summary = session
        .index()
        .summary(std::path::Path::new("/p/a.cpp"))
        .expect("the file is indexed");
    let names: Vec<(String, String)> = summary
        .declarations
        .iter()
        .map(|fact| (fact.name.clone(), fact.qualified_name()))
        .collect();
    println!("facts: {names:?}");
    assert!(
        names
            .iter()
            .any(|(name, qualified)| name == "From" && qualified == "LuaSource::From"),
        "the out-of-class definition is a fact of its own: {names:?}"
    );
}

/// **Which of the file's three shapes loses its fact** — the fixture above worked with `void F::G(int)`, and the real file
/// has the shapes below.
#[test]
fn the_three_shapes_of_the_real_file() {
    let cases: &[(&str, &str, &str)] = &[
        (
            "a `std::size_t` return",
            "class C {\npublic:\n    unsigned long GetLine(unsigned long offset) const;\n};\nunsigned long C::GetLine(unsigned long offset) const {\n    return offset;\n}\n",
            "GetLine",
        ),
        (
            "a template return type",
            "namespace std { template <class T> class shared_ptr { }; }\nclass C {\npublic:\n    void From();\n};\nstd::shared_ptr<C> C::From() {\n    return std::shared_ptr<C>();\n}\n",
            "From",
        ),
        (
            "a constructor with an initialiser list",
            "class C {\npublic:\n    C(int n);\n};\nC::C(int n)\n    : _n(n) {\n}\n",
            "C",
        ),
        (
            "a static member with a template argument",
            "namespace std { template <class T> class shared_ptr { }; }\nclass C {\npublic:\n    void From();\n};\nstd::shared_ptr<C> C::From(int) {\n    return std::shared_ptr<C>();\n}\n",
            "From",
        ),
    ];
    for (name, source, wanted) in cases {
        let session = session_with(&[("/p/a.cpp", source)]);
        let summary = session
            .index()
            .summary(std::path::Path::new("/p/a.cpp"))
            .expect("indexed");
        let found: Vec<String> = summary
            .declarations
            .iter()
            .map(|fact| fact.qualified_name())
            .collect();
        println!("{name:<40} → {found:?}");
        assert!(
            found.iter().any(|qualified| qualified.ends_with(wanted)),
            "{name} should be a fact: {found:?}"
        );
    }
}

/// **An include nobody can resolve must not erase the file's own facts.**
///
/// The real file starts with `#include "LuaParser/File/LuaSource.h"` and `#include "Util/Utf8.h"`, and it summarises to **0
/// declarations** with 0 parse errors. Every declaration shape in it works in a fixture that has no include, so the include
/// is the difference — either the rendering drops what follows a failed include, or the summary is taken from a text that
/// does.
///
/// # What was measured, and where the bug is
///
/// The **rendering is correct** — with the two includes unresolved it is exactly `unsigned long C::GetLine(…) const { … }`
/// — so the text `build_facts` reads is not the problem. The fact is missing because of where the **qualified prefix** comes
/// from: `fact_for` receives `scope` from `scopes.qualification_prefix_of(scope_id)`, and the case that works in a fixture
/// works because the class is *declared in the same file* — the scope tree then knows what `C::` refers to. In a real
/// `.cpp` the class is in a header, so with no include resolved the prefix is `None`, and a qualified declarator whose
/// prefix is unknown produces **no fact at all**. That is the document's ③, and its fix is the documented one: a second
/// pass over the **tree** for declarations whose declarator is qualified, taking the prefix from the declarator's own text
/// (the last `::` segment is the name, everything before it is the scope) rather than from the scope tree.
#[test]
fn an_unresolved_include_does_not_erase_the_files_own_facts() {
    let session = session_with(&[(
        "/p/a.cpp",
        "#include \"missing/Header.h\"\n#include \"missing/Other.h\"\n\nunsigned long C::GetLine(unsigned long offset) const {\n    return offset;\n}\n",
    )]);
    let summary = session
        .index()
        .summary(std::path::Path::new("/p/a.cpp"))
        .expect("indexed");
    let found: Vec<String> = summary
        .declarations
        .iter()
        .map(|fact| fact.qualified_name())
        .collect();
    println!("with unresolved includes: {found:?}");
    if let Some(view) = session.view(std::path::Path::new("/p/a.cpp")) {
        println!("rendering: {:?}", view.source);
    } else {
        println!("rendering: none");
    }
    assert!(
        found.iter().any(|qualified| qualified.ends_with("GetLine")),
        "the file's own definition survives an include nobody can resolve: {found:?}"
    );
}
/// **A template parameter is not a declaration in the file's scope.**
///
/// `template <class _Tp> struct A { _Tp value; };` used to file `_Tp` as a `Type` declaration **at file scope**, because
/// `qualification_prefix_of` skips the parameter-list scope and the fact builder walked every scope's bindings. On a
/// real project that was **2288** facts named `_Tp` — 492 of them in `<type_traits>` alone — and a single lookup of
/// the name took **167–187 ms** and answered 2288 declarations, none of which is a class.
///
/// The parameter is not lost: it is on the class's own fact (`DeclFact::parameters`), which is where the substitution
/// step reads it, and that is what the second half of this test pins.
#[test]
fn a_template_parameter_is_not_a_declaration_at_file_scope() {
    let session = session_with(&[(
        "/p/a.cpp",
        "template <class _Tp>\nstruct A {\n    _Tp value;\n};\n",
    )]);
    let summary = session
        .index()
        .summary(std::path::Path::new("/p/a.cpp"))
        .expect("indexed");
    let names: Vec<&str> = summary
        .declarations
        .iter()
        .map(|fact| &*fact.name)
        .collect();
    println!("facts: {names:?}");

    assert!(
        !names.contains(&"_Tp"),
        "a template parameter is not a declaration a file-scope lookup can find: {names:?}"
    );
    assert!(names.contains(&"A"), "the class itself is still a fact");
    assert!(
        names.contains(&"value"),
        "and its member is, with `_Tp` as its written type"
    );

    let class = summary
        .declarations
        .iter()
        .find(|fact| fact.name == "A")
        .expect("the class's own fact");
    assert_eq!(
        class.parameters,
        ["_Tp"],
        "the parameters live on the fact, which is what substitution reads"
    );

    match session
        .index()
        .definitions("_Tp", std::path::Path::new("/p/a.cpp"))
    {
        Known::Unknown(reason) => println!("lookup `_Tp`: {reason:?}"),
        Known::Yes(found) => panic!(
            "`_Tp` is a template parameter, so no declaration is findable by that name: {:?}",
            found
                .found
                .iter()
                .map(|entry| entry.fact.qualified_name())
                .collect::<Vec<_>>()
        ),
        Known::No => panic!("`definitions` answers `Known`, not `No`"),
    }
}
/// **A qualified definition carries its parameter list**, which is what a signature help's label is read from when the
/// declaring file has no rendering.
///
/// Found by `tests/signature_real.rs`: on a real project, `SetupStyle(style, options);` answered **no signature** while
/// the fixture tests passed. The chain was: the call is in the `.cpp`; the index's `definitions("SetupStyle")` answers
/// the **definition fact in that same file** (the "own file wins" rule); that fact's `parameter_list` was `None`; and
/// the signature's fallback — which builds the label from the fact when the header is not cooked — therefore had
/// nothing to build.
#[test]
fn a_qualified_definition_carries_its_parameter_list() {
    let session = session_with(&[(
        "/p/a.cpp",
        "struct C {\n    void f(int a, int b);\n};\nvoid C::f(int a, int b) { }\n",
    )]);
    let summary = session
        .index()
        .summary(std::path::Path::new("/p/a.cpp"))
        .expect("indexed");
    let found: Vec<(&str, Option<&str>)> = summary
        .declarations
        .iter()
        .filter(|fact| fact.name == "f")
        .map(|fact| (&*fact.name, fact.parameter_list.as_deref()))
        .collect();
    println!("facts for `f`: {found:?}");
    assert!(
        found.iter().any(|(_, parameters)| parameters.is_some()),
        "the declaration has a list, and the definition's own is `(int a, int b)`: {found:?}"
    );
}
/// **A member whose return type is separated from its name by a directive is still a member.**
///
/// libstdc++ writes every `erase` overload of `std::vector` this way:
///
/// ```cpp
///       _GLIBCXX20_CONSTEXPR
///       iterator
/// #if __cplusplus >= 201103L
///       erase(const_iterator __position)
///       { return _M_erase(begin() + (__position - cbegin())); }
/// #else
///       erase(iterator __position)
///       { return _M_erase(__position); }
/// #endif
/// ```
///
/// Measured before the fix: `facts_probe` on `bits/stl_vector.h` answered **0** facts for `erase`
/// and 2 for `push_back`, so `members_of("std::vector")` said "no member `erase`" — the last
/// false-positive diagnostic on a real project.
///
/// The cause was [`cpp_parser::grammar`]'s follower question ("does a declarator still follow this name?"): the
/// follower of `iterator` was the `#`, which is neither an identifier nor a specifier, so the name was refused the
/// type position and became the *declarator*. A directive is transparent to that question now.
#[test]
fn a_member_whose_return_type_a_directive_separates_is_a_member() {
    let session = session_with(&[(
        "/p/a.cpp",
        "struct C {\n    int x;\n    CONSTEXPR\n    iterator\n#if __cplusplus >= 201103L\n    erase(const_iterator p)\n    { return p; }\n#else\n    erase(iterator p)\n    { return p; }\n#endif\n    int size();\n};\n",
    )]);
    let summary = session
        .index()
        .summary(std::path::Path::new("/p/a.cpp"))
        .expect("indexed");
    let found: Vec<(&str, Option<&str>, &str)> = summary
        .declarations
        .iter()
        .filter(|fact| fact.name == "erase")
        .map(|fact| {
            (
                &*fact.name,
                fact.parameter_list.as_deref(),
                fact.scope.as_deref().unwrap_or("<file scope>"),
            )
        })
        .collect();
    println!("facts for `erase`: {found:?}");
    assert!(
        found
            .iter()
            .any(|(_, parameters, scope)| parameters.is_some() && *scope == "C"),
        "`erase` is a member of `C` with a parameter list: {found:?}"
    );
}
/// **A function whose return type ends in `&` keeps its parameter list.**
///
/// The declarator is nested for this shape — `__ostream_type& operator<<(long)` is
/// `InitDeclarator > Declarator > (Declarator(&), NameExpr, ParameterList)` — and the fact pass took the **last**
/// declarator on the path, which is the `&` wrapper and has no list. Every such function became a fact with
/// `parameter_list: None`: on libstdc++'s 579 headers, `parse_loss_probe` counted **1 937 of 15 253** functions that
/// way, and `bits/ostream.h` was 53 of 66. A signature help, a hover and an argument check all saw a function with
/// no arguments.
///
/// The declarator that is chosen now is the one whose **direct child names the binding** — the one the name and the
/// list belong to — which leaves a function pointer's own list (`void (*f)(int)`) where it was, because there the
/// name is not a direct child of the declarator that holds the list.
#[test]
fn a_function_returning_a_reference_keeps_its_parameter_list() {
    let session = session_with(&[(
        "/p/a.cpp",
        "struct S {\n    __ostream_type& operator<<(long n) { return n; }\n    Widget& value(int a, int b) { return a; }\n};\n",
    )]);
    let summary = session
        .index()
        .summary(std::path::Path::new("/p/a.cpp"))
        .expect("indexed");
    let found: Vec<(&str, Option<&str>)> = summary
        .declarations
        .iter()
        .filter(|fact| matches!(fact.kind, cpp_code_analysis::DeclKind::Function))
        .map(|fact| (&*fact.name, fact.parameter_list.as_deref()))
        .collect();
    println!("functions: {found:?}");
    assert!(
        found
            .iter()
            .any(|(name, parameters)| *name == "operator<<" && *parameters == Some("(long n)")),
        "the operator keeps its list: {found:?}"
    );
    assert!(
        found
            .iter()
            .any(|(name, parameters)| *name == "value" && parameters.is_some()),
        "and so does the reference-returning member: {found:?}"
    );
}
/// **A return type split by a directive is no return type at all.**
///
/// `bits/stl_bvector.h` writes `emplace_back` as
///
/// ```text
/// #if __cplusplus > 201402L
///     _GLIBCXX20_CONSTEXPR
///     reference
/// #else
///     void
/// #endif
///     emplace_back(_Args&&... __args)
/// ```
///
/// and the specifier sequence the type is read from is that text: the walk steps over the directives and answers the
/// nearest type, which is the `#else` branch's `void` — in a C++20 project where the function returns `reference`
/// (the rendering says so; measured over three headers, 12 of 1589 facts disagreed with the rendering about the return
/// type, every one of them this shape).
///
/// **Which branch is live is the preprocessor's answer, and the summary now has it.** The written
/// reading could not know it — a summary was keyed by the text and the configuration, and
/// `__cplusplus` is neither — so the fact used to decline to name a type at all
/// (`DeclFact::split_by_a_directive`). The other branch is proved where a compiler defines it —
/// `rendering_real.rs`'s `the_rendering_is_the_reading`, on libstdc++'s `stl_bvector.h`, where `#if
/// __cplusplus > 201402L` holds and `emplace_back` returns `reference`.
///
/// A declaration whose specifiers are not split keeps its type, which is the other half of the rule.
#[test]
fn a_return_type_a_directive_splits_is_the_branch_this_compilation_takes() {
    let session = session_with(&[(
        "/p/a.cpp",
        "struct S {\n\
         #if __cplusplus > 201402L\n\
         \tWidget\n\
         #else\n\
         \tvoid\n\
         #endif\n\
         \tmake(int a);\n\
         int plain(int a);\n\
         };\n",
    )]);
    // The branch `__cplusplus` selects is the **cooked** reading's answer, not the summary's: the summary is
    // environment-free and holds both branches.
    let cooked = session
        .index()
        .cooked_reading(std::path::Path::new("/p/a.cpp"))
        .expect("the file was read in its program");
    let found: Vec<(&str, Option<&str>)> = cooked
        .declarations
        .iter()
        .filter(|fact| matches!(fact.kind, cpp_code_analysis::DeclKind::Function))
        .map(|fact| (&*fact.name, fact.returns.as_deref()))
        .collect();
    println!("returns: {found:?}");
    assert!(
        found
            .iter()
            .any(|(name, returns)| *name == "make" && *returns == Some("void")),
        "the `#else` branch is the one this configuration compiles, and one answer is named: {found:?}"
    );
    assert!(
        found
            .iter()
            .any(|(name, returns)| *name == "plain" && *returns == Some("int")),
        "and an unsplit one keeps its type: {found:?}"
    );
}

/// **A function pointer is drawn as a function.**
///
/// `binary_op operation = add;` declares a *variable* — the fact says so, and hover says "a variable" — but the type
/// is `int (*)(int, int)`, so a reader scanning `operation(1, 2)` reads a call, and a theme that colours functions is
/// where that call belongs. The type decides, so the rule is narrow:
///
/// * a variable whose type is a function pointer, directly or through a typedef, is `function`;
/// * an ordinary variable stays `variable`;
/// * a **parameter** keeps its own kind — `int g(binary_op callback)` says what the name is, and that is more than
///   the type can.
#[test]
fn a_function_pointer_variable_is_drawn_as_a_function() {
    let names = classified(
        "\
typedef int (*binary_op)(int, int);
static int add(int a, int b) { return a + b; }
int g(binary_op callback) { return callback(1, 2); }
int f(void) { binary_op operation = add; int value = 1; return operation(value, 2); }
",
    );

    let kinds: Vec<(NameKind, bool)> = names
        .iter()
        .filter(|(text, _, _)| text == "operation")
        .map(|(_, kind, declaration)| (*kind, *declaration))
        .collect();
    assert!(
        !kinds.is_empty() && kinds.iter().all(|(kind, _)| *kind == NameKind::Function),
        "a function pointer is drawn as a function, declared and used: {kinds:?}"
    );

    let callback: Vec<NameKind> = names
        .iter()
        .filter(|(text, _, _)| text == "callback")
        .map(|(_, kind, _)| *kind)
        .collect();
    assert!(
        !callback.is_empty() && callback.iter().all(|kind| *kind == NameKind::Parameter),
        "a parameter stays a parameter: {callback:?}"
    );

    let value: Vec<NameKind> = names
        .iter()
        .filter(|(text, _, _)| text == "value")
        .map(|(_, kind, _)| *kind)
        .collect();
    assert!(
        !value.is_empty() && value.iter().all(|kind| *kind == NameKind::Variable),
        "an ordinary variable stays a variable: {value:?}"
    );

    let alias: Vec<NameKind> = names
        .iter()
        .filter(|(text, _, _)| text == "binary_op")
        .map(|(_, kind, _)| *kind)
        .collect();
    assert!(
        !alias.is_empty() && alias.iter().all(|kind| *kind == NameKind::Type),
        "and the typedef itself is still a type: {alias:?}"
    );
}

/// **A member whose `if` condition holds a preprocessor directive does not swallow the rest of the class.**
///
/// The reduced reproducer for `docs/buglist.md` §31. Three ingredients, each necessary:
///
/// ```text
/// a *resolved* #include      an unresolved one, or the same text written inline, parses correctly
/// namespace std {            the class must be in a namespace
/// ||  +  #if in an if        inside a member function body inside the class
/// ```
///
/// Measured before the fix: `Following` landed with scope `std::Impl` — the class body ended early and the rest of the
/// file was re-parented inside the class. Reduced from `bits/shared_ptr_base.h`, where it left `__shared_ptr` with no
/// bases (and so `shared_ptr` without `operator*`/`operator->`).
///
/// **Two things were wrong, and this fixture needed both.** The grammar had no directive seam where an operand goes
/// (`a || #if … b #endif`), and a summary written by the older grammar was still on disk and answered for it —
/// `C:\p\.cppls` for this fixture, and `test_cpp\.cppls` in the real project. So `FORMAT_VERSION` moved to 14 with
/// the grammar fix: a summary that describes an older reader is a wrong answer, not a missing one.
#[test]
fn an_include_and_a_directive_in_a_condition_do_not_swallow_the_class() {
    let session = session_with(&[
        ("/p/included.h", "int nothing;\n"),
        (
            "/p/a.cpp",
            "\
#include \"included.h\"
namespace std {
class Impl {
public:
    virtual void* f(const int& __ti) noexcept
    {
	if (1 == 2
	    ||
#if __cpp_rtti
	    3 == 4
#else
	    5 == 6
#endif
	   )
	  return 0;
	return 0;
    }
    int m;
};
class Following { public: void h(); };
}
",
        ),
    ]);
    // **The summary, not the session's own view.** The view's scope tree answers `std` for this file; the summary — what
    // the index reads, and what `inspect facts` printed — is the one that derails. So the test asks the summary.
    let summary = session
        .index()
        .summary(std::path::Path::new("/p/a.cpp"))
        .expect("the file's summary");
    let following = summary
        .declarations
        .iter()
        .find(|fact| fact.name == "Following")
        .unwrap_or_else(|| panic!("`Following` must be a fact: {:?}", summary.declarations));
    assert_eq!(
        following.scope.as_deref(),
        Some("std"),
        "the class after the member is a class of the namespace, not of `Impl`"
    );
}

/// **A constructor written with a specifier is a member too** — `explicit A(int x)` keeps its name in the specifier
/// sequence and its declarator holds only `(int x)`, so the binding path that reads declarators found the parameters
/// and never the function.
///
/// Measured before the fix, on this fixture: `inspect facts` listed `A` at 4:5 (the `A() {}`) and nothing at 2:5, so
/// `A::` offered one of the class's two constructors and a hover on the decorated declaration answered the *class*
/// instead of the constructor. After it: `2:14 A function in A modifiers 0x100` (0x100 is `explicit`), beside the
/// destructor and `A()`.
#[test]
fn a_constructor_written_with_a_specifier_is_a_member() {
    let session = session_with(&[(
        "/p/a.cpp",
        "\
struct A {
    explicit A(int x) : x_(x) {}
    virtual ~A() {}
    A() {}
    int f();
    int x_;
};
",
    )]);
    let summary = session
        .index()
        .summary(std::path::Path::new("/p/a.cpp"))
        .expect("the file's summary");
    let constructors: Vec<_> = summary
        .declarations
        .iter()
        .filter(|fact| fact.name == "A" && fact.kind == DeclKind::Function)
        .collect();
    assert_eq!(
        constructors.len(),
        2,
        "both constructors are members: {:?}",
        summary.declarations
    );
    let decorated = constructors
        .iter()
        .find(|fact| fact.modifiers.contains(DeclModifiers::EXPLICIT))
        .expect("the decorated one says it is explicit");
    assert_eq!(
        decorated.scope.as_deref(),
        Some("A"),
        "it is a member of its class"
    );
    assert_eq!(
        decorated.parameter_list.as_deref(),
        Some("(int x)"),
        "**and its parameters**, which the declarator does not hold either: without the fallback the fact read as a \
         constructor that takes nothing, which a completion row and a signature help both believe"
    );
    assert!(
        summary
            .declarations
            .iter()
            .any(|fact| fact.kind == DeclKind::Function && fact.name == "~A"),
        "and the destructor is beside it: {:?}",
        summary.declarations
    );
}

/// **`T x(a, b);` is an initialisation when `a` can be a value** — the most vexing parse, resolved by what the names are.
///
/// The grammar cannot tell `std::unique_lock<M> lock(mutex, 1);` from a declaration of a function `lock`: `mutex` alone
/// looks like an unnamed parameter of type `mutex`, which is how `void f(int);` writes one. A parameter list holds
/// *types*, so a name this file binds as a value settles it.
///
/// Measured before, on `test_cpp/src/concurrency.cpp:32`: hovering the variable answered "lock — a function, declared in
/// a function body", and every `lock.lock()` after it resolved against that phantom. After: a variable of type
/// `std::unique_lock<M>`, and the member list it offers is the class's.
#[test]
fn a_parenthesised_initialisation_with_a_value_is_a_variable() {
    let session = session_with(&[(
        "/p/a.cpp",
        "\
namespace std {
template <class T>
struct unique_lock {
    unique_lock(T& m, int mode);
    void lock();
};
}
struct M { };
std::M mutex;
void f() {
    std::unique_lock<M> lock(mutex, 1);
    lock.lock();
}
",
    )]);
    let summary = session
        .index()
        .summary(std::path::Path::new("/p/a.cpp"))
        .expect("the file's summary");
    let declared = summary
        .declarations
        .iter()
        .find(|fact| fact.name == "lock" && fact.kind == DeclKind::Variable)
        .unwrap_or_else(|| panic!("`lock` is a variable: {:?}", summary.declarations));
    assert_eq!(
        declared.type_of.as_deref(),
        Some("std::unique_lock<M>"),
        "the initialiser is not part of the type"
    );
    assert!(
        declared.local,
        "it is declared in a function body: {declared:?}"
    );
}

/// **The standard's position-dependent macros are classified as macros** — `__LINE__`, `__FILE__`, `__DATE__`,
/// `__TIME__`.
///
/// They are defined for every translation unit, and neither table the session has can say so: `g++ -dM -E` prints
/// `#define __cplusplus 201703L` and none of these (measured), and the standard's own table answers *values*, which
/// these do not have — `__LINE__` is the line it stands on. Reported from an editor as
/// `__LINE__ << __FILE__ << __DATE__ << __TIME__` arriving with no colour at all.
#[test]
fn the_standards_position_dependent_macros_are_classified() {
    let source = "\
void f() {
    log(__LINE__, __FILE__, __DATE__, __TIME__);
}
";
    let session = session_with(&[("/p/a.cpp", source)]);
    let view = session.view("/p/a.cpp").expect("the file is held");
    let names = session.classified_names(&view);
    for macro_name in ["__LINE__", "__FILE__", "__DATE__", "__TIME__"] {
        let at = source.find(macro_name).expect("the fixture names it");
        let found = names
            .iter()
            .find(|name| name.range.start_offset == at)
            .unwrap_or_else(|| panic!("`{macro_name}` is not classified: {names:?}"));
        assert_eq!(
            found.kind,
            NameKind::Macro,
            "`{macro_name}` is drawn as a macro: {found:?}"
        );
        assert!(!found.declaration, "and it declares nothing: {found:?}");
    }
}