cpp_code_analysis 0.1.4

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
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
//! Building scopes and bindings from a file's syntax tree.
//!
//! The tests are organised by the question a consumer asks, and the first thing most of them do is render the
//! scope tree as a single line — `KIND{names}(children)` — because the shape is what is easy to get subtly
//! wrong and hard to notice. A scope one level too deep, or a parameter bound in the enclosing block instead
//! of the function, produces a tree that still looks plausible and gives wrong completions everywhere.
//!
//! Scope is what these tests are about, so the renderings show scopes and the names in them, and nothing else.

use cpp_code_analysis::{BindingKind, ScopeKind, ScopeTree, build_scopes};
use cpp_parser::{CppParser, CppSyntaxKind, ParserConfig};

/// Parse, check the parse is sound, and build the scopes.
fn scopes(source: &str) -> ScopeTree {
    let tree = CppParser::parse(source, ParserConfig::default());

    assert_eq!(
        tree.to_source_text(),
        source,
        "the parse must stay lossless before anything is read out of it"
    );
    assert_eq!(
        tree.get_errors(),
        [],
        "the input must parse cleanly for its shape to mean anything: {:?}",
        tree.get_errors()
    );

    build_scopes(&tree.get_red_root(), &cpp_code_analysis::NoMacroBodies)
}

/// The scope tree as one line: `KIND{name, name}(children)`.
///
/// A scope with no bindings prints as `KIND` rather than `KIND{}`, so a rendering that lost its bindings is
/// distinguishable from one that never had any.
fn shape(table: &ScopeTree) -> String {
    fn render(table: &ScopeTree, id: cpp_code_analysis::ScopeId, out: &mut String) {
        let scope = table.scope(id).expect("a scope that exists");

        let kind = match scope.kind {
            ScopeKind::TranslationUnit => "File",
            ScopeKind::Namespace => "Ns",
            ScopeKind::Class => "Class",
            ScopeKind::Enum => "Enum",
            ScopeKind::Function => "Fn",
            ScopeKind::Block => "Block",
            ScopeKind::TemplateParameters => "Params",
            ScopeKind::Lambda => "Lambda",
        };

        out.push_str(kind);

        if !scope.bindings.is_empty() {
            let names: Vec<String> = scope
                .bindings
                .iter()
                .map(|binding| binding.name.text())
                .collect();
            out.push('{');
            out.push_str(&names.join(","));
            out.push('}');
        }

        if !scope.children.is_empty() {
            out.push('(');
            for (index, child) in scope.children.iter().enumerate() {
                if index > 0 {
                    out.push(' ');
                }
                render(table, *child, out);
            }
            out.push(')');
        }
    }

    let mut out = String::new();
    if let Some(root) = table.root() {
        render(table, root, &mut out);
    }
    out
}

/// The kind of the binding a scope holds for `name`, or `None`.
fn kind_of(
    table: &ScopeTree,
    scope: cpp_code_analysis::ScopeId,
    name: &str,
) -> Option<BindingKind> {
    table
        .scope(scope)?
        .bindings
        .iter()
        .find(|binding| binding.name.identifier_text() == Some(name))
        .map(|binding| binding.kind)
}

/// A scope's qualified name, for the scope of kind `want` that introduces `name`.
///
/// `name` is `None` for the scopes that introduce nothing. `None` back means either no such scope or no
/// qualified name for it, which is why the callers that care about the difference pass a name that exists.
fn qualified_of(table: &ScopeTree, want: ScopeKind, name: Option<&str>) -> Option<String> {
    let id = table
        .scopes()
        .iter()
        .position(|scope| scope.kind == want && scope.name.as_deref() == name)?;

    table.qualified_name_of(cpp_code_analysis::ScopeId(id))
}

/// All bindings of a name in a scope, as `(kind, name_range)` pairs.
fn bindings_of(
    table: &ScopeTree,
    scope: cpp_code_analysis::ScopeId,
    name: &str,
) -> Vec<(BindingKind, cpp_parser::SourceRange)> {
    table
        .scope(scope)
        .map(|scope| {
            scope
                .bindings
                .iter()
                .filter(|binding| binding.name.identifier_text() == Some(name))
                .map(|binding| (binding.kind, binding.name_range))
                .collect()
        })
        .unwrap_or_default()
}

// ============================================================================
// The shape of a file's scopes
// ============================================================================

/// An empty file still has a file scope.
///
/// A table with no root would make "the file's declarations" undefined rather than empty, and every consumer
/// walking from the root would need a special case for it.
#[test]
fn an_empty_file_has_a_file_scope() {
    let table = scopes("");

    assert_eq!(shape(&table), "File");
    assert_eq!(table.len(), 1);
    assert!(table.root().is_some());
}

/// Top-level declarations land in the file scope, in one scope and not one each.
///
/// The commonest shape there is, and the one a naive walk gets wrong by opening a scope per declaration.
/// The names print in sorted order, not source order.
#[test]
fn top_level_declarations_share_the_file_scope() {
    let table = scopes("int count;\nvoid f();\nclass Widget {};\n");

    assert_eq!(shape(&table), "File{Widget,count,f}");
    assert_eq!(
        table.len(),
        1,
        "an empty class body opens no scope, so there is only the file's"
    );
}

/// A namespace opens a scope, and its contents go in it rather than in the file scope.
///
/// The names inside are printed in the table's order, which is sorted by name rather than by the order they
/// appear in the file: `f` sorts before `x` even though `x` is declared first.
#[test]
fn a_namespace_opens_a_scope() {
    let table = scopes("namespace ns { int x; void f(); }\n");

    assert_eq!(shape(&table), "File{ns}(Ns{f,x})");
}

/// Nested namespaces nest, and each declares its own name in its parent.
#[test]
fn nested_namespaces_nest() {
    let table = scopes("namespace outer { namespace inner { int x; } }\n");

    assert_eq!(shape(&table), "File{outer}(Ns{inner}(Ns{x}))");
}

/// A class opens a scope, and its members go in it.
///
/// The class's own name is declared in the *enclosing* scope, which is the part that is easy to get wrong: a
/// class declared inside its own scope would not be found by anything outside it.
#[test]
fn a_class_declares_its_name_outside_itself() {
    let table = scopes("class Widget { int value_; void size(); };\n");
    let file = table.root().unwrap();

    assert_eq!(
        shape(&table),
        "File{Widget}(Class{size,value_})",
        "the members are inside; the class is outside"
    );
    assert_eq!(kind_of(&table, file, "Widget"), Some(BindingKind::Class));

    let class = table.scope(file).unwrap().children[0];
    assert_eq!(
        kind_of(&table, class, "Widget"),
        None,
        "not a member of itself"
    );
    assert_eq!(
        kind_of(&table, class, "value_"),
        Some(BindingKind::Variable)
    );
    assert_eq!(kind_of(&table, class, "size"), Some(BindingKind::Function));
}

/// A class inside a class nests, and both names are visible where they are declared.
#[test]
fn a_nested_class_nests() {
    let table = scopes("struct Outer { struct Inner { int x; }; };\n");

    assert_eq!(shape(&table), "File{Outer}(Class{Inner}(Class{x}))");
}

/// A class whose body contains a destructor is still named by its own name.
///
/// The bug this pins: `~Widget` is spelled with a `~` token, and whether a name is a destructor was decided by
/// looking for that token with `descendants_with_tokens` over the whole **declaration**. For `struct Widget { ~Widget(); };`
/// the declaration is the `StructDef`, whose descendants include the destructor inside the body — so the *class*
/// became `~Widget`. The class's scope was named `~Widget`, every member written after the destructor landed in
/// it, and `Widget` itself was never bound at all.
///
/// Every class in real C++ has a destructor, so this was not an edge case: it silently renamed the class and
/// moved its members.
#[test]
fn a_class_with_a_destructor_in_its_body_keeps_its_own_name() {
    let table = scopes("struct Widget {\n  ~Widget();\n  int size;\n};\n");
    let file = table.root().unwrap();

    assert_eq!(
        shape(&table),
        "File{Widget}(Class{size,~Widget})",
        "the class is `Widget`, `size` is its member, and the destructor is a member too — it binds now, where \
         the walker used to bind no declarator that was not an `InitDeclarator`"
    );
    assert_eq!(kind_of(&table, file, "Widget"), Some(BindingKind::Class));
    assert_eq!(
        qualified_of(&table, ScopeKind::Class, Some("Widget")).as_deref(),
        Some("Widget"),
        "and the scope it opens is named after it, not after the destructor"
    );
}

/// An `operator` declaration in a class body does not make the class an operator either.
///
/// The same shape of bug as the destructor above, one token over: the search for the `operator` keyword has to
/// look in the **name node**, and a class body holding `operator+` put that keyword in the declaration's
/// descendants. Pinned separately because the two searches are separate calls and fixing one does not fix the
/// other.
///
/// **And the operator is a member of the class**, which the old answer got wrong in the other direction: an
/// operator declares a name the language lets you call, and a class whose operators are invisible to every lookup
/// cannot answer `a + b`. The class keeps its own name *and* the operator is bound inside it.
#[test]
fn a_class_with_an_operator_in_its_body_keeps_its_own_name() {
    let table = scopes("struct Widget {\n  Widget& operator+(const Widget&);\n  int size;\n};\n");

    assert_eq!(
        shape(&table),
        "File{Widget}(Class{size,operator+}(Fn))",
        "the class is `Widget`, and the operator is a member of it"
    );
}

/// A declaration whose declarator is a bare `Declarator` — no `InitDeclarator` — **does** declare its name.
///
/// This test used to be `a_destructor_without_a_specifier_declares_nothing_yet`, written to fail the day the gap
/// landed, and it has: `~Widget();` is `Declaration[Declarator[NameExpr, ParameterList]]` with no
/// `DeclSpecifierSeq` and no `InitDeclarator`, and `CppDeclaration::get_name_token` now reads a bare declarator as
/// well. The rule it needed is exactly the one the old note asked for — a bare declarator whose `NameExpr` holds a
/// name — and the two shapes `is_unnamed_declaration` exists to reject are still rejected, which
/// `a_call_statement_declares_nothing` and `a_real_declaration_is_still_declared` above still check.
///
/// The name is the **whole spelling** `~Widget`, because a destructor's declarator is a `Declarator` whose
/// `NameExpr` holds a nested `Declaration` rather than an identifier: the token the walker finds has an empty
/// spelling, so `name_from_text` falls back to the node's own text. Without that the member would be bound as the
/// empty string — a row with no label, which is worse than the row being absent.
#[test]
fn a_destructor_without_a_specifier_declares_its_name() {
    let table = scopes("struct Widget {\n  ~Widget();\n  int size;\n};\n");

    assert_eq!(shape(&table), "File{Widget}(Class{size,~Widget})");
}

/// A `virtual` destructor **is** bound, and its name is not an identifier.
///
/// The other side of the boundary above, and the case that keeps the empty-name handling in the member-list
/// query from being dead code: the specifier sequence is what lets this declaration through the unnamed test, and
/// the name it binds is `~Widget` — a [`NameKind::Destructor`], whose `identifier_text()` is `None`. So a fact
/// built from it stores an empty name, and any rule that compared member names would compare two empty strings.
///
/// [`NameKind::Destructor`]: cpp_code_analysis::NameKind::Destructor
#[test]
fn a_virtual_destructor_is_bound_under_its_tilde_name() {
    let table = scopes("struct Widget {\n  virtual ~Widget();\n  int size;\n};\n");

    assert_eq!(shape(&table), "File{Widget}(Class{size,~Widget})");

    let class = table.scope(table.root().unwrap()).unwrap().children[0];
    let bound = table
        .scope(class)
        .unwrap()
        .bindings
        .iter()
        .find(|binding| binding.name.identifier_text().is_none())
        .expect("the destructor is bound");

    assert_eq!(bound.name.text(), "~Widget");
    assert_eq!(bound.kind, BindingKind::Destructor);
}

/// `class Widget;` declares the name even though no body follows.
///
/// A forward declaration makes `Widget` known as a class, so a table that only read definitions would leave
/// every name introduced by a forward declaration unresolvable — which in real headers is most of them.
#[test]
fn a_forward_declaration_declares_the_name() {
    let table = scopes("class Widget;\nstruct Point;\n");

    assert_eq!(shape(&table), "File{Point,Widget}");
    assert_eq!(
        kind_of(&table, table.root().unwrap(), "Widget"),
        Some(BindingKind::Class)
    );
}

/// An enum opens a scope, and its enumerators are in it.
///
/// **And the scope is *named***, which the shape alone cannot show: the name is what makes an enumerator's fact
/// `Color::Red` rather than a bare `Red` at file scope. Measured on a header declaring
/// `enum class IsTriviallyCopyConstructible { Yes, No };` — its scope came out unnamed, so every enumerator was
/// recorded as a file-scope variable: `E::Yes` could not be resolved from another file, the enumerator was drawn
/// as a variable rather than as an enum member, and a bare `Yes` was reachable from anywhere.
#[test]
fn an_enum_holds_its_enumerators() {
    let table = scopes("enum class Color { Red, Green = 2 };\n");

    assert_eq!(shape(&table), "File{Color}(Enum{Green,Red})");

    let file = table.root().unwrap();
    let enumeration = table.scope(file).unwrap().children[0];

    assert_eq!(
        table.qualified_name_of(enumeration).as_deref(),
        Some("Color"),
        "the enumerators belong to `Color`, not to the file"
    );

    assert_eq!(
        kind_of(&table, enumeration, "Red"),
        Some(BindingKind::Enumerator)
    );
    assert_eq!(
        kind_of(&table, file, "Red"),
        None,
        "an enumerator is not in the file scope"
    );

    // The same inside a namespace, which is where the standard library's traits live: the qualified name is what
    // the index stores a fact under, so this is the spelling `E::Yes` has to be resolved through.
    let nested = scopes("namespace std { enum class E { Yes }; }\n");
    let file = nested.root().unwrap();
    let namespace = nested.scope(file).unwrap().children[0];
    let enumeration = nested.scope(namespace).unwrap().children[0];
    assert_eq!(
        nested.qualified_name_of(enumeration).as_deref(),
        Some("std::E")
    );
}

/// A function declares its name outside and binds its parameters inside.
///
/// The distinction that makes `for (int i = 0; ...)` and `void f(int i)` behave: a parameter is visible in the
/// body and not outside it, and the body does not nest inside the parameter list.
#[test]
fn a_function_binds_its_parameters_in_its_own_scope() {
    let table = scopes("int add(int a, int b) { int sum = a + b; return sum; }\n");

    assert_eq!(shape(&table), "File{add}(Fn{a,b,sum})");

    let file = table.root().unwrap();
    let function = table.scope(file).unwrap().children[0];

    assert_eq!(kind_of(&table, file, "add"), Some(BindingKind::Function));
    assert_eq!(
        kind_of(&table, file, "a"),
        None,
        "a parameter is not in the file scope"
    );
    assert_eq!(kind_of(&table, function, "a"), Some(BindingKind::Variable));
    assert_eq!(
        kind_of(&table, function, "sum"),
        Some(BindingKind::Variable)
    );
}

/// A parameter is bound once, not once as a parameter and again as a body declaration.
///
/// The body's contents are walked into the function's scope directly, so a parameter list that also reached the
/// body's walk would bind every parameter twice — and a consumer showing overloads would show each one twice.
#[test]
fn a_parameter_is_bound_exactly_once() {
    let table = scopes("void f(int value) { value = 1; }\n");

    let function = table.scope(table.root().unwrap()).unwrap().children[0];
    let bindings = bindings_of(&table, function, "value");

    assert_eq!(bindings.len(), 1, "{:?}", table.scope(function).unwrap());
}

/// A parameter of a declaration with no body is still bound, because the parameter exists either way.
#[test]
fn a_declaration_without_a_body_still_binds_its_parameters() {
    let table = scopes("void f(int a, double b);\n");

    assert_eq!(shape(&table), "File{f}(Fn{a,b})");
}

/// A statement block inside a body opens a nested scope.
///
/// What makes two sibling branches free to declare the same name, and what makes a name declared in a block
/// invisible after it.
#[test]
fn a_block_opens_a_nested_scope() {
    let table = scopes("void f() { { int inner; } }\n");

    assert_eq!(shape(&table), "File{f}(Fn(Block{inner}))");
}

/// A range-based `for` binds its variable in the loop's scope, not in the enclosing block.
///
/// The construct is one of the most common loops in modern C++, and it used to not parse at all — so this test
/// could not be written until the grammar was fixed. What it pins is the same property the C-style loop has:
/// the variable belongs to the loop, and the body is a scope nested inside it.
#[test]
fn a_range_for_opens_a_scope_for_its_variable() {
    let table = scopes("void f() { for (auto x : items) { } }\n");

    assert_eq!(
        shape(&table),
        "File{f}(Fn(Block{x}(Block)))",
        "`x` is in the loop's scope; the body is nested inside it"
    );

    let function = table.scope(table.root().unwrap()).unwrap().children[0];
    let loop_scope = table.scope(function).unwrap().children[0];

    assert_eq!(
        kind_of(&table, loop_scope, "x"),
        Some(BindingKind::Variable),
        "the loop variable is declared where the loop can see it"
    );
    assert_eq!(
        kind_of(&table, table.root().unwrap(), "x"),
        None,
        "and not at file scope"
    );
}

/// A range-based `for` over a structured binding declares every name in the pattern.
///
/// The combination that needed two fixes at once: the range reading itself, and the pattern's names, which are
/// reached through a different path from an ordinary declarator.
#[test]
fn a_range_for_over_a_structured_binding_binds_each_name() {
    let table = scopes("void f() { for (auto [key, value] : map) { } }\n");

    assert_eq!(shape(&table), "File{f}(Fn(Block{key,value}(Block)))");
}

/// A range-based `for`'s range expression is not a declaration.
#[test]
fn a_range_for_over_a_call_binds_only_its_variable() {
    let table = scopes("void f() { for (int x : make_items()) { } }\n");

    assert_eq!(shape(&table), "File{f}(Fn(Block{x}(Block)))");
}

/// A bare expression statement declares nothing — including the statements the grammar reads as declarations.
///
/// The most vexing parse leaves a statement-shaped hole in the declaration grammar: `use(x);` arrives as a
/// `Declaration` whose declarator names nothing, because `use` was taken for a type and `(x)` for a
/// parenthesised declarator. What the analysis *can* say is whether a name was declared, and none was.
///
/// Without this the cost is not subtle: **every call statement in every function** contributed a binding for
/// its first argument, so a scope reported names the code only uses. That is why the list is asserted to be
/// empty rather than the shapes being pinned.
///
/// `use(x);` is one of these statements — it parses, and is misread, so it belongs here rather than among the
/// calls that parse correctly. See `direct_initialisation_of_a_user_type_does_not_parse_yet` for the same
/// ambiguity from the other side.
#[test]
fn a_call_statement_declares_nothing() {
    for body in [
        "use(x);",
        "f();",
        "g(a, b);",
        "x;",
        "a = b;",
        "++i;",
        "a + b;",
        "delete p;",
        "return;",
    ] {
        let source = format!("void f() {{ {body} }}\n");
        let table = scopes(&source);
        let function = table.scope(table.root().unwrap()).unwrap().children[0];

        let declared: Vec<String> = table
            .scope(function)
            .unwrap()
            .declared_names()
            .iter()
            .map(|name| name.text())
            .collect();

        assert!(
            declared.is_empty(),
            "{body:?} is a statement, but the walker declared {declared:?}"
        );
    }
}

/// The rule that rejects a call's argument does not reject a declaration that has a name.
///
/// The other half of the same rule, and the half that would break silently: a gate that rejected too much
/// would leave every function body empty of declarations, which no single test above would notice.
#[test]
fn a_real_declaration_is_still_declared() {
    let table = scopes(
        "void f() {\n\
         int local;\n\
         int initialised = 1;\n\
         const char* name = \"x\";\n\
         auto deduced = 2;\n\
         Widget widget{1, 2};\n\
         int direct(1, 2);\n\
         std::vector<int> values;\n\
         Foo* pointer = new Foo();\n\
         }\n",
    );

    assert_eq!(
        shape(&table),
        "File{f}(Fn{deduced,direct,initialised,local,name,pointer,values,widget})",
        "every one of these declares a name"
    );
}

/// Direct-initialisation — `Type name(args);` — declares a variable.
///
/// One of the most common declarations in C++, and it used to fail outright. A `(` after a declared name is a
/// **parameter list** or the parentheses of a **direct-initialised variable**, and the two are told apart by
/// what they can hold: `int a(b)` has a parameter, because `b` parses as a type, while `int a(1)` does not,
/// because `1` is not one.
///
/// A keyword type is the case that needs no lookup at all. A **user type** needs the file's own declarations,
/// which is the other half of the same rule and has its own test below.
#[test]
fn direct_initialisation_declares_a_variable() {
    for source in [
        "void f() { int a(1); }\n",
        "void f() { double d(1.5); }\n",
        "void f() { char c('x'); }\n",
        "void f() { unsigned int u(1); }\n",
    ] {
        let tree = CppParser::parse(source, ParserConfig::default());

        assert_eq!(
            tree.get_errors(),
            [],
            "{source:?} must parse cleanly, got {:?}",
            tree.get_errors()
        );
        assert_eq!(
            tree.to_source_text(),
            source,
            "{source:?} must stay lossless"
        );

        assert!(
            tree.get_red_root()
                .descendants()
                .any(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::Initializer),
            "{source:?} declares a variable with an initializer"
        );
    }
}

/// A **call** keeps its parentheses, because a bare name in front of `(` is not a declared type.
///
/// The other half of the rule above, and the half a naive fix breaks: reading every `(...)` after a name as an
/// initializer makes `g(1, 2);` into a declaration that declares nothing, so the statement loses its callee
/// *and* its arguments — and a name enters scope that was never declared. That is the direction to avoid, so a
/// name nothing in the file declares to be a type stays a callee.
///
/// `g();` is deliberately absent: an empty argument list is the most vexing parse's other half, and `T x()` is
/// a function declaration, so a call with no arguments is read as one — which is what C++ does with it too.
#[test]
fn a_call_keeps_its_argument_list() {
    for source in [
        "void f() { g(1); }\n",
        "void f() { g(1, 2); }\n",
        "void f() { obj.method(1); }\n",
        "void f() { p->method(x); }\n",
        // A file-scope call is not valid C++, but the reading must still not invent a variable out of it.
        "Max(a, 1);\n",
    ] {
        let tree = CppParser::parse(source, ParserConfig::default());

        assert_eq!(
            tree.get_errors(),
            [],
            "{source:?} must parse cleanly, got {:?}",
            tree.get_errors()
        );
        assert!(
            tree.get_red_root()
                .descendants()
                .any(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::CallExpr),
            "{source:?} is a call, not a declaration"
        );
    }
}

/// Direct-initialisation of a **user-defined** type parses, because the file says the name is a type.
///
/// `Widget w(1, 2);` and `g(1, 2);` are the same tokens with different meanings, and which is right depends on
/// whether `Widget` names a type. C++ settles it by looking the name up, and that is exactly why `int x(2)` is
/// unambiguous (`int` is a keyword) while `Widget w(1, 2);` is not.
///
/// The parser has no symbol table, but it does have the file, so it records the names a class-like head, a
/// `typedef` or a `using` alias introduces and asks that table. A name it finds is read as a declaration; a name
/// it does not is left to the expression reading, because the two mistakes are not equally bad — reading a *call*
/// as a declaration loses its callee and its arguments and puts a name in scope that was never declared, while
/// reading a *declaration* as a call merely leaves the variable unbound.
///
/// This is deliberately a **file-local** judgement: a type from an included header is not in the table, so
/// `std::string s("x");` stays an expression. Recording what a file declares is not the same claim as resolving
/// names across files, and the query layer is where that second claim belongs.
#[test]
fn direct_initialisation_of_a_user_type_declares_a_variable() {
    for source in [
        "struct Widget {};\nvoid f() { Widget w(1, 2); }\n",
        "class Widget {};\nvoid f() { Widget w(1, 2); }\n",
        "union Widget {};\nvoid f() { Widget w(1, 2); }\n",
        "enum class Widget {};\nvoid f() { Widget w(1, 2); }\n",
        "using Widget = int;\nvoid f() { Widget w(1, 2); }\n",
        "typedef int Integer;\nvoid f() { Integer i(1); }\n",
        "struct Outer { struct Inner {}; void m() { Inner i(1); } };\n",
        "struct Widget {};\nWidget make();\n",
    ] {
        let tree = CppParser::parse(source, ParserConfig::default());

        assert_eq!(
            tree.get_errors(),
            [],
            "{source:?} must parse cleanly, got {:?}",
            tree.get_errors()
        );
        assert_eq!(
            tree.to_source_text(),
            source,
            "{source:?} must stay lossless"
        );
    }

    // The variables themselves, which is what the scope layer reads off the tree.
    let table = scopes(
        "struct Widget {};\nvoid f() {\n  Widget w(1, 2);\n  Widget v;\n}\nstruct Outer { Inner i(1); };\n",
    );

    assert_eq!(
        shape(&table),
        "File{Outer,Widget,f}(Fn{v,w} Class{i})",
        "both direct-initialised variables are declared"
    );
}

/// A user type written **before** its declaration is a type for the *parser*, which reads the statement by its
/// shape rather than by the table.
///
/// The table is still filled in as the file is read, and still cannot answer for a name declared further down —
/// but the parser no longer needs it to: `Widget w(1, 2);` is a declaration because it has a name and an
/// argument list, and no call has that shape. The declaration reading no longer depends on the order in which
/// the file is written, which is what a file being edited needs.
#[test]
fn a_user_type_declared_later_is_still_a_declaration() {
    let source = "void f() { Widget w(1, 2); }\nstruct Widget {};\n";
    let tree = CppParser::parse(source, ParserConfig::default());

    assert!(
        tree.get_red_root()
            .descendants()
            .any(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::Initializer),
        "the declarator's name is the evidence, and it is there whether or not the type is"
    );
    assert_eq!(tree.to_source_text(), source, "and the file stays lossless");
}

/// A user type the file never declares at all is still a declaration.
///
/// This used to be the documented cost of a file-local table: nothing says `Widget` is a type, so
/// `Widget w(1, 2);` kept the reading that lost the least. It is a declaration now, because the *shape* says so —
/// a name followed by an argument list is not a call — and the trade moved to the other side: `A(B);` is read as
/// a call, and `MyType` used in a cast has to be declared somewhere in the file.
#[test]
fn an_undeclared_type_name_is_still_a_declaration() {
    for source in [
        "void f() { Widget w(1, 2); }\n",
        "void f() { std::string s(\"x\"); }\n",
        "void f() { Foo bar(1); }\n",
    ] {
        let tree = CppParser::parse(source, ParserConfig::default());

        assert!(
            tree.get_red_root()
                .descendants()
                .any(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::Initializer),
            "{source:?} names a declarator and initialises it"
        );
        assert_eq!(tree.to_source_text(), source, "{source:?} stays lossless");
    }
}

/// `sizeof` of a **builtin** type parses, as it always should have.
///
/// `sizeof(std::vector<int>)` and `sizeof(Foo)` worked — the first as a type, the second as an expression, since
/// a bare name is one. Only `sizeof(int)` failed, because `int` cannot start an expression and the
/// parenthesised-type reading was missing. It is there now, and this test pins that the two readings of `sizeof`
/// both work.
#[test]
fn sizeof_a_builtin_type_parses() {
    for source in [
        "void f() { sizeof(int); }\n",
        "void f() { sizeof(unsigned char); }\n",
    ] {
        let tree = CppParser::parse(source, ParserConfig::default());

        assert!(
            tree.get_errors().is_empty(),
            "{source:?} should parse, got {:?}",
            tree.get_errors()
        );
        assert_eq!(tree.to_source_text(), source, "and stays lossless");
    }

    // The neighbouring spellings that do parse, asserted so the gap cannot be described more broadly than it is.
    for source in [
        "void f() { sizeof(std::vector<int>); }\n",
        "void f() { sizeof(Foo); }\n",
        "void f() { sizeof x; }\n",
    ] {
        let tree = CppParser::parse(source, ParserConfig::default());
        assert_eq!(tree.get_errors(), [], "{source:?} parses");
    }
}

/// Assignment and compound assignment parse, in every spelling, and the statement forms built on them.
///
/// These used to fail with `expected `;` after expression`, and the cause was not in the statement rules at all
/// but in the **binary operator table**: no assignment operator was in it, so `a = b` parsed as the bare
/// expression `a` and stopped at the `=`. The expression reading then reported a missing `;`, and the
/// declaration/expression fallback could not help because the *expression* reading was the one that failed.
///
/// Worth a test of its own rather than a line in another: assignments are in nearly every line of real C++, so
/// their absence made the parser report a syntax error on ordinary code — the false positives that get an
/// editor-facing tool switched off.
#[test]
fn assignment_operators_parse() {
    for body in [
        "a = b;",
        "i += 1;",
        "i -= 1;",
        "i *= 2;",
        "i /= 2;",
        "i %= 2;",
        "flags &= mask;",
        "flags |= mask;",
        "flags ^= mask;",
        "value <<= 2;",
        "value >>= 2;",
        "a = b = c;",
        "arr[0] = 1;",
        "arr[0] += 1;",
        "p->field = 1;",
        "p->next = q;",
        "obj.field = obj.other;",
        "*p = 5;",
        "x = y + z * w;",
    ] {
        let source = format!("void f() {{ {body} }}\n");
        let tree = CppParser::parse(&source, ParserConfig::default());

        assert_eq!(
            tree.get_errors(),
            [],
            "{body:?} must parse cleanly, got {:?}",
            tree.get_errors()
        );
        assert_eq!(tree.to_source_text(), source, "{body:?} must stay lossless");
    }
}

/// Assignment is right-associative and everything else is left-associative.
///
/// The shape rather than the outcome: `*p = *q = 5` is `*p = (*q = 5)`, and reading it left-associatively would
/// give `(*p = *q) = 5`, which is not a thing anyone writes and is not what the source says. Pinned because the
/// tree round-trips either way — a wrong associativity is invisible to every losslessness check.
///
/// The operands are dereferences on purpose. `a = b = c;` cannot be used: at statement position it is read as a
/// **declaration** of `a`, because `a` may be a type name and `= b = c` then looks like an initializer. `*p`
/// cannot be a type, so this statement is unambiguously an expression and the shape under test is the
/// expression's own.
#[test]
fn assignment_is_right_associative() {
    let source = "void f() { *p = *q = 5; }\n";
    let tree = CppParser::parse(source, ParserConfig::default());

    assert_eq!(tree.get_errors(), [], "must parse cleanly");

    let outer = tree
        .get_red_root()
        .descendants()
        .find(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::BinaryExpr)
        .expect("a binary expression");

    assert_eq!(
        outer.text().to_string(),
        "*p = *q = 5",
        "the outer assignment covers the whole chain"
    );

    let inner = outer
        .children()
        .find(|child| CppSyntaxKind::from(child.kind()) == CppSyntaxKind::BinaryExpr)
        .expect("the right-hand side is itself an assignment");

    assert_eq!(
        inner.text().to_string(),
        "*q = 5",
        "which is what right-associative means here"
    );
}

/// A loop's init-declaration goes in the loop's scope, not in the enclosing block.
///
/// The case that decides whether `for (int i = 0; ...)` leaks `i` into the surrounding function — and the
/// reason a scope is opened for the loop rather than for its body.
///
/// Three levels, and each is doing something: the function's own block, the scope the loop opens for its init
/// declaration, and the body's block **inside** that — which is what lets the body see `i` while the rest of
/// the function cannot.
#[test]
fn a_loop_opens_a_scope_for_its_init_declaration() {
    let table = scopes("void f() { for (int i = 0; i < 3; ++i) { int body; } }\n");

    assert_eq!(
        shape(&table),
        "File{f}(Fn(Block{i}(Block{body})))",
        "`i` is in the loop's scope; `body` is in the body's, nested inside it"
    );
}

/// Two sibling branches each get their own scope, so the same name can be declared in both.
///
/// The function's body is one block, and each branch opens a scope inside it — so a name declared in a branch
/// is not visible after the branch, and the same name can appear in both without colliding.
#[test]
fn sibling_branches_have_separate_scopes() {
    let table = scopes("void f() { if (c) { int x; } else { int x; } }\n");

    assert_eq!(
        shape(&table),
        "File{f}(Fn(Block(Block{x} Block{x})))",
        "the function's block, then one scope per branch"
    );

    // And they are different bindings, which is the point: one declaration each, in separate scopes.
    let function = table.scope(table.root().unwrap()).unwrap().children[0];
    let body = table.scope(function).unwrap().children[0];
    let branches = &table.scope(body).unwrap().children;

    assert_eq!(branches.len(), 2, "one scope per branch");
    let first = bindings_of(&table, branches[0], "x");
    let second = bindings_of(&table, branches[1], "x");

    assert_eq!(first.len(), 1);
    assert_eq!(second.len(), 1);
    assert_ne!(
        first[0].1, second[0].1,
        "two declarations of the same name at different offsets"
    );
}

/// A `switch` opens one scope for all its cases.
///
/// One scope and not one per case, because that is what C++ does: a declaration in one `case` is in scope in
/// the next, which is why people write braces inside a `case`.
#[test]
fn a_switch_opens_one_scope_for_all_its_cases() {
    let table = scopes("void f() { switch (n) { case 1: { int a; } case 2: { int b; } } }\n");

    assert_eq!(shape(&table), "File{f}(Fn(Block(Block{a} Block{b})))");
}

/// A label is bound in the scope it appears in.
#[test]
fn a_label_is_bound() {
    let table = scopes("void f() { goto done; done: return; }\n");

    assert_eq!(shape(&table), "File{f}(Fn{done})");

    let function = table.scope(table.root().unwrap()).unwrap().children[0];
    assert_eq!(kind_of(&table, function, "done"), Some(BindingKind::Label));
}

// ============================================================================
// Types, aliases, and using
// ============================================================================

/// A `typedef` declares a name, read from its declarator rather than from the node.
#[test]
fn a_typedef_declares_its_name() {
    let table = scopes("typedef int Integer;\n");

    assert_eq!(shape(&table), "File{Integer}");
    assert_eq!(
        kind_of(&table, table.root().unwrap(), "Integer"),
        Some(BindingKind::Typedef)
    );
}

/// **Every** name a `typedef` lists, not the first.
///
/// `typedef WCHAR *PWCHAR, *LPWCH, *PWCH;` introduces three type names in one declaration, and that is how every C
/// header writes its pointer aliases — `winnt.h` hundreds of times. Binding only the first left the others
/// undeclared: a consumer asking for `LPWCH` found nothing, and every fact about it was missing from the index.
#[test]
fn a_typedef_declares_every_name_it_lists() {
    let table = scopes("typedef WCHAR *PWCHAR, *LPWCH, *PWCH;\n");

    assert_eq!(shape(&table), "File{LPWCH,PWCH,PWCHAR}");
    for name in ["PWCHAR", "LPWCH", "PWCH"] {
        assert_eq!(
            kind_of(&table, table.root().unwrap(), name),
            Some(BindingKind::Typedef),
            "`{name}` is one of the declaration's names"
        );
    }
}

/// `using Alias = T;` is an alias, and `using ns::f;` is a using-declaration.
///
/// The same node kind for two constructs that mean different things, told apart by whether a type follows the
/// `=`. A consumer offering completions treats them differently — one is a type, the other is whatever `f` was.
#[test]
fn a_using_declaration_is_told_apart_from_an_alias() {
    let table = scopes("using Alias = int;\n");
    assert_eq!(
        kind_of(&table, table.root().unwrap(), "Alias"),
        Some(BindingKind::Alias)
    );

    let table = scopes("using ns::f;\n");
    assert_eq!(
        shape(&table),
        "File{f}",
        "the name is the last component, not the qualifier"
    );
    assert_eq!(
        kind_of(&table, table.root().unwrap(), "f"),
        Some(BindingKind::UsingDeclaration)
    );
}

/// `using namespace std;` is recorded, and binds a namespace rather than a variable.
///
/// It introduces no name of its own, so the alternative to recording it is leaving no trace at all — and then a
/// consumer asking "why is `vector` in scope here" has nothing to point at.
#[test]
fn a_using_directive_is_recorded() {
    let table = scopes("using namespace std;\n");

    assert_eq!(shape(&table), "File{std}");
    assert_eq!(
        kind_of(&table, table.root().unwrap(), "std"),
        Some(BindingKind::UsingDirective)
    );
}

// ============================================================================
// Templates
// ============================================================================

/// A template's parameters go in a scope of their own, and the declaration is inside it.
///
/// What makes `T` visible in the template's body and invisible outside. The class's *name*, though, is declared
/// where the template was written — a class declared inside its own parameter scope would be unreachable.
#[test]
fn a_template_parameter_scope_wraps_the_declaration() {
    let table = scopes("template <typename T, int N> class Array { T data[N]; };\n");

    assert_eq!(
        shape(&table),
        "File{Array}(Params{N,T}(Class{data}))",
        "`Array` is outside the parameter scope; `T` and `N` are in it"
    );
}

/// A template parameter is a `TemplateParameter`, not an alias.
///
/// The difference decides whether `T::value_type` is a name that can be looked up now or one that depends on an
/// argument: storing `T` as an alias would make it look like a known type.
#[test]
fn a_template_parameter_has_its_own_kind() {
    let table = scopes("template <typename T> T id(T x) { return x; }\n");

    let params = table.scope(table.root().unwrap()).unwrap().children[0];

    assert_eq!(
        kind_of(&table, params, "T"),
        Some(BindingKind::TemplateParameter)
    );
    assert_eq!(
        table.scope(params).unwrap().kind,
        ScopeKind::TemplateParameters
    );
}

/// A template parameter is not in the file scope, and the function declared by the template is.
#[test]
fn a_template_parameter_is_not_in_the_file_scope() {
    let table = scopes("template <typename T> T id(T x) { return x; }\n");

    let shape = shape(&table);
    assert!(shape.starts_with("File{id}(Params{T}"), "{shape}");
    assert_eq!(
        kind_of(&table, table.root().unwrap(), "T"),
        None,
        "T belongs to the template"
    );
}

// ============================================================================
// What is deliberately not bound
// ============================================================================

/// A qualified declaration binds nothing in the enclosing scope.
///
/// `int ns::Widget::count = 0;` declares a member of `ns::Widget`, not a name in the file scope. Binding it as
/// plain `count` would put a name in scope that cannot be used unqualified — and it would collide with every
/// other `count` in the file.
#[test]
fn a_qualified_declaration_binds_nothing_here() {
    let table = scopes("int ns::Widget::count = 0;\n");

    assert_eq!(
        shape(&table),
        "File",
        "the name belongs to `ns::Widget`, which this file does not declare"
    );
}

/// **A `::` in the base clause is not this declaration's name.**
///
/// A declaration is read as *qualified* — and so binds nothing here — when its **specifier sequence** mentions
/// a `::`-qualified name that does not belong to a declarator. That rule exists for `void Box<int>::grow()`,
/// and it has now twice caught text that is not the declaration's name at all:
///
/// ```text
/// class basic_string { … };        the ClassBody, 94 KB of members writing `X::y` all over it
/// struct W : Base<A::B> {};        the BaseSpecifier, which is where a class names its template
/// ```
///
/// Both were called qualified, both asked whether the qualifier named a scope *this file* had built, both got
/// `false`, and both returned before binding anything — so the class had no binding and therefore **no fact**,
/// with **no parse error to show for it**.
///
/// Measured before the fix, on `<vector>`'s closure: `xmemory:755` writes
/// `struct [[msvc::no_specializations(…)]] allocator_traits : conditional_t<…, _Default_allocator_traits<_Alloc>,
/// _Normal_allocator_traits<_Alloc>> {};` and produced **no fact for `allocator_traits` at all** — only one for
/// its template parameter — while every unqualified base beside it was declared normally. A 311-byte file
/// holding that declaration verbatim is the whole reproduction.
///
/// The two directions are asserted together because the fix is a `continue` in a shared walk: dropping too
/// much would make `int ns::Widget::count = 0;` bind `count` at file scope, which is the mistake the rule was
/// written to prevent.
#[test]
fn a_qualified_name_in_a_base_clause_does_not_make_the_declaration_qualified() {
    // The plain qualified base, a qualified name inside the base's template arguments, and several bases.
    for source in [
        "struct W : Base<A::B> {};\n",
        "struct W : A::B {};\n",
        "struct W : public Base<std::vector<int>> {};\n",
        "struct W : Base<A::B>, Other<C::D> {};\n",
        "template <class T> struct W : conditional_t<A::value, Base> {};\n",
    ] {
        let table = scopes(source);
        let file = table.scope(table.root().unwrap()).unwrap();
        let names: Vec<String> = file
            .bindings
            .iter()
            .map(|binding| binding.name.text())
            .collect();

        assert!(
            names.iter().any(|name| name == "W"),
            "the class is declared here — nothing in its base clause is its own name: {source:?} gave {names:?}"
        );
    }

    // …and the rule this protects is still in force.
    let table = scopes("int ns::Widget::count = 0;\n");
    assert_eq!(
        shape(&table),
        "File",
        "a genuinely qualified declaration still binds nothing here"
    );
}

/// A `friend` declaration binds nothing: a friend is not a member.
///
/// `friend class X;` says X's members may reach into this class. Binding `X` as a member would make it appear
/// in member completion, where it is not a member at all.
#[test]
fn a_friend_declaration_binds_nothing() {
    let table = scopes("class Widget { friend class Helper; friend void free_fn(); };\n");

    let class = table.scope(table.root().unwrap()).unwrap().children[0];
    let names: Vec<String> = table
        .scope(class)
        .unwrap()
        .bindings
        .iter()
        .map(|binding| binding.name.text())
        .collect();

    assert!(
        names.is_empty(),
        "a friend declares nothing here, got {names:?}"
    );
}

/// **A class whose members write qualified names is still a class this file declares.**
///
/// The measured case is `std::basic_string`, which is 94 KB of members and writes `::` all over the body
/// (`allocator_traits<_Alloc>::…`, `pointer_traits<pointer>::…`). `declaration_is_qualified` reads a `::` in the
/// specifier sequence as "this declaration names something through a qualifier" — the rule that keeps
/// `int ns::Widget::count = 0;` from binding `count` at file scope — and it used to descend **into the class
/// body** to find one. So the class was called a qualified declaration, the qualifier (`allocator_traits`) named
/// no scope this file had built, and `declaration_parts` returned before binding anything.
///
/// The result was silence rather than a wrong answer: the class had no binding and therefore no fact, so
/// `cooked(<xstring>)` held 157 declarations and `basic_string` was not one of them, and `members_of("std::string")`
/// reported `NotDeclaredHere`.
///
/// Two shapes, because both were broken and both are ordinary: a member whose **type** is qualified, and one whose
/// **default argument** is.
#[test]
fn a_class_whose_members_write_qualified_names_is_still_declared() {
    for text in [
        "template <class T> class Widget { std::vector<int> values; };\n",
        "class Widget { int f(std::size_t n = std::numeric_limits<int>::max()); };\n",
        "struct Widget { using type = std::allocator_traits<Alloc>::value_type; };\n",
    ] {
        let table = scopes(text);
        let names: Vec<String> = table
            .scope(table.root().unwrap())
            .unwrap()
            .bindings
            .iter()
            .map(|binding| binding.name.text())
            .collect();

        assert!(
            names.iter().any(|name| name == "Widget"),
            "`Widget` is declared in this file, whatever its members write: {names:?} for {text:?}"
        );
    }
}

/// **A qualified name whose segments are separate nodes does not take the indexing thread down.**
///
/// `Outer<T>::grow` writes `<`, `T` and `>` in a **child node** of the name, so a reader that walks the name node's
/// own tokens sees no angle brackets at all, counts a depth of zero everywhere, and believes the `::` inside
/// `<A::B>` is a separator. That reader ended in `last_identifier(..).expect(..)` — no direct identifier token
/// either — and **panicked**, on a real project, inside the background indexing thread.
///
/// What the user saw was not an error message: a status bar that never stopped spinning (the pump never reached the
/// end of its work) and a completion list with nothing in it (a client that is told `isIncomplete` filters what it
/// has). Both of those are the same panic, and the corpus below is what the compiler's own headers are made of.
#[test]
fn a_qualified_name_with_nested_segments_is_read_without_panicking() {
    let table = scopes(
        "\
template <class T> struct Outer { struct Inner { void grow(); }; };
template <class T> void Outer<T>::Inner::grow() {}
template <class T> void Outer<T>::grow() {}
template <class T> void Outer<A::B>::grow() {}
void Outer<Box<int>>::grow() {}
void Outer<int>::grow(Outer<int>::Inner* p) {}
int Outer<int>::count = 0;
",
    );

    // The name is the last segment and the class is where the qualifier points — `grow` in `Outer::Inner` for the
    // first line, `grow` in `Outer` for the rest.
    let named = |wanted: &str| -> Vec<String> {
        (0..table.scopes().len())
            .filter(|index| {
                table
                    .qualified_name_of(cpp_code_analysis::ScopeId(*index))
                    .as_deref()
                    == Some(wanted)
            })
            .flat_map(|index| {
                table
                    .scope(cpp_code_analysis::ScopeId(index))
                    .map(|scope| {
                        scope
                            .bindings
                            .iter()
                            .map(|binding| binding.name.text())
                            .collect::<Vec<_>>()
                    })
                    .unwrap_or_default()
            })
            .collect()
    };

    let in_class = named("Outer");
    let in_inner = named("Outer::Inner");

    assert!(
        in_class.contains(&"grow".to_string()) && in_class.contains(&"count".to_string()),
        "the members written through a template argument are members of the class: {in_class:?}"
    );
    assert!(
        in_inner.contains(&"grow".to_string()),
        "and the nested one is in the nested class: {in_inner:?}"
    );
}

/// A `static_assert` declares nothing, and does not stop the declarations around it.
#[test]
fn a_static_assert_declares_nothing() {
    let table = scopes("int before;\nstatic_assert(true);\nint after;\n");

    assert_eq!(shape(&table), "File{after,before}");
}

/// A `static_assert` whose argument is a comparison *does* parse, template-id or not.
///
/// This was a documented gap in the parser: `static_assert(a > 0)` and `static_assert(true)` parsed, but
/// `static_assert(sizeof(int) > 0)` did not — the `>` was readable as closing a template argument list, and the
/// expression parser gave up rather than treating it as a comparison. The `sizeof` of a builtin type is read
/// now, and with it the comparison.
#[test]
fn a_static_assert_with_a_comparison_parses() {
    let source = "static_assert(sizeof(int) > 0);\n";
    let tree = CppParser::parse(source, ParserConfig::default());

    assert!(
        tree.get_errors().is_empty(),
        "the comparison should parse, got {:?}",
        tree.get_errors()
    );
    assert_eq!(
        tree.to_source_text(),
        source,
        "and stays lossless regardless"
    );

    // And it declares nothing, like every other `static_assert`.
    assert_eq!(shape(&scopes(source)), "File");
}

/// A reference is not a binding — only what a declaration introduces is.
///
/// Asserted explicitly because it is a design decision rather than an oversight: collecting uses is a different
/// pass with a different output shape, and doing it here would make a scope's bindings ambiguous between
/// "declared here" and "used here".
#[test]
fn a_use_is_not_a_binding() {
    let table = scopes("void f() { undeclared_name; other(); }\n");

    assert_eq!(
        shape(&table),
        "File{f}(Fn)",
        "nothing is bound for a name that is only used"
    );
}

// ============================================================================
// A scope a macro body opened
// ============================================================================

/// **A scope the file's braces do not write is opened from the macro's replacement list** — the reading MSVC's
/// STL needs and the one the tree cannot carry.
///
/// `<vector>` has no `namespace std` in it at all: the header writes `_STD_BEGIN` on a line of its own and the
/// brace that scopes 165 declarations is in `yvals_core.h`. The macro's *name* is in the file, its *meaning* is in
/// another one, and this is the seam: [`cpp_code_analysis::MacroBodies`].
///
/// Three assertions, and they are the three a consumer needs:
///
/// * the declarations are **scoped** — `vector`'s fact says `std`, which is what makes `std::vector` a name;
/// * the reading is **recorded with its evidence**, so a consumer that can ask the include graph again can check
///   the answer instead of trusting it (`MacroScopeReading`);
/// * the name is **not bound** — no binding points at the invocation, so "rename `std`" cannot rewrite the macro.
#[test]
fn a_scope_a_macro_body_opens_holds_the_declarations_behind_it() {
    use cpp_code_analysis::{CompilerConfig, Known, MemoryFiles, SummaryStore};

    let files = MemoryFiles::new()
        .with_file(
            "/p/ns.h",
            "#pragma once\n#define _STD_BEGIN namespace std {\n#define _STD_END }\n",
        )
        .with_file(
            "/p/main.cpp",
            "#include \"ns.h\"\n_STD_BEGIN\nstruct vector { int size; };\n_STD_END\n",
        );

    let root = std::env::temp_dir().join("cppls-macro-scope-tests");
    let _ = std::fs::remove_dir_all(&root);
    std::fs::create_dir_all(&root).expect("the test directory");

    let mut store = SummaryStore::with_provider(&root, CompilerConfig::default(), files);
    let indexed =
        store.index_includes_from(std::path::Path::new("/p/main.cpp"), Default::default());

    assert_eq!(
        indexed.re_read, 2,
        "both files mention a name the closure gives a body to — `main.cpp` invokes it and `ns.h` writes the \
         `#define` — which is exactly what the filter's soundness costs: one re-parse of the file that defined \
         it, whose summary comes out identical. What matters is that the file which does *not* mention it is not \
         re-read, and that nothing that could change is skipped: {:?}",
        indexed.indexed
    );

    let summary = store
        .index()
        .summary(std::path::Path::new("/p/main.cpp"))
        .expect("main.cpp is indexed");

    // (1) The declaration is scoped by a name the file never spells.
    let vector = summary
        .declarations
        .iter()
        .find(|fact| fact.name == "vector")
        .expect("the class was read");
    assert_eq!(
        vector.scope.as_deref(),
        Some("std"),
        "the body's `namespace std {{` is what puts it there: {:?}",
        summary
            .declarations
            .iter()
            .map(|fact| fact.qualified_name())
            .collect::<Vec<_>>()
    );
    assert_eq!(vector.qualified_name(), "std::vector");

    // (2) The evidence is kept, both halves of it: the invocation that opened the scope and the one that closed
    // it, each with the replacement list it was read from.
    let readings: Vec<(&str, Option<Vec<String>>)> = summary
        .macro_readings
        .iter()
        .map(|reading| (reading.name.as_str(), reading.opens.clone()))
        .collect();
    assert_eq!(
        readings,
        vec![
            ("_STD_BEGIN", Some(vec!["std".to_string()])),
            ("_STD_END", None),
        ],
        "both invocations are recorded, and the closer is told apart by having no scope"
    );
    // The body is kept **verbatim** — the slice `MacroFact::body_range` covers, whitespace and all — because it is
    // evidence to be compared with what the header says now, not a value to be normalised. The shape is read from
    // it by the lexer, which drops trivia; the record keeps it.
    assert_eq!(summary.macro_readings[0].body.trim(), "namespace std {");
    assert_eq!(summary.macro_readings[1].body.trim(), "}");

    // (3) A scope without a binding: the name is not declared *here*, so nothing may claim the invocation is
    // where `std` was written. The scope exists (that is what makes `std::vector` a qualified name) and there is
    // no fact for `std` — which is what keeps a rename from rewriting `_STD_BEGIN`.
    assert!(
        summary.declarations.iter().all(|fact| fact.name != "std"),
        "no fact is invented for a name the file does not write: {:?}",
        summary
            .declarations
            .iter()
            .map(|fact| fact.qualified_name())
            .collect::<Vec<_>>()
    );

    // …and the query a consumer asks: the qualified name resolves to the class, in this file.
    match store
        .index()
        .definition("std::vector", std::path::Path::new("/p/main.cpp"))
    {
        Known::Yes(found) => {
            assert_eq!(found.fact.name, "vector");
            assert_eq!(found.fact.qualified_name(), "std::vector");
        }
        other => panic!("`std::vector` must resolve through the scope a body opened: {other:?}"),
    }

    // **The shape MSVC actually writes**: an export macro in front of the declaration, so the class is not the
    // statement's first token. It is the same scoping question one token further in, and the one `<vector>` has
    // seventeen of (`_EXPORT_STD template <…> class vector { … }`).
    //
    // Two details are copied from `yvals_core.h` rather than invented, and both were measured:
    //
    // * `_EXPORT_STD` is defined as **nothing** in this configuration (`export` needs
    //   `_HAS_CXX23 && _BUILD_STD_MODULE`, and with that in force the declaration really is a module export);
    // * it is defined **inside a conditional**, which is what puts its body on the *in-force* channel instead of
    //   the definition channel. That distinction is not decoration: a name the tables describe as a *macro*
    //   changes which rule reads the line (`at_a_macro_that_stands_for_a_declaration` stands aside for a name it
    //   can describe), and MSVC's own definition is conditional for exactly this kind of reason.
    let files = MemoryFiles::new()
        .with_file(
            "/q/ns.h",
            "#pragma once\n#define _STD_BEGIN namespace std {\n#define _STD_END }\n\
             #if defined(_BUILD_STD_MODULE)\n#define _EXPORT_STD export\n#else\n#define _EXPORT_STD\n#endif\n",
        )
        .with_file(
            "/q/main.cpp",
            "#include \"ns.h\"\n_STD_BEGIN\n_EXPORT_STD template <class _Ty, class _Alloc = allocator<_Ty>>\nclass vector { // varying size array of values\npublic:\n    using value_type = _Ty;\n};\n_STD_END\n",
        );

    let mut store = SummaryStore::with_provider(&root, CompilerConfig::default(), files);
    store.index_includes_from(std::path::Path::new("/q/main.cpp"), Default::default());

    let summary = store
        .index()
        .summary(std::path::Path::new("/q/main.cpp"))
        .expect("main.cpp is indexed");
    let vector = summary
        .declarations
        .iter()
        .find(|fact| fact.name == "vector")
        .unwrap_or_else(|| {
            panic!(
                "the class was read: {:?}",
                summary
                    .declarations
                    .iter()
                    .map(|fact| (fact.qualified_name(), fact.kind))
                    .collect::<Vec<_>>()
            )
        });
    assert_eq!(
        vector.scope.as_deref(),
        Some("std"),
        "a macro in front of the declaration does not change whose scope it is in: {:?}",
        summary
            .declarations
            .iter()
            .map(|fact| fact.qualified_name())
            .collect::<Vec<_>>()
    );
}

/// **The same scope, when the macro is invoked in a header the entry point only reaches through another one.**
///
/// [`a_scope_a_macro_body_opens_holds_the_declarations_behind_it`] puts the invocation in the **entry point**,
/// and that is the case the reading is built for: an entry point is the file whose closure the index walks, so
/// its own summary is the one the pass is about. This test moves the invocation one header down — `main.cpp`
/// includes `mid.h`, `mid.h` includes `deep.h`, and `deep.h` is where the namespace is opened and the
/// declaration is written.
///
/// Nothing about the question changes: `deep.h` defines `NSB` and invokes it in the same file, so the body is
/// its own and no header can take it away. What changes is *which* reader has to see it:
///
/// ```text
/// the first pass      no includes are indexed yet, so the scope walk has no bodies and files `Deep` at file scope
/// the second pass     re-reads the files whose reading a body could change, and this is where it was wrong
/// ```
///
/// **What it caught.** `build_scopes` was handed the environment of the file's *includes*, and a macro a file
/// writes and invokes **itself** is in no include — so it was invisible to the scope walk, the namespace it
/// opened was lost, and every declaration behind it landed at file scope. Moving the same `#define` into a
/// header the file includes made the test pass, which is what makes this a defect rather than a limitation: the
/// two spellings mean the same thing and only one of them was read.
#[test]
fn a_scope_a_macro_body_opens_is_held_where_the_invocation_is_two_headers_down() {
    use cpp_code_analysis::{CompilerConfig, MemoryFiles, SummaryStore};

    let files = MemoryFiles::new()
        .with_file(
            "/q/deep.h",
            "#pragma once\n#define NSB namespace deepns {\n#define NSE }\nNSB\nstruct Deep { int d; };\nNSE\n",
        )
        .with_file("/q/mid.h", "#pragma once\n#include \"deep.h\"\n")
        .with_file(
            "/q/main.cpp",
            "#include \"mid.h\"\nvoid f() { deepns::Deep d; }\n",
        );

    let root = std::env::temp_dir().join("cppls-macro-scope-deep-tests");
    let _ = std::fs::remove_dir_all(&root);
    std::fs::create_dir_all(&root).expect("the test directory");

    let mut store = SummaryStore::with_provider(&root, CompilerConfig::default(), files);
    store.index_includes_from(std::path::Path::new("/q/main.cpp"), Default::default());

    let summary = store
        .index()
        .summary(std::path::Path::new("/q/deep.h"))
        .expect("deep.h is indexed");
    let deep = summary
        .declarations
        .iter()
        .find(|fact| fact.name == "Deep")
        .unwrap_or_else(|| {
            panic!(
                "the declaration was read: {:?}",
                summary
                    .declarations
                    .iter()
                    .map(|fact| fact.qualified_name())
                    .collect::<Vec<_>>()
            )
        });
    assert_eq!(
        deep.scope.as_deref(),
        Some("deepns"),
        "the file that writes the `#define` and invokes it keeps the scope it opens, however deep it is: {:?}",
        summary
            .declarations
            .iter()
            .map(|fact| fact.qualified_name())
            .collect::<Vec<_>>()
    );
}

/// **A function behind an export macro, in a namespace a macro opened** — the shape `std::format` has.
///
/// [`a_scope_a_macro_body_opens_holds_the_declarations_behind_it`] pins the *class* spelling
/// (`_EXPORT_STD template <…> class vector`), which is what `<vector>` writes and what resolves. This is the
/// same question about a **function**, which is what `<format>` writes:
///
/// ```cpp
/// _STD_BEGIN
/// _EXPORT_STD template <class... _Types>
/// string format(format_string<_Types...> _Fmt, _Types&&... _Args);
/// _STD_END
/// ```
///
/// asked because `std::format` is the one standard-library name a completion probe reports as absent while
/// `std::string` resolves, so the difference between the two spellings is worth pinning rather than assuming.
/// It passes — which is what says the loss is not here: `std::format` is missing from the reading
/// `FileIndexer::index_rendering` builds, and this harness reaches the same text through `FileIndexer::index`.
#[test]
fn a_function_behind_an_export_macro_is_in_the_namespace_the_macro_opened() {
    use cpp_code_analysis::{CompilerConfig, Known, MemoryFiles, SummaryStore};

    let files = MemoryFiles::new()
        .with_file(
            "/q/ns.h",
            "#pragma once\n#define _STD_BEGIN namespace std {\n#define _STD_END }\n\
             #if defined(_BUILD_STD_MODULE)\n#define _EXPORT_STD export\n#else\n#define _EXPORT_STD\n#endif\n",
        )
        .with_file(
            "/q/main.cpp",
            "#include \"ns.h\"\n_STD_BEGIN\n_EXPORT_STD template <class _Ty>\n_Ty format(int _Fmt);\n_STD_END\n",
        );

    let root = std::env::temp_dir().join("cppls-macro-scope-function-tests");
    let _ = std::fs::remove_dir_all(&root);
    std::fs::create_dir_all(&root).expect("the test directory");

    let mut store = SummaryStore::with_provider(&root, CompilerConfig::default(), files);
    store.index_includes_from(std::path::Path::new("/q/main.cpp"), Default::default());

    let summary = store
        .index()
        .summary(std::path::Path::new("/q/main.cpp"))
        .expect("main.cpp is indexed");
    let format = summary
        .declarations
        .iter()
        .find(|fact| fact.name == "format")
        .unwrap_or_else(|| {
            panic!(
                "the function was read: {:?}",
                summary
                    .declarations
                    .iter()
                    .map(|fact| (fact.qualified_name(), fact.kind))
                    .collect::<Vec<_>>()
            )
        });
    assert_eq!(
        format.scope.as_deref(),
        Some("std"),
        "a function is scoped by the namespace the macro opened, exactly as the class beside it is: {:?}",
        summary
            .declarations
            .iter()
            .map(|fact| fact.qualified_name())
            .collect::<Vec<_>>()
    );

    match store
        .index()
        .definition("std::format", std::path::Path::new("/q/main.cpp"))
    {
        Known::Yes(found) => assert_eq!(found.fact.qualified_name(), "std::format"),
        other => {
            panic!("`std::format` must resolve for the same reason `std::vector` does: {other:?}")
        }
    }
}

/// **An inline namespace is transparent to a qualified name; an ordinary one is not.**
///
/// [namespace.def]: "members of an inline namespace can be used in most respects as though they were members of
/// the enclosing namespace". MSVC's `<format>` writes `std::format` between `_FMT_P2286_BEGIN` and
/// `_FMT_P2286_END`, whose body is `inline namespace __p2286 {` — so the declaration is *inside* `__p2286` and
/// its qualified name is nonetheless `std::format`. `std::literals` and libstdc++'s `inline namespace __cxx11`
/// — which holds `std::string` — are the same shape.
///
/// # The four ways the pair can be written
///
/// The macro pair is the shape the standard library uses, and both halves of it matter: whether the pair is
/// **behind a conditional** (MSVC's is, under `#if _HAS_CXX23`) and whether the namespace it opens is
/// **`inline`**. The first run of this test had only the first two fixtures, and the answer it gave — the
/// conditional one passing while the plain one failed — is what said the condition was not the question and the
/// keyword was.
///
/// # What it caught
///
/// `scope_of_a_body` decided "is this a namespace head" by its **first token**, so `inline namespace __p2286 {`
/// was read as `Other` and opened nothing — every declaration between the two invocations landed in the
/// enclosing scope. And the walker's own check for the literal spelling asked the `NamespaceDecl` node's
/// children for an `InlineKeyword`, which can never be there: the parser puts the keyword **beside** the node
/// (`TranslationUnit > [InlineKeyword, NamespaceDecl]`), so a check written that way silently answered `false`
/// for every inline namespace — including the literal one MSVC's rendering contains, which is the path the
/// product actually takes.
///
/// The last fixture is that path, and it is here because the first three did **not** catch it: they reach the
/// scope walk through a macro body, and the rendering reaches it through a parsed `NamespaceDecl`.
#[test]
fn an_inline_namespace_is_transparent_to_a_qualified_name() {
    use cpp_code_analysis::{CompilerConfig, DeclFact, MemoryFiles, SummaryStore};

    // Every fixture declares `Deep` inside the namespace, and every one must reach it as `std::Deep` **when the
    // namespace is inline** — that is the whole question. The two ordinary ones must not.
    let headers = [
        (
            "macro, conditional, inline",
            "#pragma once\n#if 1\n#define NSB inline namespace deepns {\n#define NSE }\n#else\n#define NSB\n#define NSE\n#endif\n",
            "std::Deep",
        ),
        (
            "macro, conditional, plain",
            "#pragma once\n#if 1\n#define NSB namespace deepns {\n#define NSE }\n#else\n#define NSB\n#define NSE\n#endif\n",
            "std::deepns::Deep",
        ),
        (
            "macro, plain, inline",
            "#pragma once\n#define NSB inline namespace deepns {\n#define NSE }\n",
            "std::Deep",
        ),
        (
            "macro, plain, plain",
            "#pragma once\n#define NSB namespace deepns {\n#define NSE }\n",
            "std::deepns::Deep",
        ),
        ("written out, inline", "#pragma once\n", "std::Deep"),
    ];

    // The last fixture spells the namespace instead of using the macro, which is the path a **rendering** takes:
    // MSVC's `<format>` is cooked, so the scope walk sees the text `inline namespace __p2286 {` in a parsed tree
    // rather than a `MacroCall`.
    let sources = [
        "#include \"pair.h\"\nnamespace std {\nNSB\nstruct Deep { int d; };\nNSE\nint after(int);\n}\n",
        "#include \"pair.h\"\nnamespace std {\nNSB\nstruct Deep { int d; };\nNSE\nint after(int);\n}\n",
        "#include \"pair.h\"\nnamespace std {\nNSB\nstruct Deep { int d; };\nNSE\nint after(int);\n}\n",
        "#include \"pair.h\"\nnamespace std {\nNSB\nstruct Deep { int d; };\nNSE\nint after(int);\n}\n",
        "#include \"pair.h\"\nnamespace std {\ninline namespace deepns {\nstruct Deep { int d; };\n}\nint after(int);\n}\n",
    ];

    let mut readings: Vec<(&str, Vec<String>, Vec<String>)> = Vec::new();
    for ((label, header, _), source) in headers.into_iter().zip(sources) {
        let files = MemoryFiles::new()
            .with_file("/q/pair.h", header)
            .with_file("/q/main.cpp", source);

        let root = std::env::temp_dir().join(format!(
            "cppls-inline-namespace-{}",
            label.replace(' ', "-")
        ));
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(&root).expect("the test directory");

        let mut store = SummaryStore::with_provider(&root, CompilerConfig::default(), files);
        store.index_includes_from(std::path::Path::new("/q/main.cpp"), Default::default());

        let summary = store
            .index()
            .summary(std::path::Path::new("/q/main.cpp"))
            .expect("main.cpp is indexed");
        let names = |want: &str| -> Vec<String> {
            summary
                .declarations
                .iter()
                .filter(|fact| fact.name == want)
                .map(DeclFact::qualified_name)
                .collect()
        };
        readings.push((label, names("Deep"), names("after")));
    }

    // **Every fixture is read before anything is asserted**, because the reading that matters is the *pattern*
    // across them: which single word changes the answer.
    for ((label, _, expected), (_, deep, after)) in headers.iter().zip(&readings) {
        assert_eq!(
            after,
            &vec!["std::after".to_string()],
            "({label}) the declaration after the closer is in `std`"
        );
        assert_eq!(
            deep,
            &vec![expected.to_string()],
            "({label}) an inline namespace's members are the enclosing namespace's members, and an ordinary \
             namespace's are its own. All five readings: {readings:?}"
        );
    }
}

/// **A member spelled through an alias resolves through it, and nothing else starts resolving.**
///
/// `size_type` is a member of `basic_string`, so the qualified name the index holds is
/// `std::basic_string::size_type`. `std::string` is a `using` declaration for `basic_string<char>`, so
/// `std::string::size_type` is a **second question** — resolve the alias, then the member — and before this it
/// answered `NotDeclaredHere` while the declaration was right there.
///
/// Measured as a pair on MSVC's library, which is what said the missing half was the alias rather than member
/// resolution:
///
/// ```text
/// std::basic_string::size_type   -> Yes              member resolution works
/// std::string::size_type         -> NotDeclaredHere  the alias is what did not
/// ```
///
/// The second half of the test is the one that matters as much: a fallback that rewrote a name it could not
/// resolve into *some* member would be inventing a declaration, and `not_a_member` is here to say it does not.
#[test]
fn a_member_of_an_aliased_class_resolves_through_the_alias() {
    use cpp_code_analysis::{CompilerConfig, Known, MemoryFiles, SummaryStore};

    let files = MemoryFiles::new().with_file(
        "/q/main.cpp",
        "namespace std {\n\
         template <class _Ty> struct basic_string { using size_type = unsigned long long; };\n\
         using string = basic_string<char>;\n\
         }\n\
         std::basic_string<char>::size_type a;\n\
         std::string::size_type b;\n",
    );

    let root = std::env::temp_dir().join("cppls-alias-member-tests");
    let _ = std::fs::remove_dir_all(&root);
    std::fs::create_dir_all(&root).expect("the test directory");

    let mut store = SummaryStore::with_provider(&root, CompilerConfig::default(), files);
    store.index_includes_from(std::path::Path::new("/q/main.cpp"), Default::default());

    let index = store.index();
    let main = std::path::Path::new("/q/main.cpp");

    // The member as its own class spells it — the case that already worked, kept here so that a change to the
    // fallback cannot break it quietly.
    assert!(
        matches!(
            index.definition("std::basic_string::size_type", main),
            Known::Yes(_)
        ),
        "the member under the class that declares it resolves: {:?}",
        index.definition("std::basic_string::size_type", main)
    );

    match index.definition("std::string::size_type", main) {
        Known::Yes(found) => assert_eq!(found.fact.name, "size_type"),
        other => panic!("a member spelled through an alias must resolve through it: {other:?}"),
    }

    // …and the alias does not turn a name nobody declares into one. `std::string` is an alias for
    // `basic_string<char>`, which has no member by this name, so the answer is still that it is nowhere.
    assert!(
        matches!(
            index.definition("std::string::not_a_member", main),
            Known::Unknown(_)
        ),
        "the fallback rewrites a name, it does not invent a declaration: {:?}",
        index.definition("std::string::not_a_member", main)
    );
}

/// **A word in a macro's body that expands to nothing is not a word** — the shape MSVC's `_STD_BEGIN` really has.
///
/// The failure this pins was the whole of `std::format`. Measured on MSVC 14.51's `yvals_core.h`, the body of
/// `_STD_BEGIN` is a word and a namespace head:
///
/// ```text
/// #define _STD_BEGIN   \
///     _EXTERN_CXX_WORKAROUND \
///     namespace std {
/// ```
///
/// and `_EXTERN_CXX_WORKAROUND` is `extern "C++" {` in one arm of its `#if` and **nothing at all** in the other.
/// With the empty arm in force, `_STD_BEGIN`'s first token is an identifier with an empty replacement list, the
/// shape reader stopped there, no scope was opened — and all 1054 declarations of `<format>` were filed at **file
/// scope**, which is why `std::format` could not be found while `std::string` could.
///
/// # Why this is asked of the walker rather than of the store
///
/// Because the walker is where the reading is: [`build_scopes`] is handed the environment, and this is the question
/// it asks of it. The store's second pass has a **separate** gate — "which files' readings could have changed" —
/// which answers from the macro *facts* alone and can only see a body the plain reader can place; a test written
/// against the store would be measuring that gate instead. Both halves are real, and this test is about the first.
///
/// Three details are copied from the real header rather than invented, and each is load-bearing: the body is
/// written with **line continuations** (which is why the shape reader lexes it rather than pattern-matching it);
/// the empty word's body is **whitespace** rather than an empty string — the continuation that ends a `#define`
/// line belongs to the line, not to the body; and the empty word is defined in the environment the body is read
/// in, which is what a header's own closure gives it.
#[test]
fn a_word_in_a_body_that_expands_to_nothing_does_not_stop_the_reading() {
    use cpp_code_analysis::{MacroBodies, build_scopes};
    use cpp_parser::{CppParser, IncludedMacro, MacroEnvironment, ParserConfig};

    // The bodies verbatim: `_STD_BEGIN`'s is the real continuation and the real namespace head, and
    // `_EXTERN_CXX_WORKAROUND`'s is what the arm that says nothing produces.
    const STD_BEGIN: &str = "   \\\n    _EXTERN_CXX_WORKAROUND \\\n    namespace std {\n";
    const NOTHING: &str = "   \n";
    const STD_END: &str = "   \\\n    _END_EXTERN_CXX_WORKAROUND \\\n    }\n";

    let word = |name: &str, body: &str| IncludedMacro {
        name: name.into(),
        from_offset: 0,
        definition: None,
        body_text: Some(body.into()),
        parameters: None,
    };

    let environment = MacroEnvironment::from_included_macros([
        word("_STD_BEGIN", STD_BEGIN),
        word("_STD_END", STD_END),
        word("_EXTERN_CXX_WORKAROUND", NOTHING),
        word("_END_EXTERN_CXX_WORKAROUND", NOTHING),
    ]);

    // The premise, asserted separately: the word really is a macro with an empty body, so a failure below is about
    // the shape reader rather than about the fixture.
    assert!(
        MacroBodies::body_at(&environment, "_EXTERN_CXX_WORKAROUND", 0)
            .is_some_and(|body| body.trim().is_empty()),
        "the fixture's empty word must answer an empty body"
    );
    assert_eq!(
        cpp_parser::shape_of_a_body(STD_BEGIN),
        cpp_parser::BodyShape::Other,
        "…and without the environment the shape is unreadable, which is the state the bug was found in"
    );

    const FORMAT: &str = "\
_STD_BEGIN
_EXPORT_STD template <class... _Types>
_NODISCARD string format(const format_string<_Types...> _Fmt, _Types&&... _Args) {
    return {};
}
_STD_END
int at_file_scope;
";

    let tree = CppParser::parse(FORMAT, ParserConfig::default());
    let scopes = build_scopes(&tree.get_red_root(), &environment);

    let readings: Vec<(&str, Option<Vec<String>>)> = scopes
        .macro_readings
        .iter()
        .map(|reading| (reading.name.as_str(), reading.opens.clone()))
        .collect();
    assert_eq!(
        readings,
        vec![
            ("_STD_BEGIN", Some(vec!["std".to_string()])),
            ("_STD_END", None),
        ],
        "the two invocations are read **through** the empty word between their own names and the braces"
    );

    // …and the declarations are in the scope the body opened, which is what makes `std::format` a name.
    let scope_of = |wanted: &str| {
        cpp_code_analysis::ScopeId(
            scopes
                .scopes()
                .iter()
                .position(|scope| {
                    scope
                        .bindings
                        .iter()
                        .any(|binding| binding.name.text() == wanted)
                })
                .unwrap_or_else(|| panic!("`{wanted}` was not declared at all")),
        )
    };

    assert_eq!(
        scopes
            .qualification_prefix_of(scope_of("format"))
            .unwrap_or_default(),
        "std",
        "`format` is a member of `std`"
    );
    assert_ne!(
        scope_of("at_file_scope"),
        scope_of("format"),
        "and the declaration after `_STD_END` is back at file scope, so the closer was read too"
    );
}

// ============================================================================
// Malformed input
// ============================================================================

/// A file that does not parse still produces a table, with whatever was readable in it.
///
/// This layer runs while a file is being typed, so a construct the parser recovered from must not cost the
/// declarations around it.
#[test]
fn a_recovered_parse_still_declares_what_it_can() {
    let tree = CppParser::parse(
        "int before;\nstruct { ; \nint after;\n",
        ParserConfig::default(),
    );
    let table = build_scopes(&tree.get_red_root(), &cpp_code_analysis::NoMacroBodies);

    // The parse is recovered, not clean — and the point is that the table is still built.
    assert_eq!(
        tree.to_source_text(),
        "int before;\nstruct { ; \nint after;\n"
    );

    let names: Vec<String> = table
        .scope(table.root().unwrap())
        .unwrap()
        .bindings
        .iter()
        .map(|binding| binding.name.text())
        .collect();

    assert!(
        names.contains(&"before".to_string()),
        "the declarations before the damage are read: {names:?}"
    );
}

/// An anonymous namespace binds no name, and still opens a scope.
///
/// Both halves matter: binding an invented name would put a name in scope that cannot be used, and skipping the
/// scope would put the namespace's contents in the file scope, where they are not.
#[test]
fn an_anonymous_namespace_opens_a_scope_without_binding_a_name() {
    let table = scopes("namespace { int hidden; }\n");

    assert_eq!(shape(&table), "File(Ns{hidden})");
}

/// An unnamed parameter declares nothing, and does not disturb the ones that are named.
#[test]
fn an_unnamed_parameter_declares_nothing() {
    let table = scopes("void f(int, double named) {}\n");

    assert_eq!(shape(&table), "File{f}(Fn{named})");
}

/// A structured binding binds every name in the pattern.
#[test]
fn a_structured_binding_binds_each_name() {
    let table = scopes("void f() { auto [first, second] = pair; }\n");

    assert_eq!(shape(&table), "File{f}(Fn{first,second})");

    let function = table.scope(table.root().unwrap()).unwrap().children[0];
    assert_eq!(
        kind_of(&table, function, "first"),
        Some(BindingKind::Variable)
    );
    assert_eq!(
        kind_of(&table, function, "second"),
        Some(BindingKind::Variable)
    );
}

/// Whatever the input, building scopes terminates without panicking.
///
/// An editor builds this on every keystroke, including while the file is half-typed, so a construct the parser
/// recovered from must not take the process down.
#[test]
fn building_scopes_never_panics() {
    let sources = [
        "",
        ";",
        "{",
        "}",
        "namespace",
        "namespace {",
        "class",
        "class {",
        "template <",
        "template <typename> ",
        "void f(",
        "void f() {",
        "enum {",
        "using",
        "typedef",
        "struct A : B {",
        "int ns::",
        "auto [a, = x;",
        "[[nodiscard]]",
        "void f(int a = {1, 2}) {}",
        "class A { class B { class C { int x; }; }; };",
        "void f() { for (;;) { while (1) { if (x) { } } } }",
    ];

    for source in sources {
        let tree = CppParser::parse(source, ParserConfig::default());
        assert_eq!(
            tree.to_source_text(),
            source,
            "losslessness must hold even here: {source:?}"
        );

        let table = build_scopes(&tree.get_red_root(), &cpp_code_analysis::NoMacroBodies);

        // Touch the queries, so the closure is part of what is tested rather than elided.
        if let Some(root) = table.root() {
            for offset in 0..source.len().min(64) {
                if let Some(scope) = table.scope_at(offset) {
                    let _ = table.scope_chain(scope);
                    let _ = table.scope(scope).map(|scope| scope.declared_names());
                }
            }
            let _ = table.scope_chain(root);
        }
    }
}

/// The scope covering an offset is the innermost declaration it sits in, on a real file.
///
/// The end-to-end version of the unit test in the symbol layer: a cursor inside a member function's body is in
/// that function's scope and not in the class's.
///
/// Note where the offsets point. A syntax node's range starts at its *first token*, so the class scope begins at
/// the `class` keyword — a cursor on the keyword itself is already inside the class, because that is where the
/// node starts. What is *not* inside is the enclosing file's view of the name, which is a different question
/// from where the node's text is.
#[test]
fn the_scope_at_an_offset_is_the_innermost_on_a_real_file() {
    let source = "class Widget {\n  void size() {\n    int local = 0;\n  }\n};\n";
    let table = scopes(source);

    let keyword_offset = source.find("class").unwrap();
    let body_offset = source.find('{').unwrap() + 1;
    let method_offset = source.find("void size").unwrap() + 5;
    let local_offset = source.find("int local").unwrap() + 5;

    let at = |offset: usize| {
        let scope = table.scope_at(offset).expect("a scope");
        table.scope(scope).unwrap().kind
    };

    assert_eq!(
        at(keyword_offset),
        ScopeKind::Class,
        "the class node starts at its keyword"
    );
    assert_eq!(at(body_offset), ScopeKind::Class, "just inside the body");
    assert_eq!(at(method_offset), ScopeKind::Function, "inside the method");
    assert_eq!(
        at(local_offset),
        ScopeKind::Function,
        "inside the method body"
    );
    assert_eq!(at(method_offset), ScopeKind::Function, "inside the method");
    assert_eq!(
        at(local_offset),
        ScopeKind::Function,
        "inside the method body"
    );
}

/// The bindings a scope reports are only the ones written in it, not the ones in its children.
///
/// A consumer resolving a name walks outward itself, so a scope that included its children's names would make
/// every lookup find things that shadow nothing and are not visible.
#[test]
fn a_scope_reports_only_its_own_bindings() {
    let table = scopes("namespace ns { int inner; }\nint outer;\n");
    let file = table.root().unwrap();

    let names: Vec<String> = table
        .scope(file)
        .unwrap()
        .declared_names()
        .iter()
        .map(|name| name.text())
        .collect();

    assert_eq!(names, vec!["ns", "outer"], "not `inner`");
}

/// The name range is the identifier's, not the whole declarator's.
///
/// The difference between a rename that edits one identifier and one that eats the initialiser, so it is
/// asserted on the source text rather than on the numbers.
#[test]
fn a_bindings_name_range_covers_just_the_name() {
    let source = "int counter = 42;\n";
    let table = scopes(source);
    let file = table.root().unwrap();

    let binding = &table.scope(file).unwrap().bindings[0];

    let slice = |range: cpp_parser::SourceRange| &source[range.start_offset..range.end_offset()];

    assert_eq!(slice(binding.name_range), "counter");
    assert!(
        binding.name_range.length < binding.range.length,
        "the name is a part of the declaration, not the whole of it"
    );
}

/// **A binding records its declarator**, which is the layer's contract rather than a display choice.
///
/// `"counter = 42"` and not `"int counter = 42;"`, and the reason is worth keeping written down because a reader
/// will meet it from the other side: an editor's outline wants the whole declaration, and the first attempt at
/// giving it that widened *this* — which broke `auto` deduction in two suites, because a fact's range text is where
/// the operators of a deduced type are read from and its start is how a declaration finds the template parameters
/// in scope. Measured: `const auto& r = base` came back as `const int`.
///
/// So the widening lives in the handler that presents symbols
/// (`cpp_ls::handlers::document_symbol::declaration_range`) and this stays the declarator. The two are different
/// questions and the test that says so is this one, beside
/// `the_declaration_range_is_the_whole_declaration_when_it_is_that_names` in the handler.
#[test]
fn a_bindings_range_is_its_declarator() {
    let source = "int counter = 42;\n";
    let table = scopes(source);
    let file = table.root().unwrap();

    let binding = &table.scope(file).unwrap().bindings[0];

    let slice = |range: cpp_parser::SourceRange| &source[range.start_offset..range.end_offset()];

    assert_eq!(slice(binding.name_range), "counter");
    assert_eq!(slice(binding.range), "counter = 42");
    assert!(
        binding.name_range.length < binding.range.length,
        "the name is a part of the declarator, not the whole of it"
    );
}

/// **And two declarators keep their own**, which is the case the rule above must not swallow.
///
/// `int a, b;` declares two names under one type, so the type belongs to neither of them alone: attributing
/// `int a, b;` to both would make a rename or a highlight of one edit the other.
#[test]
fn a_shared_declaration_is_not_attributed_to_one_name() {
    let source = "int a = 1, b = 2;\n";
    let table = scopes(source);
    let file = table.root().unwrap();

    let slice = |range: cpp_parser::SourceRange| &source[range.start_offset..range.end_offset()];

    let named = |name: &str| {
        table
            .scope(file)
            .unwrap()
            .bindings
            .iter()
            .find(|binding| binding.name.text() == name)
            .unwrap_or_else(|| panic!("`{name}` is declared here"))
            .range
    };

    assert_eq!(slice(named("a")), "a = 1");
    assert_eq!(slice(named("b")), "b = 2");
}

// ---------------------------------------------------------------------------------------------
// Qualified names
//
// A scope records the name it introduces, which is the only way `ns::C::f` can be produced: the *binding* of
// `f` says `f` is in the class scope, and the class scope is the only thing that knows it is called `C`.
// ---------------------------------------------------------------------------------------------

/// The name a scope introduces is what makes a qualified name reachable, segment by segment.
#[test]
fn a_scope_records_the_name_it_introduces() {
    let table = scopes("namespace ns { struct C { int member; }; }\n");

    assert_eq!(
        qualified_of(&table, ScopeKind::Namespace, Some("ns")).as_deref(),
        Some("ns")
    );
    assert_eq!(
        qualified_of(&table, ScopeKind::Class, Some("C")).as_deref(),
        Some("ns::C"),
        "the class's qualified name includes the namespace it was written in"
    );
}

/// A nested `namespace a::b` and the spelled-out form are the same thing, and must produce the same name.
///
/// The two are one construct in C++11 and later, and a consumer that stored only the *written* spelling would
/// answer differently for them — which is the kind of difference that only shows up in a rename.
#[test]
fn a_nested_namespace_spelling_is_the_same_name() {
    let compact = scopes("namespace a::b { struct C { int member; }; }\n");
    let spelled = scopes("namespace a { namespace b { struct C { int member; }; } }\n");

    for table in [&compact, &spelled] {
        assert_eq!(
            qualified_of(table, ScopeKind::Class, Some("C")).as_deref(),
            Some("a::b::C"),
            "both spellings name the same class"
        );
    }
}

/// A scope that introduces no name contributes nothing, and stops nothing.
///
/// This is what makes `void ns::f() {` and `void f() {` agree: the function body is transparent either way,
/// and only the namespace the function was written in is part of the answer. Getting this wrong would give
/// `ns::f`'s locals the qualified name `ns::f::local`, which is not a name anything can be referred to by.
#[test]
fn an_unnamed_scope_is_transparent() {
    let table = scopes("namespace ns { void f() { int local = 0; } }\n");

    let function = table
        .scopes()
        .iter()
        .position(|scope| scope.kind == ScopeKind::Function)
        .expect("the function body has a scope");
    let function = cpp_code_analysis::ScopeId(function);

    assert_eq!(
        table.qualified_name_of(function).as_deref(),
        Some("ns"),
        "the function body contributes no segment but does not cut the namespace off"
    );
    assert_eq!(
        table.scope(function).expect("the scope").name,
        None,
        "and it really is unnamed rather than named `f`"
    );
}

/// **An unnamed class takes the name of the variable it declares**, which is the only key its members can have.
///
/// ```c
/// namespace ns { struct { int member; } value; }
/// ```
///
/// This used to assert a dead end — "`ns::member` is not a name, and neither is `member`" — and that was true while
/// nothing could reach such a class: its members were filed in a scope with no name, so a member question about `value`
/// had nowhere to look. `struct { … } bits;` is how C declares a type it never names, and the declarator is the only
/// spelling in the declaration that can serve as a key, so the scope takes it — and `sema::types` keys the variable's
/// type by the same name, which is what makes `bits.three` answerable. See
/// `an_unnamed_struct_type_is_keyed_by_the_variable_it_declares` in `tests/types.rs`.
#[test]
fn an_unnamed_class_takes_the_name_of_the_variable_it_declares() {
    let table = scopes("namespace ns { struct { int member; } value; }\n");

    let class = table
        .scopes()
        .iter()
        .position(|scope| scope.kind == ScopeKind::Class)
        .expect("the class body has a scope");

    assert_eq!(
        table.qualified_name_of(cpp_code_analysis::ScopeId(class)),
        Some("ns::value".to_string()),
        "the declarator's name is the segment, under the namespace it was written in"
    );
}

/// A member's qualified name comes from its class scope, not from the binding it sits beside.
#[test]
fn a_member_is_found_under_its_class() {
    let table = scopes("namespace ns { struct C { void method(); int field; }; }\n");

    let class = table
        .scopes()
        .iter()
        .position(|scope| scope.kind == ScopeKind::Class)
        .expect("the class body has a scope");
    let class = cpp_code_analysis::ScopeId(class);

    let members: Vec<String> = table
        .scope(class)
        .expect("the scope")
        .bindings
        .iter()
        .map(|binding| {
            format!(
                "{}::{}",
                table.qualified_name_of(class).expect("the class is named"),
                binding.name.text()
            )
        })
        .collect();

    assert_eq!(members, ["ns::C::field", "ns::C::method"]);
}

/// A scope with no name of its own has no qualified name, rather than an empty one.
///
/// The distinction matters to a consumer: `Some("")` would be a name that matches nothing while looking like
/// an answer, where `None` says "there is no qualified name here".
#[test]
fn the_file_scope_has_no_qualified_name() {
    let table = scopes("int x;\n");

    let root = table.root().expect("a non-empty file has a file scope");
    assert_eq!(table.scope(root).expect("the scope").name, None);
    assert_eq!(table.qualified_name_of(root), None);
}

/// **A linkage specification declares what it covers**, in the scope it was written in.
///
/// Both spellings are one construct (`parse_linkage_specification`): a `Declaration` whose specifiers say
/// `extern "C"`/`extern "C++"` and whose *child* is what the linkage applies to — a nested declaration, or a
/// block. Neither declares a name of its own, and neither is a scope: a linkage is a property of the
/// declarations inside, and their names belong to the enclosing namespace.
///
/// This is MSVC's shape for the whole iostream hierarchy —
/// `_EXPORT_STD extern "C++" template <class _Elem, class _Traits> class basic_istream : … { … };` — and while
/// the walk stopped at the unnamed outer declaration, `<istream>`'s first indexed fact was at line **715** of
/// 935 with `class basic_istream` at line 24: no class, no members, and nothing inheriting from them.
#[test]
fn a_linkage_specification_declares_what_it_covers() {
    let source = "\
namespace std {
extern \"C++\" template <class _Elem, class _Traits>
class basic_istream {
public:
    void read(int n);
    int member;
};
extern \"C\" { void c_function(int); }
}
";
    let table = scopes(source);

    assert_eq!(
        shape(&table),
        // `basic_istream` and `c_function` are both names of `std` — the class from the nested declaration, the C
        // function from the block — and `_Elem`/`_Traits` are in a parameter scope **inside** `std` while the
        // class's own name is not: the template's parameters are visible in the class and the class is visible
        // outside it.
        "File{std}(Ns{basic_istream,c_function}(Params{_Elem,_Traits}(Class{member,read}(Fn{n})) Fn))",
        "the class and the C function are both declared, in `std`"
    );
}

/// …and an ordinary `extern` variable is still a declaration: the **string literal** is the difference.
///
/// `extern Widget global;` carries the same `ExternSpec` node as `extern "C"`, and reading the keyword as the
/// whole test stopped it being declared at all — measured, this fixture's name disappearing from the file.
#[test]
fn an_extern_variable_is_a_declaration() {
    let table = scopes("struct Widget { int size; };\nextern Widget global;\n");

    assert_eq!(shape(&table), "File{Widget,global}(Class{size})");
}

/// **A local whose type is a qualified name is a local**, and it is bound in the body it was written in.
///
/// The shape is what every real file starts with — `std::size_t length = 0;` — and the question is whether the
/// *declarator* is read or the qualified type swallows it. Measured on a user's file, `length` was the one local of
/// nine unresolved names: every other name in that body resolved, so this is not "locals do not work" but one
/// spelling of one declaration.
#[test]
fn a_local_declared_with_a_qualified_type_is_bound() {
    let table = scopes(
        "namespace std { using size_t = unsigned long; }\n\
         void f() {\n\
         \x20   std::size_t length = 0;\n\
         \x20   std::string line;\n\
         }\n",
    );

    let body = shape(&table);
    assert!(
        body.contains("length"),
        "the declaration is the declarator's, wherever its type came from: {body}"
    );
    assert!(body.contains("line"), "and so is the next one: {body}");
}

/// **一个 operator 声明是有名字的声明** —— 它没有标识符(`operator*` 是关键字加一个记号),
/// 但它仍然在类的作用域里绑一个名字,否则"类的 operator 是不是成员"这个问题的答案永远是"不是"。
#[test]
fn operators_bind_a_name() {
    let table = scopes("struct M { int operator*() const; int operator[](int at); int cents; };\n");
    let shape = shape(&table);

    assert!(shape.contains("operator*"), "{shape}");
    assert!(shape.contains("operator[]"), "{shape}");
    assert!(shape.contains("cents"), "{shape}");
}
/// **A local whose extent is a macro is still a local.**
///
/// Reported from a rename: `int more[MAX_ITEMS];` is a fact in the index, and `local_references_of` — the per-file
/// analysis that rename and highlight use for locals — has **no entry for it**. A rename then refuses the name (the
/// safe direction), but a reader with the cursor on it gets nothing highlighted, and the question "where else is this
/// local" goes unanswered.
///
/// The two spellings below are the same declaration with and without the macro, so that the macro is the only
/// difference the assertion can see.
#[test]
fn a_local_whose_extent_is_a_macro_is_placed() {
    use cpp_code_analysis::sema::declarations::local_references_of;

    for source in [
        "void f() {\n    int more[4];\n    (void)more;\n}\n",
        "#define N 4\nvoid f() {\n    int more[N];\n    (void)more;\n}\n",
    ] {
        let tree = CppParser::parse(source, ParserConfig::default());
        let root = tree.get_red_root();
        let table = build_scopes(&root, &cpp_code_analysis::NoMacroBodies);
        let locals = local_references_of(&table, &root);
        println!("{source:?} → {locals:?}");
        assert!(
            locals.iter().any(|entry| {
                source[entry.declared_at as usize..].starts_with("more") && !entry.uses.is_empty()
            }),
            "`more` is a local, declared at one place and used at another: {locals:?}"
        );
    }
}
/// **A member after a nested class that closes inside a conditional region is still a member of the outer class.**
///
/// Found on libstdc++'s `<bits/basic_string.h>`: every member of `std::basic_string` after `struct _Alloc_hider` is
/// filed under the **nested** class — 1134 facts, and `members_of("std::basic_string")` answered the 27 typedefs
/// declared before it and none of the functions (`size`, `erase`, …). The nested class is declared like this:
///
/// ```cpp
/// struct _Alloc_hider : allocator_type
/// {
///     _Alloc_hider(pointer __dat, const _Alloc& __a = _Alloc()) : … { }
///     pointer _M_p;
/// };
/// ```
///
/// so `#if` regions *inside* a class body are the shape to test: the closing `};` of a nested class must end it,
/// whatever conditional regions it contains.
#[test]
fn a_nested_class_ends_where_its_brace_ends() {
    for source in [
        "class C { struct Inner : Base { int x; }; int size() const; };\n",
        "class C {\n#if __cplusplus < 201103L\n    int old();\n#else\n    struct Inner : Base { int x; };\n#endif\n    int size() const;\n};\n",
        "class C {\n    struct Inner : Base {\n#if 1\n        Inner() : Base() { }\n#endif\n        int x;\n    };\n    int size() const;\n};\n",
        "class C {\n    struct Inner : Base { Inner() : Base() { }\n#if 1\n        int y;\n#endif\n    };\n    int size() const;\n};\n",
        // Bisection: which part of the shape loses the closing brace?
        "class C {\n    struct Inner : Base // note\n    {\n        int y;\n    };\n    int size() const;\n};\n",
        "class C {\n    struct Inner : Base\n    {\n#if A\n        Inner(p a)\n        : Base(a), _M_p(a) { }\n#else\n        Inner(p a)\n        : Base(a), _M_p(a) { }\n#endif\n        int y;\n    };\n    int size() const;\n};\n",
        "class C {\n    struct Inner : Base\n    {\n#if A\n        Inner(p a) : Base(a), _M_p(a) { }\n#endif\n        int y;\n    };\n    int size() const;\n};\n",
        "class C {\n    struct Inner : Base\n    {\n        Inner(p a) : Base(a), _M_p(a) { }\n        int y;\n    };\n    int size() const;\n};\n",
        // Deeper bisection: two constructors in one branch, default arguments, `std::move`.
        "class C {\n    struct Inner : Base\n    {\n#if A\n        Inner(p a)\n        : Base(a), _M_p(a) { }\n#else\n        Inner(p a)\n        : Base(a), _M_p(a) { }\n\n        Inner(p a)\n        : Base(std::move(a)), _M_p(a) { }\n#endif\n        int y;\n    };\n    int size() const;\n};\n",
        "class C {\n    struct Inner : Base\n    {\n        Inner(p a)\n        : Base(a), _M_p(a) { }\n        Inner(p a)\n        : Base(std::move(a)), _M_p(a) { }\n        int y;\n    };\n    int size() const;\n};\n",
        "class C {\n    struct Inner : Base\n    {\n        Inner(p a)\n        : Base(a) { }\n        Inner(p a)\n        : Base(a) { }\n        int y;\n    };\n    int size() const;\n};\n",
        "class C {\n    struct Inner : Base\n    {\n        Inner(p a) : Base(a) { }\n        Inner(p a) : Base(a) { }\n        int y;\n    };\n    int size() const;\n};\n",
        // **The libstdc++ shape, verbatim** — a base with a trailing comment, both branches of a conditional holding
        // constructors with member-initializer lists, and a macro before them.
        "class C {\n    struct Inner : Base // TODO check __is_final\n    {\n#if __cplusplus < 201103L\n\tInner(pointer __dat, const Alloc& __a = Alloc())\n\t: Base(__a), _M_p(__dat) { }\n#else\n\tCONSTEXPR\n\tInner(pointer __dat, const Alloc& __a)\n\t: Base(__a), _M_p(__dat) { }\n\n\tCONSTEXPR\n\tInner(pointer __dat, Alloc&& __a = Alloc())\n\t: Base(std::move(__a)), _M_p(__dat) { }\n#endif\n\n\tpointer _M_p; // The actual data.\n    };\n    int size() const;\n};\n",
    ] {
        let tree = CppParser::parse(source, ParserConfig::default());
        let table = build_scopes(&tree.get_red_root(), &cpp_code_analysis::NoMacroBodies);
        let shape = shape(&table);
        println!("{source}\n→ {shape}\n");
        let size_scope = table.scopes().iter().find(|scope| {
            scope
                .bindings
                .iter()
                .any(|binding| binding.name.text() == "size")
        });
        assert_eq!(
            size_scope
                .and_then(|scope| scope.name.as_ref())
                .map(|name| name.to_string()),
            Some("C".to_string()),
            "`size` is a member of `C`, whatever the nested class does: {shape}"
        );
    }
}
/// **A lambda is a scope, and a lambda written in an initialiser is written inside the declarator.**
///
/// `auto show = [](double a) { if (const auto inner = f(1, 2)) { g(inner); } };` parses as
/// `InitDeclarator(Declarator(… LambdaExpr …))` — the lambda is a **child of the declarator** — and no walk reached
/// it: `ScopeKind::Lambda` existed with no constructor, and `declarator_as` reads a declarator for its name and
/// parameters without walking its children. So every declaration in a lambda body was absent from the scope tree and
/// therefore from the index. Reported from an editor: `if (const auto result = safe_divide(a, b))` written inside
/// `auto show_division = [](double a, double b) { … };` had no hover, no completion and no deduced type.
///
/// Measured on this fixture before the fix: four facts (`f`, `g`, `h`, `show`) where the same body as a free
/// function filed five — the missing one was the body's own `inner`; the lambda's own parameter `a` was missing too.
#[test]
fn a_lambda_body_is_its_own_scope() {
    let source = "int f(int, int);\nvoid g(int);\nvoid h() {\n    auto show = [](double a) { if (int inner = 1) { g(inner); } };\n}\n";
    let table = scopes(source);
    let shape = shape(&table);
    println!("{shape}");

    let lambda = table
        .scopes()
        .iter()
        .position(|scope| scope.kind == ScopeKind::Lambda)
        .expect("a lambda scope");
    assert!(
        kind_of(&table, cpp_code_analysis::ScopeId(lambda), "a").is_some(),
        "the lambda's parameter is bound in its own scope: {shape}"
    );
    assert!(
        shape.contains("inner"),
        "and a declaration in its body is a declaration: {shape}"
    );
}

/// **A lambda written directly in a body** — the other place `item()` has to know about one.
#[test]
fn a_lambda_inside_a_statement_is_a_scope_too() {
    let source = "void g(int);\nvoid h() {\n    auto show = [](double a) { g(1); };\n}\n";
    let table = scopes(source);
    let shape = shape(&table);
    println!("{shape}");
    assert!(
        table
            .scopes()
            .iter()
            .any(|scope| scope.kind == ScopeKind::Lambda),
        "the lambda declares a scope of its own: {shape}"
    );
}

/// **A call statement whose callee is qualified binds nothing** — the most-vexing-parse shape, at file scope.
///
/// `std::iter_swap(__result, __b);` parses as a `Declaration`: the specifier is `std::iter_swap` and the declarator
/// is the parameter list `(__result, __b)`. Inside a body that went through the branch written for out-of-line
/// definitions (`size_t LuaSource::GetLine(…) { … }` — a qualified name and no declarator name), which **bound the
/// function**: libstdc++'s `bits/stl_algo.h` alone produced 22 `std::iter_swap` facts at namespace scope, kind
/// `Function`, `local: false`, carrying the enclosing template's parameters.
///
/// A definition cannot nest inside a body, so that is the test. The `namespace std { }` in the fixture is what makes
/// the case the interesting one: the qualified name *does* name a scope this file has, so the "binds nothing here"
/// rule did not apply.
#[test]
fn a_call_to_a_qualified_name_in_a_body_binds_nothing() {
    let source = "namespace std { }\nvoid f() {\n    std::iter_swap(a, b);\n}\n";
    let table = scopes(source);
    let shape = shape(&table);
    println!("{shape}");
    assert!(
        !shape.contains("iter_swap"),
        "the call is not a declaration of anything: {shape}"
    );
}

/// **A `friend` function defined inside a class binds its own parameters and body.**
///
/// The `friend` keyword wraps the declaration it qualifies — `FriendDecl { Declaration { InitDeclarator … } }` — and
/// that shape used to be skipped whole: no function scope, no parameter bindings, and `left`/`right` in an inline
/// `operator==` read as undeclared (four findings on `classes.cpp` of the C++ corpus). The friend's *name* still
/// declares nothing in the class — that is what `is_friend` keeps out — but its parameters are its own.
#[test]
fn a_friend_definition_binds_its_parameters() {
    let source = "\
struct S {
    int x;
    friend bool operator==(S const& left, S const& right) { return left.x == right.x; }
};
";
    let table = scopes(source);
    let shape = shape(&table);
    println!("{shape}");
    assert!(
        shape.contains("left,right"),
        "the friend function's parameters are bound in a scope of its own: {shape}"
    );
    assert!(
        shape.contains("Class{x}"),
        "the class's own member list is unchanged: {shape}"
    );
}

/// **A `catch` handler's variable is a declaration**, visible in the handler and not outside it.
#[test]
fn a_catch_handlers_variable_is_bound() {
    let source = "\
void f() {
    try { } catch (int const& again) { (void)again; }
}
";
    let table = scopes(source);
    let shape = shape(&table);
    println!("{shape}");
    assert!(
        shape.contains("again"),
        "the handler's variable is bound: {shape}"
    );
}