cpp_code_analysis 0.4.0

The analysis layer of cpp_ls: the preprocessor, symbol scopes, type inference and the semantic checks.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
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
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
//! Building a file's scopes and bindings from its syntax tree.
//!
//! This is the step that turns the syntax into something a name can be looked up in, and it stays **inside one
//! file**: nothing here reads an `#include`, another file, or the project. That is not a limitation but the
//! point — completion at a cursor needs this file's scopes and nothing else, so a step that reached further
//! would make every keystroke cost the whole project. Crossing a file boundary is the include graph's job, and
//! it happens at a different layer.
//!
//! # What the syntax can and cannot say
//!
//! Every binding here is derived from the **shape** of a declaration. `class Widget` binds a
//! [`BindingKind::Class`] because a class definition was written, not because anything was resolved. There are
//! no types at this layer, so `auto x = f();` binds a variable whose type is not known, and that is the honest
//! result rather than a failure.
//!
//! Two consequences are worth stating because they look like omissions and are not:
//!
//! * **A reference is not recorded.** `f()` inside a body is not a binding; only what a declaration
//!   *introduces* is. Collecting references is a different pass with a different output shape, and doing it
//!   here would make this pass's result ambiguous between "declared here" and "used here".
//! * **A qualified name is kept qualified.** `int ns::Widget::count;` does not declare `count` in the
//!   enclosing scope, because that is not what it means — it declares a member of `ns::Widget`, and resolving
//!   which one needs the qualifier resolved. Binding it as a plain `count` would put a name in scope that
//!   cannot actually be used unqualified.
//!
//! # Malformed input
//!
//! This layer runs while a file is being typed, so every step has a fallback: an unreadable name is skipped
//! rather than invented, and a construct the parser recovered from contributes whatever it did parse. A
//! binding that cannot be placed is dropped, and the resulting gap is visible to a consumer — which is better
//! than a binding in the wrong scope, and much better than a panic in an editor.

use cpp_parser::{
    CppAstNode, CppAstToken, CppSyntaxKind, CppSyntaxNode, CppTokenKind, MacroBodies,
};

use crate::summary::MacroScopeReading;

use crate::symbol::{
    Binding, BindingKind, BindingOrigin, DeclName, Name, QualifiedName, ScopeId, ScopeKind,
    ScopeTree,
};

/// Should a block statement open a scope of its own?
///
/// A `compound-statement` is the body of a namespace, of a function, of a class — and of an `if`, a loop, or a
/// bare block. Only the last group introduces a scope: the others *are* the scope their header created, and
/// opening a second one would put a namespace's declarations one level too deep. The distinction is carried by
/// the caller, which knows which header it is walking.
///
/// The function-body case is handled by walking the body's *contents* into the function scope rather than by
/// walking the body node, so there is no variant for it here: a `CompoundStat` reached through
/// [`ScopeWalker::descend`] is always a statement block, because every construct whose body is not one has
/// already taken its contents directly.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Body {
    /// The compound statement is a statement block and opens its own scope.
    OpensAScope,
}

/// The answer for a caller with no macro evidence at all — a buffer parsed on its own, or a test that is about
/// something else.
///
/// The parser's own [`cpp_parser::NothingAtAll`], under the name this crate's callers and tests already use: one
/// type with two names would be worse than one name in two crates, and the *behaviour* is the thing both crates
/// have to agree about — "nobody says", which is the answer that leaves every reading exactly where it was before
/// the seam existed.
pub use cpp_parser::NothingAtAll as NoMacroBodies;
/// Build a file's symbol table from its syntax tree.
///
/// The root node is the translation unit, and the table it produces has that as its file scope. See the module
/// documentation for what is and is not recorded.
///
/// `bodies` is what the file's **includes** say about the macros it invokes — see [`MacroBodies`]. A caller with no
/// such evidence passes [`NoMacroBodies`] and gets exactly the table this function produced before the parameter
/// existed.
pub fn build_scopes(root: &CppSyntaxNode, bodies: &dyn MacroBodies) -> ScopeTree {
    build_scopes_with(root, bodies, true)
}

/// **[`build_scopes`] with a choice about function bodies.** A **program**'s reading keeps none: a local is a
/// name no importer can write, and bodies are about half of the standard library's tree — see `build_facts`,
/// which drops the same declarations, and `index_tree`, which passes `keep_locals` to both.
pub fn build_scopes_with(
    root: &CppSyntaxNode,
    bodies: &dyn MacroBodies,
    want_bodies: bool,
) -> ScopeTree {
    let mut walker = ScopeWalker {
        table: ScopeTree::new(),
        bodies,
        own: Default::default(),
        want_bodies,
    };

    let file = walker.table.create_scope(
        ScopeKind::TranslationUnit,
        None,
        Some(cpp_parser::source_range(root.text_range())),
    );

    walker.items(root, file);

    walker.table
}

/// Walks a tree, creating a scope per construct and a binding per declaration.
struct ScopeWalker<'a> {
    table: ScopeTree,
    /// What the includes say about a macro the file invokes — see [`MacroBodies`], which is
    /// [`cpp_parser::MacroBodies`]: the seam is one trait, in the crate that owns the reader that needs it.
    bodies: &'a dyn MacroBodies,
    /// **Whether function bodies are entered at all.** See [`build_scopes_with`]: a program's reading does not.
    want_bodies: bool,
    /// **The file's own `#define`s**, as the walk passes them.
    ///
    /// `bodies` is what the file's **includes** contribute, and a macro a file writes and invokes *itself* is in
    /// neither: it is written here, so no include can carry it, and an environment built from the closure has
    /// never seen it. Leaving it out cost the scope the macro opens, and the declarations behind it were filed
    /// at file scope.
    ///
    /// Measured as a pair, which is what makes it a defect rather than a limitation:
    ///
    /// ```text
    /// #define NSB namespace deepns {     written in a header main.cpp includes   → `Deep` is `deepns::Deep`  ✓
    ///                                  written in the file that invokes it      → `Deep` is `Deep`          ✗
    /// ```
    ///
    /// `tests/scopes.rs`'s `a_scope_a_macro_body_opens_is_held_where_the_invocation_is_two_headers_down` is that
    /// pair, and it holds however deep the file is — the entry point's own summary is not the only one the index
    /// builds.
    ///
    /// Filled **as the walk passes each directive**, which is what makes it positional for free: a `#define`
    /// below its own use is not in the table yet when that use is read, and that is the language's rule rather
    /// than a coincidence of this implementation.
    own: rustc_hash::FxHashMap<Box<str>, Box<str>>,
}

/// A body reader that answers from the file's **own** `#define`s first, then from what its includes say.
///
/// The two are one question — "what does this name stand for here" — asked of two sources, and neither can
/// answer for the other: a name written in this file is in no include, and a name from a header is in no
/// `#define` of this file. [`ScopeWalker::opened_by_a_body`] used to ask only the second.
struct OwnAndIncluded<'a> {
    own: &'a rustc_hash::FxHashMap<Box<str>, Box<str>>,
    included: &'a dyn MacroBodies,
}

impl MacroBodies for OwnAndIncluded<'_> {
    fn body_at(&self, name: &str, at: usize) -> Option<std::borrow::Cow<'_, str>> {
        if let Some(body) = self.own.get(name) {
            return Some(std::borrow::Cow::Borrowed(body));
        }
        self.included.body_at(name, at)
    }
}

/// Whether the token **before** this node is `inline` — the `inline` in `inline namespace X {`.
///
/// The keyword is a **sibling** of the `NamespaceDecl` rather than a child of it, which is what the first
/// attempt at this got wrong: the tree is
///
/// ```text
/// Syntax(TranslationUnit)@0..45
///   Token(InlineKeyword)@0..6 "inline"
///   Syntax(NamespaceDecl)@7..45
///     Token(NamespaceKeyword)@7..16 "namespace"
/// ```
///
/// so asking the node's own tokens for an `InlineKeyword` can never find one, and a check written that way
/// silently answers `false` for every inline namespace — which is exactly what it did.
///
/// [`begins_an_exported_region`](crate::sema::declarations::begins_an_exported_region) walks back the same way
/// for `export`, which is spelled in front of a declaration for the same reason and lands in the same place.
/// Trivia is skipped, because `inline` and the declaration it modifies may be separated by a newline or a
/// comment — a macro body is written across lines more often than not.
fn begins_an_inline_namespace(node: &CppSyntaxNode) -> bool {
    let mut previous = node.prev_sibling_or_token();

    while let Some(element) = previous {
        if let Some(token) = element.as_token() {
            if cpp_parser::is_trivia(CppTokenKind::from(token.kind())) {
                previous = token.prev_sibling_or_token();
                continue;
            }

            return CppTokenKind::from(token.kind()) == CppTokenKind::InlineKeyword;
        }

        // A *node* before this one: the keyword is not there, whatever it is.
        return false;
    }

    false
}

/// `#define NAME …` from a directive node, when that is what it is and `NAME` is **object-like**.
///
/// A function-like macro is not a scope opener — `#define F(x) namespace n {` opens nothing, because `F` is not
/// the name a declaration can follow — so the `(` is what refuses it.
///
/// The body is the rest of the **logical line**: tokens up to the one that carries the newline, which is inside
/// the directive node. Continuations are already part of that node, so a body written across lines
/// (`_STD_BEGIN`'s real spelling) arrives whole.
fn a_define_at(node: &CppSyntaxNode) -> Option<(String, String)> {
    if !cpp_parser::CppPreprocessorDirective::can_cast(node.kind().into()) {
        return None;
    }

    let tokens: Vec<_> = node
        .children_with_tokens()
        .filter_map(|child| child.into_token())
        .filter(|token| !token.text().trim().is_empty())
        .collect();

    if CppTokenKind::from(tokens.first()?.kind()) != CppTokenKind::Hash {
        return None;
    }
    if tokens.get(1)?.text() != "define" {
        return None;
    }
    let name = tokens.get(2)?;
    if CppTokenKind::from(name.kind()) != CppTokenKind::Identifier {
        return None;
    }
    if tokens
        .get(3)
        .is_some_and(|token| CppTokenKind::from(token.kind()) == CppTokenKind::LeftParen)
    {
        return None;
    }

    let body = tokens[3..]
        .iter()
        .take_while(|token| !token.text().contains('\n'))
        .map(|token| token.text())
        .collect::<Vec<_>>()
        .join(" ");

    Some((name.text().to_string(), body))
}

/// What an invocation does to the scope the walk is in, when its replacement list says.
///
/// Three alternatives rather than one plus flags, because each is read from a different body — `namespace X {`,
/// `try {`, `}` — and a single value would have to invent a name for the ones that name nothing.
enum OpenedByBody {
    Opens {
        name: String,
        /// The namespace's segments, outermost first. Empty for `namespace {`.
        segments: Vec<String>,
        body: String,
        range: cpp_parser::SourceRange,
    },
    Closes {
        name: String,
        body: String,
        range: cpp_parser::SourceRange,
    },
    /// An invocation that **opens a brace** and names nothing (`try {`, `extern "C" {`).
    ///
    /// A frame with no scope behind it: what it buys is that the invocation which closes it pops *this* frame
    /// rather than a namespace that is still open. Nothing is recorded — a reading is evidence about a scope, and
    /// there is no scope here.
    OpensABrace {
        /// Kept for the diagnostic value of the name in a debugger, since no reading stores it.
        #[allow(dead_code)]
        name: String,
        #[allow(dead_code)]
        range: cpp_parser::SourceRange,
    },
}

impl ScopeWalker<'_> {
    /// Walk the children of `node`, adding what they declare to `scope`.
    ///
    /// **The scope can change part way through the list**, and that is the one thing this loop does that the
    /// original did not: `_STD_BEGIN` is a *sibling* of the declarations it wraps, because the file has no `{` of
    /// its own for them to live in — the brace is in the macro's body. So the walk keeps a *current* scope, and an
    /// invocation whose body says `namespace std {` moves the declarations after it into a `std` scope until an
    /// invocation whose body is `}` moves them back out. See [`ScopeWalker::opened_by_a_body`].
    fn items(&mut self, node: &CppSyntaxNode, scope: ScopeId) {
        self.walk_children(node, scope, None);
    }

    /// Walk the children of `node` into `scope`, treating a body node as part of `scope` rather than nested.
    ///
    /// For a namespace, a class, or an enum, the `{ ... }` **is** the scope the construct opened: its contents
    /// belong to `scope` itself, not to a block inside it. Walking the body node through the ordinary path would
    /// open a second scope and put every declaration one level too deep — which still looks plausible, and
    /// breaks every lookup that walks outward.
    fn items_in_scope(&mut self, node: &CppSyntaxNode, scope: ScopeId, bodies: &[CppSyntaxKind]) {
        self.walk_children(node, scope, Some(bodies));
    }

    /// The one child loop: macro-opened scopes first, then the ordinary [`ScopeWalker::item`].
    ///
    /// `same_scope_bodies` are the child kinds whose own contents belong to `scope` rather than to a block inside
    /// them ([`ScopeWalker::items_in_scope`]); `None` is the plain walk, where a `CompoundStat` is a statement block
    /// and opens a scope of its own.
    fn walk_children(
        &mut self,
        node: &CppSyntaxNode,
        scope: ScopeId,
        same_scope_bodies: Option<&[CppSyntaxKind]>,
    ) {
        let mut current = scope;
        // The scopes an invocation opened and no invocation has closed yet, each with the scope to come back to.
        // A `Vec` because the constructs nest: `_STD_BEGIN … _EXTERN_C … _END_EXTERN_C … _STD_END` is the shape
        // `yvals_core.h` writes, and a single slot would leave the second closer undoing the first opener.
        let mut opened: Vec<(ScopeId, ScopeId)> = Vec::new();

        for child in node.children() {
            // **A directive is read before it is asked about**, so a `#define` this file writes is in force for
            // everything below it and not for what stands above. See [`ScopeWalker::own`].
            if let Some((name, body)) = a_define_at(&child) {
                self.own
                    .insert(name.into_boxed_str(), body.into_boxed_str());
            }
            match self.opened_by_a_body(&child) {
                Some(OpenedByBody::Opens {
                    name,
                    segments,
                    body,
                    range,
                }) => {
                    let inner = self.open_from_a_body(&segments, current, range, &name, &body);
                    opened.push((inner, current));
                    current = inner;
                }
                Some(OpenedByBody::OpensABrace { name: _, range: _ }) => {
                    // Nothing to open and nothing to record: the frame exists so the closer has something of its
                    // own to close. The scope the walk is in does not change.
                    opened.push((current, current));
                }
                Some(OpenedByBody::Closes { name, body, range }) => {
                    // The reading is recorded either way: an invocation that closes a construct is as much a part
                    // of why this file's scopes look the way they do as one that opens it, and a consumer checking
                    // the evidence has to be able to see both.
                    self.table.macro_readings.push(MacroScopeReading {
                        range,
                        name,
                        body,
                        opens: None,
                    });
                    if let Some((_, enclosing)) = opened.pop() {
                        current = enclosing;
                    }
                }
                None => match same_scope_bodies {
                    Some(bodies) if bodies.contains(&CppSyntaxKind::from(child.kind())) => {
                        self.items(&child, current);
                    }
                    _ => self.item(&child, current),
                },
            }
        }

        // A construct this file opens and never closes — an unbalanced `_STD_BEGIN`, or a closer written in a file
        // the walk never saw — leaves its scope open, and the declarations walked into it stay there. That is the
        // reading the body asked for, and a missing brace is not something this file's tokens prove.
    }

    /// What the macro written at this node does to the scope, **when a replacement list says** — the whole of the
    /// "scope construction sees through the macro" step.
    ///
    /// Three conditions, and each one is what keeps a guess out:
    ///
    /// * the node is a `MacroCall` at a place the walk is reading declarations from — an invocation the parser read
    ///   as something else (a specifier, a statement inside a body) declares nothing and is not asked about;
    /// * the name's replacement list is one of the two structural shapes ([`cpp_parser::shape_of_a_body`]);
    /// * and the body is asked at the **offset of the invocation**, because a name's meaning is positional:
    ///   `_GLIBCXX_BEGIN_NAMESPACE_VERSION` is `namespace __8 {` in one configuration and nothing at all in another.
    ///
    /// **Why the tree does not do this nesting itself.** The name is in another file, so a `NamespaceDecl` node here
    /// would have no name token — and a tree whose *shape* depends on what a header says would differ between the
    /// index's parse (which has the include closure) and an editor's ([`crate::file::FileView`] parses the buffer on
    /// its own). Two trees that disagree about nesting is a worse defect than one flat tree whose scopes say more:
    /// the flat shape is what this file's tokens actually say, and the scope is the evidence's contribution,
    /// recorded in [`ScopeTree::macro_readings`] beside it.
    fn opened_by_a_body(&self, node: &CppSyntaxNode) -> Option<OpenedByBody> {
        if CppSyntaxKind::from(node.kind()) != CppSyntaxKind::MacroCall {
            return None;
        }

        let name = invocation_name(node)?;
        let range = cpp_parser::source_range(node.text_range());
        // **This file's own `#define`s first, then the includes'** — see [`ScopeWalker::own`]. Both the body and
        // the words *inside* it are read through the pair, because a body this file wrote may name a word a
        // header defines (`_STD_BEGIN` → `_EXTERN_CXX_WORKAROUND`) and the other way round.
        let bodies = OwnAndIncluded {
            own: &self.own,
            included: self.bodies,
        };
        let body = bodies.body_at(&name, range.start_offset)?;

        // **Asked at the invocation's own offset**, because a body is positional in two ways: the body itself
        // (`_GLIBCXX_BEGIN_NAMESPACE_VERSION` is `namespace __8 {` in one configuration and nothing in another),
        // and the words *inside* it (`_STD_BEGIN` is `_EXTERN_CXX_WORKAROUND namespace std {`, and
        // `_EXTERN_CXX_WORKAROUND` is empty in the arm that is in force — see [`cpp_parser::shape_of_a_body_at`]).
        match cpp_parser::shape_of_a_body_at(&body, &bodies, range.start_offset) {
            cpp_parser::BodyShape::OpensANamespace(segments) => Some(OpenedByBody::Opens {
                name,
                segments,
                body: body.to_string(),
                range,
            }),
            cpp_parser::BodyShape::ClosesABlock => Some(OpenedByBody::Closes {
                name,
                body: body.to_string(),
                range,
            }),
            // A **statement-level opener** — `try {`, `extern "C" {`. It names nothing, so no scope is created and
            // no reading is recorded (a reading is evidence about a *scope*); what it does is keep the brace
            // count honest, so the `}`-bodied invocation that closes it pops *this* frame rather than the
            // namespace around it.
            cpp_parser::BodyShape::OpensABlock => Some(OpenedByBody::OpensABrace { name, range }),
            // A qualifier (`_STD` = `::std::`) is not a construct: it changes how a *name* is read, which is the
            // parser's business (`exprs.rs`/`types.rs`), and it opens and closes nothing. Listed rather than
            // caught by `_` so that a new shape cannot be added without this match being looked at.
            cpp_parser::BodyShape::QualifiesAName | cpp_parser::BodyShape::Other => None,
        }
    }

    /// Open the namespace an invocation's body spelled, and record where the reading came from.
    ///
    /// **No binding is created for the name**, and that is deliberate rather than an omission: a binding is a
    /// *declaration site* — what a rename edits and what a reference search answers with — and this file does not
    /// write the name. `std` is spelled nowhere in MSVC's `<vector>`; a binding whose range pointed at `_STD_BEGIN`
    /// would make "rename `std`" rewrite the macro invocation. The scope is what the query layer needs (a qualified
    /// name runs through it, so `std::vector` resolves), and a scope with no binding claims nothing about where the
    /// name was written.
    fn open_from_a_body(
        &mut self,
        segments: &[String],
        parent: ScopeId,
        range: cpp_parser::SourceRange,
        name: &str,
        body: &str,
    ) -> ScopeId {
        let inner = if segments.is_empty() {
            // `namespace {` — a namespace with no name, whose contents are visible in this file and nowhere else.
            self.table
                .create_scope(ScopeKind::Namespace, Some(parent), Some(range))
        } else {
            // **`inline namespace X {` is opened, and contributes no segment.** See
            // [`cpp_parser::a_body_opens_an_inline_namespace`] for why the question is asked separately from the
            // shape, and [`ScopeWalker::open_namespace_chain`] for what leaving the name off does.
            let inline = cpp_parser::a_body_opens_an_inline_namespace(body);
            self.open_namespace_chain(segments, parent, range, inline)
        };

        self.table.macro_readings.push(MacroScopeReading {
            range,
            name: name.to_string(),
            body: body.to_string(),
            opens: Some(segments.to_vec()),
        });

        inner
    }

    /// Walk one construct, adding what it declares to `scope`.
    ///
    /// The match is exhaustive over the kinds that *declare* something, and everything else falls through to
    /// [`ScopeWalker::descend`], which keeps looking. That fallback is what makes this robust on the shapes the
    /// grammar produces for constructs it recovered from: a node this does not recognise is still searched for
    /// the declarations inside it.
    fn item(&mut self, node: &CppSyntaxNode, scope: ScopeId) {
        match CppSyntaxKind::from(node.kind()) {
            CppSyntaxKind::NamespaceDecl => self.namespace(node, scope),
            CppSyntaxKind::ClassDef
            | CppSyntaxKind::StructDef
            | CppSyntaxKind::UnionDef
            | CppSyntaxKind::ClassDecl
            | CppSyntaxKind::StructDecl
            | CppSyntaxKind::UnionDecl => self.class_like(node, scope, scope, BindingKind::Class),
            CppSyntaxKind::EnumDef | CppSyntaxKind::EnumClassDef => {
                self.enum_like(node, scope, scope)
            }
            // A `TemplateDecl` met on its own — outside the `Declaration` that normally holds it — declares
            // nothing by itself: it is the header, and the declaration it belongs to is elsewhere. Its
            // parameters still open a scope, so descending is right.
            CppSyntaxKind::TemplateDecl => {
                let parameters = self.table.create_scope(
                    ScopeKind::TemplateParameters,
                    Some(scope),
                    Some(cpp_parser::source_range(node.text_range())),
                );
                for list in node
                    .children()
                    .filter(|child| cpp_parser::CppTemplateParamList::can_cast(child.kind().into()))
                {
                    self.template_parameters(&list, parameters);
                }
                self.items(node, parameters);
            }
            // **A `typedef` declares an alias *and* may declare a class body.** `typedef_decl` binds the alias names
            // (one per declarator); `specifiers` is what walks a `{ … }` into a scope with its members, and it was
            // never called here — so `typedef struct Named { int c; } Named;` produced **one fact** (the alias,
            // `type_of: "struct Named { int c; }"`) and no member at all, for the *tagged* spelling as much as the
            // anonymous one. Measured on the neovim checkout's fixture with `tests/anon_struct_probe.rs`:
            // `members_of("Object")` answered an empty list, and "a member list built from no visible declaration"
            // was **21 539 of 40 000 refusals** across that project — C declares almost every struct this way.
            CppSyntaxKind::TypedefDecl => {
                self.typedef_decl(node, scope);
                self.specifiers(node, scope, scope, false);
            }
            // **A `concept` declares a type-level name, and it declares it in the scope it is written in.**
            //
            // The node was read by the parser and by nothing else: measured, `grep ConceptDecl` over this crate found
            // **no** handling anywhere, so `template <class T> concept UnaryCopyable = …;` bound nothing — and a
            // highlighter then had no opinion about `UnaryCopyable`, which is the name a reader most needs coloured
            // in a constraints header.
            //
            // `BindingKind::Alias` rather than a kind of its own: a concept *is* a name for a constraint rather than
            // a storage class, and every consumer that treats an alias as a type — completion, semantic tokens, the
            // signature of a template — is saying the right thing about it. A new kind would have to be taught to all
            // of them to say the same.
            CppSyntaxKind::ConceptDecl => self.concept_decl(node, scope, scope),
            // **A `friend` declaration wraps a declaration of its own** — `friend bool operator==(…) { … }` is
            // `FriendDecl { Declaration { … } }` — and nothing walked into it, so an inline friend's parameters and
            // body were bound nowhere: every use of `left`/`right` in the fixture above read as undeclared. The
            // wrapped declaration is an ordinary one; `declaration` knows it is a friend because its parent is this
            // node, and that is what keeps the friend's *name* out of the class's members.
            CppSyntaxKind::FriendDecl => self.items(node, scope),
            // **A lambda declares a scope of its own**, and nothing created one: `ScopeKind::Lambda` existed
            // with no constructor. Reported from an editor — `if (const auto result = safe_divide(a, b))` inside
            // `auto show_division = [](double a, double b) { … };` had no hover, no completion and no deduced
            // type, because everything inside the lambda was unbound. Measured: the body's declarations were
            // **absent from the index entirely**, where the same body outside a lambda filed them.
            CppSyntaxKind::LambdaExpr => self.lambda(node, scope),
            CppSyntaxKind::UsingDecl => self.using_decl(node, scope),
            CppSyntaxKind::UsingDirective => self.using_directive(node, scope),
            CppSyntaxKind::Declaration => self.declaration(node, scope),
            CppSyntaxKind::LabelStat => self.label(node, scope),
            // The constructs that open a scope a statement lives in. `CompoundStat` is deliberately absent:
            // whether it opens one is the caller's decision, and is passed down instead.
            CppSyntaxKind::ForStat
            | CppSyntaxKind::RangeForStat
            | CppSyntaxKind::WhileStat
            | CppSyntaxKind::DoWhileStat
            | CppSyntaxKind::SwitchStat
            | CppSyntaxKind::TryStat
            | CppSyntaxKind::IfStat => self.statement_scope(node, scope),
            // **A handler binds its exception variable**, and nothing bound it: `catch (std::exception const&
            // again) { … again.what() … }` had no declaration for `again` anywhere in the tree, so every use of it
            // read as undeclared (one finding on `exceptions.cpp` of the C++ corpus). The handler is a scope like a
            // function's: the variable is visible in the body and nowhere else.
            CppSyntaxKind::CatchStat => self.catch_handler(node, scope),
            _ => self.descend(node, scope, Body::OpensAScope),
        }
    }

    /// Keep looking inside a node that declares nothing itself.
    ///
    /// A `compound-statement` met here is a statement block — the caller has already said that the scope its
    /// header introduced is `scope` — so it opens one of its own, which is what makes `{ int x; }` inside a body
    /// a nested scope rather than a flattening.
    ///
    /// A **body belonging to a class-like construct** is the exception, and the reason this checks for one: a
    /// namespace's and a class's contents are their own scope, so opening a block here would put every
    /// declaration one level too deep. The check is on the body's own kind, because by the time a body is
    /// reached the construct that owns it is not visible any more — which is exactly how this went wrong the
    /// first time.
    fn descend(&mut self, node: &CppSyntaxNode, scope: ScopeId, body: Body) {
        if cpp_parser::CppCompoundStat::can_cast(node.kind().into()) {
            // **A program's reading keeps no bodies**: a local is a name no importer can write, and a body is half
            // of the standard library's tree. See `build_scopes_with`.
            if !self.want_bodies {
                return;
            }
            let inner = self.block(node, scope, body);
            self.items(node, inner);
            return;
        }

        self.items(node, scope);
    }

    /// `catch (Type const& name) { … }` — the handler's own scope, holding the exception variable.
    ///
    /// The declaration is a `Parameter` inside the handler's `ParameterList`, and the body is its `CompoundStat`
    /// child. The parameter list is read by [`ScopeWalker::parameters`] — the same reader a function's list uses — and
    /// then the body is walked as a block of its own.
    fn catch_handler(&mut self, node: &CppSyntaxNode, parent: ScopeId) {
        let handler = self.table.create_scope(
            ScopeKind::Block,
            Some(parent),
            Some(cpp_parser::source_range(node.text_range())),
        );

        for list in node
            .children()
            .filter(|child| cpp_parser::CppParamList::can_cast(child.kind().into()))
        {
            self.parameters(&list, handler);
        }

        for body in node
            .children()
            .filter(|child| cpp_parser::CppCompoundStat::can_cast(child.kind().into()))
        {
            let block = self.block(&body, handler, Body::OpensAScope);
            self.items(&body, block);
        }
    }
    /// A block statement, opening a scope for the statements it holds.
    fn block(&mut self, node: &CppSyntaxNode, parent: ScopeId, body: Body) -> ScopeId {
        match body {
            Body::OpensAScope => self.table.create_scope(
                ScopeKind::Block,
                Some(parent),
                Some(cpp_parser::source_range(node.text_range())),
            ),
        }
    }

    /// `namespace ns { ... }`, the nested spelling `namespace a::b { ... }`, and the anonymous form.
    fn namespace(&mut self, node: &CppSyntaxNode, parent: ScopeId) {
        let range = cpp_parser::source_range(node.text_range());

        // The body, found before anything is created, because the scope chain below has to know whether the
        // declaration has one at all.
        let body = first_child(node, CppSyntaxKind::CompoundStat);

        // `namespace a::b { }` is one declaration that introduces **both** names, and it is the same construct
        // as the spelled-out nesting. One scope per segment is what makes the two produce the same qualified
        // name, and the bindings follow the scopes: `a` goes in the enclosing scope and `b` inside `a`, because
        // that is where each becomes usable.
        //
        // An anonymous namespace has no segments at all, which is a fact about the program rather than a
        // failure: its contents are visible in this file and nowhere else, and no qualified name runs through it.
        let segments = namespace_segments(node);
        let segment_ranges = namespace_segment_ranges(node);

        // **Is this an inline namespace?** [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`, and that macro's 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.
        let inline = begins_an_inline_namespace(node);

        let scope = match (segments.as_slice(), body) {
            // Anonymous. Nothing to name and nothing to make reachable.
            ([], _) => self
                .table
                .create_scope(ScopeKind::Namespace, Some(parent), Some(range)),
            (segments, Some(_)) => self.open_namespace_chain(segments, parent, range, inline),
            // A namespace declaration with no body — `namespace ns;` is not legal C++, but the grammar can
            // produce one from malformed input, and naming a scope that has nothing in it is better than
            // opening a chain the walk then has to explain.
            (segments, None) => self.table.create_named_scope(
                ScopeKind::Namespace,
                Some(parent),
                Some(range),
                segments.last().map(String::as_str),
            ),
        };

        self.bind_namespace_segments(&segments, &segment_ranges, scope, parent, node, range);

        self.items_in_scope(node, scope, &[CppSyntaxKind::CompoundStat]);
    }

    /// Bind each segment of a namespace name in the scope that segment becomes usable in.
    ///
    /// `inner` is the innermost scope the declaration opened, and the bindings are placed by walking *outward*
    /// from it: the last segment goes in the innermost scope, and the first goes in `parent` — which is what
    /// makes `namespace a::b` and `namespace a { namespace b {` introduce the same two names in the same two
    /// places. That is each name being where it is usable: `a` from the enclosing scope, `b` from inside `a`.
    ///
    /// [`declared_name`] cannot answer this: it refuses a qualified name, which is right for every other
    /// declaration (`int ns::count;` declares a member of `ns`, not a name here) and wrong for this one, where
    /// the `::` *is* a nesting the declaration creates.
    fn bind_namespace_segments(
        &mut self,
        segments: &[String],
        ranges: &[cpp_parser::SourceRange],
        inner: ScopeId,
        parent: ScopeId,
        node: &CppSyntaxNode,
        whole: cpp_parser::SourceRange,
    ) {
        // Innermost first, and each name lands one scope *outside* its own: `a` is usable from the scope that
        // encloses it, so that is where it is declared. `enclosing` therefore starts at the innermost scope's
        // parent, which for a single-segment name is already the answer.
        let mut enclosing = self
            .table
            .scope(inner)
            .and_then(|scope| scope.parent)
            .unwrap_or(parent);

        for index in (0..segments.len()).rev() {
            let name_range = ranges.get(index).copied().unwrap_or(whole);
            self.bind(
                enclosing,
                Name::identifier(&segments[index]),
                BindingKind::Namespace,
                node,
                name_range,
            );

            enclosing = self
                .table
                .scope(enclosing)
                .and_then(|scope| scope.parent)
                .unwrap_or(parent);
        }
    }

    /// Open one namespace scope per segment of a nested namespace name, returning the innermost.
    ///
    /// The intermediate scopes are the reason this is a chain rather than one scope with a compound name: a
    /// qualified name is built one segment at a time by [`ScopeTree::qualified_name_of`], so `a::b` has to be
    /// two scopes or `a::b::C` cannot be produced. Each takes the namespace declaration's range, because the
    /// whole declaration is what introduced all of them.
    ///
    /// A single-segment name goes through here too, which keeps one rule for where the body lands.
    /// `inline` decides whether the scopes this opens **contribute a segment to a qualified name**.
    ///
    /// A scope's name is what [`ScopeTree::qualified_name_of`] joins to spell a declaration's qualified name,
    /// so leaving it off is exactly the statement "declarations written in here are qualified by what encloses
    /// it" — which is what an inline namespace means. The scope is still created and still holds its bindings:
    /// lookup walks through it, braces balance in it, and `bind_namespace_segments` still declares the name, so
    /// `std::__p2286` remains resolvable as a scope. What it does not do is *appear* in a qualified name, and
    /// that is the half `std::format` needs.
    fn open_namespace_chain(
        &mut self,
        segments: &[String],
        parent: ScopeId,
        range: cpp_parser::SourceRange,
        inline: bool,
    ) -> ScopeId {
        let mut enclosing = parent;

        for segment in segments {
            enclosing = self.table.create_named_scope(
                ScopeKind::Namespace,
                Some(enclosing),
                Some(range),
                if inline { None } else { Some(segment) },
            );
        }

        enclosing
    }

    /// A class, struct, or union, in either its definition or its declaration form.
    ///
    /// Both forms are handled together because both *declare* the name — `class Widget;` is a declaration that
    /// makes `Widget` known as a class — and the difference is only whether a body follows.
    /// A class, struct, or union, in either its definition or its declaration form.
    ///
    /// Both forms *declare* the name — `class Widget;` makes `Widget` known as a class — and the difference is
    /// only whether a body follows. That difference decides whether a scope is opened at all, which matters:
    /// a forward declaration has no members, so an empty class scope for it is a scope a consumer would report
    /// as "this class has no members" rather than "this class was not defined here".
    fn class_like(
        &mut self,
        node: &CppSyntaxNode,
        outer: ScopeId,
        inner: ScopeId,
        kind: BindingKind,
    ) {
        // **The name has to be the one written *before* the body, and that is the whole of the anonymous case.**
        //
        // `declared_name` looks along the declarator-to-name path, and for a class whose only child is the body — the
        // anonymous `struct { int a; int b; }` — that path descends *into* the body and answers the **first member's**
        // name. Measured with `tests/anon_struct_probe.rs`: `typedef struct { int a; int b; } Object;` produced a class
        // scope named **`a`**, holding `["a", "b"]`, so a member query for `Object` had nothing to look at — and on the
        // neovim checkout "a member list built from no visible declaration" was **21 539 of 40 000 refusals**, the
        // dominant shape of C. A class's own name is always written before its `{`, so anything at or after the body
        // starts is a member's name and not the class's.
        let body = first_child(node, CppSyntaxKind::ClassBody);
        let body_start = body
            .as_ref()
            .map(|body| usize::from(body.text_range().start()));
        let declared = declared_name(node)
            .filter(|(_, range)| body_start.is_none_or(|start| range.start_offset < start));

        // **`typedef struct { … } Name;`** — the struct has no tag, and the only name the type has is the typedef's, so
        // the class body's scope takes that name. Measured on the neovim checkout: `Object`
        // (`typedef struct { ObjectType type; union { … } data; } Object;`) answered **0 members**.
        //
        // **And `struct { … } bits;` — the variable's name**, for the same reason one step further out: the type has no
        // spelling at all, and the members must be reachable from *something*. `sema::types` keys such a variable's type
        // by its own name (see the note there), so this is the other half of that agreement.
        let declared_text = declared
            .as_ref()
            .map(|(name, _)| name.kind.text())
            .or_else(|| the_typedef_name_around(node))
            .or_else(|| Self::the_declarators_name_around(node));

        if let Some((name, name_range)) = declared {
            self.bind(outer, name, kind, node, name_range);
        }

        // `class Widget;` — the name is declared and there is nothing else to say about it.
        let Some(body) = body else {
            return;
        };

        // An empty body — `class Widget {};` — opens no scope either: there are no members to hold, and an
        // empty scope would make a consumer report "this class has no members" where the truth is "nothing was
        // written here". Asked of the body rather than of the declaration, because a class with a base clause
        // and no members has no members either.
        if body.children().next().is_none() {
            return;
        }

        // **An anonymous member's body is the enclosing class's body**, which is what an *anonymous union* means:
        // `struct line { union { long integer; double real; }; char colour; };` puts `integer` and `real` in `line`'s
        // member space, and C11 and C++ say so in as many words. This walk created a scope with no name for such a
        // body, so its members were reachable from nowhere — measured on a nine-file C corpus, `line.integer` reported
        // "no member `integer`" and a completion after `line.` offered four of the six names. Pinned by
        // `an_anonymous_unions_members_belong_to_the_struct`.
        // **And no declarator**, which is what tells an anonymous *member* from a member that has a name:
        // `struct { bool file; bool bar; } magic;` declares `magic` — the body's contents are `magic`'s members, not the
        // enclosing struct's — while `union { long integer; double real; };` declares no name at all, so its members are
        // the struct's (C11's anonymous member, and the rule above). Measured: without the declarator test,
        // `struct exarg { … struct { bool file; bool bar; } magic; }` answered four members instead of three, because
        // `file` and `bar` were bound into `exarg`.
        let anonymous_member = declared_text.is_none()
            && !Self::declares_a_name_after_the_body(node, &body)
            && Self::sits_in_a_class_body(node);
        let scope = if anonymous_member {
            inner
        } else {
            self.table.create_named_scope(
                ScopeKind::Class,
                Some(inner),
                Some(cpp_parser::source_range(node.text_range())),
                declared_text.as_deref(),
            )
        };

        // The body is this scope, so its members land here rather than in a block inside it.
        self.items_in_scope(node, scope, &[CppSyntaxKind::ClassBody]);

        // **Now that the class has a name, its constructors can be told from its functions.**
        //
        // A constructor and a member function are spelled the same way — `ExpectedVoid()` and `ExpectedVoid()` — and
        // the only thing that separates them is that a constructor's name is the class's. [`function_binding_kind`]
        // cannot know that while the class is being built, and its own note says so; this is the moment the
        // question becomes answerable, and it is asked once per class rather than once per declaration.
        //
        // Measured on `class ExpectedVoid { constexpr ExpectedVoid() {} };`: without this the constructor was a
        // `Function`, and a highlighter reading it as one drew the constructor's name — and every *use* of the class
        // name near it, which resolves to the same binding — as `method`. A reader scanning the class sees the class
        // name written three times and one of them coloured as a function.
        //
        // The reassignment is safe because it only ever moves `Function` to its own special case: a class cannot have
        // a member function with the class's name, since that is a constructor by definition ([class.ctor]).
        if let Some(class_name) = declared_text.as_deref()
            && let Some(data) = self.table.scope_mut(scope)
        {
            for binding in &mut data.bindings {
                if binding.kind == BindingKind::Function && binding.name.is(class_name) {
                    binding.kind = BindingKind::Constructor;
                }
            }
        }
    }

    /// An `enum`, scoped or unscoped.
    ///
    /// The enumerators are bound in the enum's own scope in both forms. That is exactly right for `enum class`
    /// and *nearly* right for an unscoped `enum`, whose enumerators are also visible in the enclosing scope —
    /// which is a second binding rather than a different one, and is left to the lookup step to model, because
    /// adding it here would make the enum scope report names it does not own.
    fn enum_like(&mut self, node: &CppSyntaxNode, outer: ScopeId, inner: ScopeId) {
        // **The name is read by the parser's own enum node**, not by [`declared_name`]: an enumeration has no
        // declarator, so that function falls back to a node's *last* identifier — which for `enum class E { Yes, No };`
        // is `No`, the last enumerator. Measured on a header declaring
        // `enum class IsTriviallyCopyConstructible { Yes, No };`: the enum's scope came out **unnamed**
        // (`name None`), every enumerator's fact was recorded with `scope: None` — as if it were a file-scope
        // variable — so `E::Yes` could not be resolved from another file, `Yes` was drawn as a variable rather than
        // as an enum member, and a bare `Yes` was reachable from anywhere in the project.
        let from_the_parser = cpp_parser::CppEnumDef::cast(node.clone())
            .and_then(|definition| definition.get_name())
            .and_then(|token| {
                use cpp_parser::CppAstToken as _;
                let text = token.syntax().text().to_string();
                let range = cpp_parser::source_range(token.syntax().text_range());
                name_from_text(&text, node).map(|name| (name, range))
            });
        // **No fallback to `declared_name`.** That reader answers a declaration's name by its *last* identifier —
        // right for a declarator, wrong for an enumeration, whose body comes after the name and holds identifiers of
        // its own. `enum { A = 1, B = A };` has no name; the fallback took the `A` of `B`'s initializer, named the
        // scope `A`, and filed every enumerator inside it (measured on `state_defs.h`: `MODE_INSERT` in
        // `REPLACE_FLAG`, and go-to-definition answered `NotDeclaredHere`). `CppEnumDef::get_name` reads the name
        // where the language writes it, so there is no shape left for a fallback to cover.
        let declared = from_the_parser;
        let declared_text = declared.as_ref().map(|(name, _)| name.kind.text());

        let scope = self.table.create_named_scope(
            ScopeKind::Enum,
            Some(inner),
            Some(cpp_parser::source_range(node.text_range())),
            declared_text.as_deref(),
        );

        // **`enum class` hides its enumerators, `enum` does not.** The difference is one lookup step — see
        // [`crate::sema::resolve::definitions_at`] — and it is read from the head, which is the only place the
        // language writes it: `enum class E` / `enum struct E` are scoped, and `enum E`, `enum { … }` and
        // `enum : int { … }` are not.
        let head: String = node
            .text()
            .to_string()
            .chars()
            .take_while(|character| *character != '{')
            .collect();
        let scoped = head
            .split(|character: char| character.is_whitespace() || character == ':')
            .any(|word| matches!(word, "class" | "struct"));
        if !scoped && let Some(enum_scope) = self.table.scope_mut(scope) {
            enum_scope.unscoped_enum = true;
        }

        if let Some((name, name_range)) = declared {
            self.bind(outer, name, BindingKind::Enum, node, name_range);
        }

        // The enumerators are one level down, inside the body the enumeration writes — and the body is not
        // always a direct child, so it is searched for rather than assumed.
        for body in node
            .descendants()
            .filter(|child| cpp_parser::CppCompoundStat::can_cast(child.kind().into()))
        {
            self.enumerators(&body, scope);
        }
    }

    /// Bind every enumerator declared in a body.
    fn enumerators(&mut self, body: &CppSyntaxNode, scope: ScopeId) {
        for enumerator in body.children() {
            if !cpp_parser::CppEnumerator::can_cast(enumerator.kind().into()) {
                continue;
            }
            if let Some((name, name_range)) = declared_name(&enumerator) {
                self.bind(
                    scope,
                    name,
                    BindingKind::Enumerator,
                    &enumerator,
                    name_range,
                );
            }
        }
    }

    /// `concept UnaryCopyable = requires(T t) { … };`.
    ///
    /// The name is a `NameExpr` child of the node rather than a declarator — the parser reads a `ConceptDecl` as
    /// `concept <name> = <constraint>`, and there is no `Declarator` in it:
    ///
    /// ```text
    /// Syntax(ConceptDecl)@19..68
    ///   Token(Identifier)@19..26 "concept"
    ///   Syntax(NameExpr)@27..40
    ///     Token(Identifier)@27..40 "UnaryCopyable"     ← this
    ///   Token(Assign)@41..42 "="
    /// ```
    ///
    /// `declared_name` is the wrong reader here, and the reason is worth writing down: it looks for a name **only
    /// along the declarator-to-name path**, which is what keeps it from binding the `b` of `a = b;` — and a
    /// `ConceptDecl` has no declarator at all, so that path finds nothing. The name is the `NameExpr` child, and the
    /// identifier inside it is read directly.
    fn concept_decl(&mut self, node: &CppSyntaxNode, scope: ScopeId, parameters: ScopeId) {
        let Some(name_expr) = node
            .children()
            .find(|child| cpp_parser::CppNameExpr::can_cast(child.kind().into()))
        else {
            return;
        };

        // The first identifier of the name expression: a concept is declared with an unqualified identifier, so
        // there is exactly one, and a qualified spelling would not be a concept declaration in the first place.
        let Some(token) = name_expr
            .descendants_with_tokens()
            .filter_map(|element| element.into_token())
            .find(|token| CppTokenKind::from(token.kind()) == CppTokenKind::Identifier)
        else {
            return;
        };

        let text = token.text().to_string();
        if text.is_empty() {
            return;
        }

        self.bind(
            scope,
            Name::identifier(text),
            BindingKind::Alias,
            node,
            cpp_parser::source_range(token.text_range()),
        );

        // **And the constraint is walked inside the parameter list's scope.** `template <typename T> concept Number =
        // std::integral<T> || …;` — the `T` inside the constraint is that parameter, and nothing walked the constraint
        // *at all*: this function ended at the binding, so no `T` was ever bound in the constraint's body. Reported
        // from an editor with a screenshot: the `T`s inside the concept were uncoloured, and the client's own grammar
        // drew the `>` as `keyword.operator.comparison`. Measured through the semantic tokens: the `T` inside
        // `std::integral<T>` had no token at all.
        //
        // The *name* is bound in `scope` and the *constraint* walked in `parameters`, which is the same split a class
        // template makes: the class's name belongs where the template was written, and its body belongs where its
        // parameters are visible.
        self.items(node, parameters);
    }

    /// `typedef int Integer;`.
    fn typedef_decl(&mut self, node: &CppSyntaxNode, scope: ScopeId) {
        // The names are in the declarators, not on the node: `typedef <specifiers> <declarator>, <declarator>;`.
        //
        // **Every** declarator, not the first: `typedef WCHAR *PWCHAR, *LPWCH, *PWCH;` introduces three names in
        // one declaration, and that shape is how every C header writes its pointer aliases. Binding only the first
        // left the others undeclared — so `LPWCH q;` in the same file was a declaration of a type nothing knew,
        // and a consumer asking for the alias `LPWCH` found nothing. The parser reads the list (one loop); this is
        // the other half of the same fact.
        for declarator in node
            .children()
            .filter(|child| cpp_parser::CppDeclarator::can_cast(child.kind().into()))
        {
            if let Some((name, name_range)) = declared_name(&declarator) {
                self.bind(scope, name, BindingKind::Typedef, node, name_range);
            }
        }
    }

    /// `using Alias = T;` and `using ns::f;`, which are the same node kind.
    ///
    /// The two are told apart by whether a `TypeId` follows the `=`: an alias has one, a using-declaration
    /// does not. Both introduce a name into this scope, and the difference is what kind of thing it is.
    fn using_decl(&mut self, node: &CppSyntaxNode, scope: ScopeId) {
        let is_alias = first_child(node, CppSyntaxKind::TypeId).is_some();

        // A `using namespace std;` is a `UsingDecl` wrapping a `UsingDirective`, and it binds a namespace
        // rather than a name — so it is handed to the rule that says so, rather than read as a using-declaration
        // whose name happens to be the namespace's.
        if let Some(directive) = first_child(node, CppSyntaxKind::UsingDirective) {
            self.using_directive(&directive, scope);
            return;
        }

        let kind = if is_alias {
            BindingKind::Alias
        } else {
            BindingKind::UsingDeclaration
        };

        // A using-declaration is usually qualified — `using ns::f;` — and what it introduces is the **last**
        // component: `f` becomes usable unqualified, `ns` does not. An alias is never qualified in the same
        // way, because the name it introduces is written first, so either component would be the same.
        //
        // Read from the *deepest* name in the declaration rather than from the outermost. The two differ for a
        // qualified using-declaration, where the outer `NameExpr` holds the first segment and the rest of the
        // name sits inside it: the outer one's own tokens are `ns`, and its `::` — so a "last identifier" read
        // from there finds nothing and the binding is the qualifier. See [`find_name_node`].
        let Some(name_node) = find_name_node(node) else {
            return;
        };

        let Some(token) = last_identifier(&name_node) else {
            return;
        };

        let text = token.text().to_string();
        let name_range = cpp_parser::source_range(token.text_range());

        let Some(name) = name_from_text(&text, node) else {
            return;
        };

        self.bind(scope, name, kind, node, name_range);
    }

    /// `using namespace ns;` — which declares no name, and still has to be recorded.
    ///
    /// It binds nothing, because it introduces no name: what it does is make a whole namespace's names
    /// visible, which is a fact lookup has to account for and a *binding* cannot express. It is recorded as a
    /// binding of the namespace's name anyway, with [`BindingKind::UsingDirective`], because a consumer asking
    /// "why is `vector` in scope here" needs to find this line — and because the alternative is for the
    /// construct to leave no trace at all.
    fn using_directive(&mut self, node: &CppSyntaxNode, scope: ScopeId) {
        if let Some((name, name_range)) = declared_name(node) {
            self.bind(scope, name, BindingKind::UsingDirective, node, name_range);
        }
    }

    /// A `Declaration`: `int count;`, `void f(int a) { ... }`, `class Widget;`, `enum class E { ... }`.
    ///
    /// # Why the specifiers are searched for a class or an enum
    ///
    /// `class Widget;` and `enum class Color { Red };` are `Declaration`s in this grammar, with the keyword
    /// inside a `BuiltinType` in the decl-specifier sequence — not the `ClassDef` and `EnumClassDef` nodes
    /// that a *definition* with a name in the declarator produces. So the keyword is what identifies the
    /// construct, and reading names only from declarators would leave every forward declaration and every
    /// scoped enum undeclared — which in a real header is most of the class names in the file.
    fn declaration(&mut self, node: &CppSyntaxNode, scope: ScopeId) {
        // **A linkage specification declares nothing itself and holds what it applies to.** `extern "C++" …` is a
        // `Declaration` whose specifier sequence says which linkage and whose *child* is what it covers — a nested
        // `Declaration` for `extern "C" void f();`, a `CompoundStat` for `extern "C" { … }` (see the parser's
        // `parse_linkage_specification`). Neither declares a name, which is why the "an unnamed declaration declares
        // nothing" guard in `declaration_parts` used to return here; neither opens a scope either, because a linkage
        // is a property of the declarations rather than a place names live — C++ puts the names in the enclosing
        // namespace. So the contents are walked **in this scope**.
        //
        // Measured, on MSVC's `<istream>`: the whole iostream hierarchy is written this way
        // (`_EXPORT_STD extern "C++" template <class _Elem, class _Traits> class basic_istream : … { … };`), so
        // `std::basic_istream`, its forty members and everything inheriting from them were absent from the index —
        // the file's first fact was at line **715** of 935 while `class basic_istream` is at line 24, and
        // `std::cin.read`, `std::cout.flush()` and a completion after `std::cin.` all had nothing to answer with.
        if self.linkage(node, scope) {
            return;
        }

        // A templated declaration has its parameter list in a **sibling** node rather than around the
        // declaration, so it is intercepted here: the parameters open a scope, and the declaration's contents
        // are walked inside it. Missing this leaves `T` unbound and a template's class declared in the wrong
        // scope.
        if let Some(template) = first_child(node, CppSyntaxKind::TemplateDecl) {
            self.templated_declaration(node, &template, scope);
            return;
        }

        self.declaration_parts(node, scope, scope);
    }

    /// Walk the contents of a **linkage specification**, and say whether this node was one.
    ///
    /// `extern "C" void f();` and `extern "C" { void f(); }` are the two spellings, and both declare `f` in the
    /// scope the linkage was written in.
    ///
    /// The test is the **string literal**, which is the same one the parser dispatches on
    /// (`starts_a_linkage_specification`): `extern int x;` carries the very same `ExternSpec` and is an ordinary
    /// declaration with a declarator, so a walk that keyed on the keyword alone silently stopped declaring every
    /// `extern` variable — measured, `extern Widget global;` in a fixture, which turned two type tests red. A node
    /// with neither a nested declaration nor a block is not walked here at all: it is left to the ordinary
    /// declaration path, which is where a malformed one belongs.
    fn linkage(&mut self, node: &CppSyntaxNode, scope: ScopeId) -> bool {
        let is_linkage = first_child(node, CppSyntaxKind::DeclSpecifierSeq)
            .and_then(|specifiers| first_child(&specifiers, CppSyntaxKind::ExternSpec))
            .is_some_and(|specification| {
                specification
                    .children_with_tokens()
                    .filter_map(|child| child.into_token())
                    .any(|token| CppTokenKind::from(token.kind()) == CppTokenKind::StringLiteral)
            });
        if !is_linkage {
            return false;
        }

        let mut walked = false;

        for child in node.children() {
            match CppSyntaxKind::from(child.kind()) {
                // The declaration the linkage applies to: `extern "C++" template <…> class C { … };`.
                CppSyntaxKind::Declaration => {
                    self.declaration(&child, scope);
                    walked = true;
                }
                // The braced form. A container rather than a scope: `extern "C" { void f(); }` is one name in the
                // enclosing namespace, and putting it in a block of its own would hide it from everything outside.
                CppSyntaxKind::CompoundStat => {
                    self.items(&child, scope);
                    walked = true;
                }
                _ => {}
            }
        }

        walked
    }

    /// A declaration whose `template <...>` header was found.
    ///
    /// The parameters are bound in a scope of their own, and the declaration's *contents* are walked inside it
    /// — while its declared name belongs to the scope the template was written in. `template <typename T> class
    /// Array { T x; }` declares `Array` outside and `x` within sight of `T`, and those are different scopes.
    fn templated_declaration(
        &mut self,
        node: &CppSyntaxNode,
        template: &CppSyntaxNode,
        scope: ScopeId,
    ) {
        // **The parameters are in force for the whole declaration, not just for its header.** `scope_at` answers the
        // *innermost scope whose range contains the offset*, so a range that stopped at the `>` of
        // `template <typename T>` made `T` invisible everywhere the declaration actually used it — and for a
        // `concept` there is no body scope below it to inherit the binding, so the constraint's `T` belonged to no
        // scope at all. Reported from an editor with a screenshot: `template <typename T> concept Number =
        // std::integral<T> || std::floating_point<T>;` drew nothing on either `T`, so the client's own grammar drew
        // the `>` as a comparison operator. Measured through the semantic tokens: no token for the `T` inside
        // `std::integral<T>`.
        //
        // The rule is the language's: a template parameter is visible from its declaration to the end of the
        // template-declaration it introduces. `node` is exactly that span.
        let parameters = self.table.create_scope(
            ScopeKind::TemplateParameters,
            Some(scope),
            Some(cpp_parser::source_range(node.text_range())),
        );

        for list in template
            .children()
            .filter(|child| cpp_parser::CppTemplateParamList::can_cast(child.kind().into()))
        {
            self.template_parameters(&list, parameters);
        }

        // **A templated `using` is a declaration beside the parameter list, not a declarator.**
        //
        // Measured, the tree is
        //
        // ```text
        // Syntax(Declaration)@20..117
        //   Syntax(TemplateDecl)@20..48        `template <class _Alloc>`
        //   Syntax(UsingDecl)@48..117          `using _Alloc_ptr_t = typename …;`
        // ```
        //
        // so the walk below — which reads *declarators* — finds none, declares nothing, and the alias never
        // becomes a fact. `template <class _Alloc> using _Alloc_ptr_t = …;` is how the standard library writes
        // every allocator and traits alias, so this was leaving whole families of names out of the index:
        // measured on one file's closure, `_Alloc_ptr_t`, `_Alloc_size_t`, `_Alty_traits` and their neighbours
        // were held **zero** times while `basic_string::size_type` — an alias too, but a member of a class and
        // so reached by the class body's walk rather than by this one — resolved normally.
        //
        // The name is bound in `scope` and not in `parameters`, which is the rule the note above states: an
        // alias template declares its name where the template was written, exactly as a class template does.
        if let Some(using) = first_child(node, CppSyntaxKind::UsingDecl) {
            self.using_decl(&using, scope);
            return;
        }

        // **A templated `concept` is the same shape as a templated `using`, and needs the same reading.**
        //
        // ```text
        // Syntax(Declaration)@0..68
        //   Syntax(TemplateDecl)@0..18        `template <class T>`
        //   Syntax(ConceptDecl)@19..68        `concept UnaryCopyable = requires(T t) { … };`
        // ```
        //
        // The two arrive beside the parameter list rather than inside it, and `declaration_parts` reads
        // *declarators* — which a `ConceptDecl` has none of, so it declared nothing and `UnaryCopyable` was a name
        // no consumer could classify. Measured: `grep ConceptDecl` over this crate found no handling anywhere, so
        // **every** concept in every project was invisible.
        //
        // Bound in `scope` and not in `parameters`, for the reason the `using` note above gives: a concept declares
        // its name where the template was written, exactly as a class template does.
        if let Some(concept) = first_child(node, CppSyntaxKind::ConceptDecl) {
            self.concept_decl(&concept, scope, parameters);
            return;
        }

        self.declaration_parts(node, scope, parameters);
    }

    /// Bind every parameter of a `template <...>` list.
    ///
    /// One scope for the whole list, which is what lets a later parameter refer to an earlier one:
    /// `template <typename T, T* Next>` is legal, and a parameter bound in a scope of its own would make `T`
    /// invisible to `Next`.
    fn template_parameters(&mut self, list: &CppSyntaxNode, scope: ScopeId) {
        for parameter in list.children() {
            if !cpp_parser::CppTemplateParam::can_cast(parameter.kind().into()) {
                continue;
            }

            if let Some((name, name_range)) = declared_name(&parameter) {
                self.bind(
                    scope,
                    name,
                    BindingKind::TemplateParameter,
                    &parameter,
                    name_range,
                );
            }
        }
    }

    /// The specifiers and declarators of a declaration, with any class-like specifier resolved first.
    ///
    /// Two scopes rather than one, because a templated declaration puts its name and its contents in different
    /// places: `template <typename T> class Array { T x; }` declares `Array` where the template was written and
    /// puts `x` in a scope that can see `T`. For an ordinary declaration the two are the same scope, which is
    /// what `inner` being passed as `outer` means at the call sites.
    /// Is this declaration **written inside another class's body** — an anonymous member?
    ///
    /// Every ancestor is walked and only a statement block or the translation unit stops it: the declaration a class body
    /// holds is not the node the class was read from, so a search that stopped at the first Declaration answered "not a
    /// member" for the one shape this question exists for.
    /// Does anything **name the object** after the class-like body — the magic of struct { … } magic;?
    ///
    /// `declarators(node)` cannot answer it: the node the class path is handed is the declaration the *body* came from,
    /// and the declarator sits beside it rather than inside it (measured: struct { bool file; bool bar; } magic; answered
    /// "no declarator" and its fields were bound into the enclosing struct). The text after the body is the question
    /// itself — a member without a name is an anonymous member, and one with a name owns its contents.
    fn declares_a_name_after_the_body(node: &CppSyntaxNode, body: &CppSyntaxNode) -> bool {
        // **The declaration, one level up.** The node a class-like specifier is read from is not always the whole
        // declaration — struct { bool file; } magic; reaches this path with the *body's* node, whose text stops at the
        // closing brace, so the name magic is outside it. The nearest ancestor that is a Declaration, or the node
        // itself when there is none.
        let declaration = node
            .ancestors()
            .find(|ancestor| cpp_parser::CppDeclaration::can_cast(ancestor.kind().into()))
            .unwrap_or_else(|| node.clone());
        // **A declarator written after the body**, which is the question itself: `struct { … } magic;` names its object with a
        // declarator beside the body, while `struct { … };` has none. The offsets used to be recovered by searching the body's
        // **text** inside the declaration's.
        let body_end = usize::from(body.text_range().end());
        declarators(&declaration).into_iter().any(|declarator| {
            usize::from(declarator.text_range().start()) >= body_end
                && declared_name(&declarator).is_some()
        })
    }
    /// The **declarator's** name in the declaration that holds this class-like specifier — struct { … } bits; → its.
    ///
    /// The other half of the agreement with `sema::types`: a variable whose type is an unnamed struct is keyed by its own
    /// name, so the class scope has to carry that name or the members are reachable from nowhere.
    fn the_declarators_name_around(node: &CppSyntaxNode) -> Option<String> {
        let declaration = node
            .ancestors()
            .find(|ancestor| cpp_parser::CppDeclaration::can_cast(ancestor.kind().into()))?;
        let declaration = cpp_parser::CppDeclaration::cast(declaration)?;
        declaration.get_name_text()
    }
    fn sits_in_a_class_body(node: &CppSyntaxNode) -> bool {
        for ancestor in node.ancestors() {
            // **A class body or a block, and a block is what stops the search**: a declaration written in a function's body is
            // not a member, whatever class it names.
            if cpp_parser::CppClassBody::can_cast(ancestor.kind().into()) {
                return true;
            }
            if cpp_parser::CppCompoundStat::can_cast(ancestor.kind().into())
                || CppSyntaxKind::from(ancestor.kind()) == CppSyntaxKind::TranslationUnit
            {
                return false;
            }
        }
        false
    }
    fn declaration_parts(&mut self, node: &CppSyntaxNode, outer: ScopeId, inner: ScopeId) {
        // `f(x);` and `int(x);` have the same token shape, so the grammar reads both as a declaration — the
        // most vexing parse, and no parser without a table of type names can tell them apart. What it *can* say
        // is whether any name was declared, and the AST layer already answers that: a real declarator names
        // itself with a direct token or a `NameExpr` child, while the declarator of a call statement holds only
        // a parenthesised declarator one level down. A declaration with no name therefore went through the
        // declaration path without declaring anything, which is what a statement looks like when it lands here.
        //
        // This rejects only real declarations that genuinely have no name — `static_assert(...)`, a type
        // definition with no declarator, an anonymous class — and none of those declares a binding either.
        // **A `::`-qualified declaration never binds its name at file scope.** Either it is a member of a class
        // this file declares, and then `declarator_as` puts it in that class's scope, or the qualifier names
        // something this file has not built — and then it binds nothing here. What it must not do is fall through
        // to the ordinary path, which would bind `count` at file scope: a name that cannot be used unqualified and
        // that collides with every other `count`. `a_qualified_declaration_binds_nothing_here` is that rule.
        //
        // The AST layer cannot tell these apart from a call statement — `get_name_text` answers `None` for both —
        // which is why the question is asked here and in this shape.
        // **A constructor is the same shape and this guard did not see it.** `LuaSource::LuaSource(std::string
        // &&fileText) : _source(fileText), … { … }` spells its name in the specifiers like every out-of-line
        // definition, and `is_unnamed_declaration` is **true** for it — its declarator holds the parameter list, not
        // a name. `declaration_is_qualified` requires both halves and its second half (`named_in_a_declarator`)
        // answered `true` here, so the declaration went down the unnamed branch and the constructor`s parameters
        // were bound by nothing: `fileText` had no hover and no completion inside the body.
        //
        // The second condition is the precise form of the same question: a qualified specifier on a declaration with
        // **no declarator name at all**. `Widget w;` (a qualified type, a plain declarator) is not unnamed and is
        // unaffected.
        //
        // **The name the declaration is written with, wherever the grammar put it** — in the declarator's own name
        // (`int Source::GetLine(int)` — the name is written against `(`, so the declaration rule knows it is the
        // declarator's) or in the specifier sequence (`void Box<int>::grow`, whose qualifier carries template
        // arguments and so cannot be told from a return type). One question, asked once, for the three rules below
        // and for [`ScopeWalker::declarator_as`], which reads the same pair.
        let qualified_name = the_qualified_name_of_a_declaration(node);
        // **A statement that looks like one of these declares nothing, and a definition never nests inside a
        // *function body*.** The most-vexing-parse reading of a call with a qualified callee is exactly this shape —
        // `std::iter_swap(__result, __b);` is a `Declaration` naming `std::iter_swap` with a parameter list — and
        // inside a body it bound a **function** named `iter_swap` in scope `std`, taking the enclosing function's
        // template parameters with it. Measured on libstdc++: `bits/stl_algo.h` alone had 22 `std::iter_swap` facts at
        // namespace scope, `local: false`, all of them call statements.
        //
        // **A namespace body is a `CompoundStat` too**, and asking only for that kind rejected every out-of-class
        // member definition written inside a namespace — the layout of every `.cpp` there is:
        //
        // ```text
        // namespace archive {
        //     void Archive::put(const Entry& entry) { _counts[entry.key] += entry.count; }
        // }
        // ```
        //
        // The whole declaration was dropped: no function scope, no parameter bindings, and `entry` reported as
        // "not declared" in the body it is declared in. What makes a statement a statement is the *parent* of the
        // compound: a function's body hangs off the declaration, a branch's off the `if`, and a namespace's off the
        // `NamespaceDecl` — which is a scope, not a body, so it is allowed through here.
        if qualified_name.is_some()
            && node.ancestors().any(|ancestor| {
                ancestor.parent().is_some_and(|parent| {
                    cpp_parser::CppCompoundStat::can_cast(ancestor.kind().into())
                        && !cpp_parser::CppNamespaceDecl::can_cast(parent.kind().into())
                })
            })
        {
            return;
        }

        // `friend` declarations declare nothing in this scope: `friend class X;` says X's members may reach
        // into this class, and X itself is declared elsewhere. Binding it here would make a friend class look
        // like a member.
        //
        // **Direct children, and the parent.** The `friend` keyword's node wraps the declaration it qualifies —
        // `FriendDecl { Declaration { InitDeclarator … } }` — so the declaration that *is* the friend sees the
        // node as its **parent**, while the declaration that merely contains one (`struct S { friend … };`) sees
        // it as a child. Asked with `descendants()`, the enclosing class definition answered yes and was skipped
        // altogether: the class's name was not bound and its body was never walked.
        //
        // Read before the unnamed check below, which is where a friend *definition* used to be dropped: `operator==`
        // is a name `declared_name` cannot read from its declarator, so the declaration counted as unnamed and the
        // parameters and body of a perfectly ordinary function were never walked.
        let is_friend = node
            .children()
            .any(|child| cpp_parser::CppFriendDecl::can_cast(child.kind().into()))
            || node
                .parent()
                .is_some_and(|parent| cpp_parser::CppFriendDecl::can_cast(parent.kind().into()));

        if let Some((qualifier, _)) = &qualified_name
            && self.scope_of_the_qualifier(qualifier, outer).is_none()
        {
            // **The name is not this file's — the body is.** `size_t LuaSource::GetLine(size_t offset) const
            // { … }` declares nothing at file scope: the class is in a header this file only includes. That
            // rule stays (see `a_qualified_declaration_binds_nothing_here`), and this used to `return` on it,
            // which dropped the **whole** declaration — including the function's own parameters and locals,
            // which have nothing to do with the class.
            //
            // Measured on EmmyLuaCodeStyle's `LuaParser/src/File/LuaSource.cpp` (a file of nothing but
            // out-of-line definitions): the scope tree was one `TranslationUnit` with **zero bindings**, and a
            // completion inside `GetLine` offered `_lineOffsetVec` — a member, which the index answers — and
            // neither `offset` nor `maxLine`. Every `.cpp` of that project is written this way, so the whole
            // file was unsearchable from the inside.
            //
            // What is read is only what the function owns: its parameter names, and the names its body
            // declares, in an unnamed scope that belongs to no class.
            self.read_the_inside_of_a_foreign_definition(node, outer);
            return;
        } else if qualified_name.is_none() && is_unnamed_declaration(node) {
            // **A declaration with no name can still declare members.** `enum { LAJF };` is the C spelling of a set
            // of constants, and it names nothing — `is_unnamed_declaration` is true, so this used to return before
            // the body was walked at all, and every enumerator of an anonymous enum was missing from the scope tree
            // and therefore from the index: reported from an editor as "an unnamed enum is not supported", and
            // measured as `definitions("LAJF") → NotDeclaredHere` in a file that declares it two lines up.
            //
            // The specifier pass is what walks a body — `enum_like`, `class_like` — so it runs here, and only for a
            // declaration that has one. A body-less unnamed declaration (`int;`, a stray `;`) still declares
            // nothing and still returns.
            if declares_a_body(node) {
                self.specifiers(node, outer, inner, false);
                return;
            }
            // **A `friend` definition whose name the declarator does not yield falls through.** The name is the
            // class's business and `is_friend` keeps it out below, but the parameters and the body belong to the
            // function and the declarator loop is what reads them.
            if !is_friend {
                return;
            }
        }

        // `friend` declarations declare nothing in this scope: `friend class X;` says X's members may reach
        // into this class, and X itself is declared elsewhere. Binding it here would make a friend class look
        // like a member.
        // A structured binding declares several names through one `StructuredBinding` node. It appears
        // wherever the pattern was written — as an init-declarator (`auto [a, b] = pair;`) or as a bare
        // declarator — so it is searched for under this declaration's declarators.
        if let Some(names) = ScopeWalker::structured_binding_names(node) {
            for name_node in names {
                if let Some((name, name_range)) = declared_name(&name_node) {
                    self.bind(outer, name, BindingKind::Variable, &name_node, name_range);
                }
            }
            return;
        }

        // A class or an enum written in the specifiers brings its own name — and, for an enum, its own body.
        // When it did, the declarators have nothing left to declare.
        //
        // Whether a body follows is asked once, here, because it decides three things: whether a function
        // declarator opens a scope at all, how far that scope reaches, and what is walked into it.
        let body = function_body(node);
        let mut function_scope = None;

        match self.specifiers(node, outer, inner, is_friend) {
            SpecifierName::Bound => return,
            SpecifierName::InDeclarator(kind) => {
                // The class-like specifier named nothing, so the name is in a declarator — and when there is
                // **no** declarator at all, the name is in the specifier beside the keyword instead:
                // `class Widget;` is a forward declaration, and the grammar now writes it flat (the keyword is
                // one specifier and `Widget` the next) rather than nesting the name inside the keyword. Without
                // this the forward declaration declared nothing, since it has no declarator to read a name from.
                if declarators(node).is_empty() {
                    if let Some((name, name_range)) = elaborated_type_name(node) {
                        self.bind(outer, name, kind, node, name_range);
                    }
                    return;
                }

                for declarator in declarators(node) {
                    function_scope = self
                        .declarator_as(
                            &declarator,
                            outer,
                            inner,
                            is_friend,
                            Some(kind),
                            body.as_ref(),
                        )
                        .or(function_scope);
                }
            }
            SpecifierName::None => {
                for declarator in declarators(node) {
                    function_scope = self
                        .declarator_as(&declarator, outer, inner, is_friend, None, body.as_ref())
                        .or(function_scope);
                }
            }
        }

        // **A function whose name the specifier sequence holds** — `explicit A(int x) : x_(x) {}` is the shape:
        // the declarator is `(int x)` and names nothing, so the loop above bound the parameters and never the
        // function. `CppDeclaration::get_name` reads the name (`305a927` added the arm), and this is the binding that
        // makes it a **fact**: measured on `struct A { explicit A(int x) : x_(x) {} A() {} int f(); }`, `inspect facts`
        // listed `A` at 4:5 and nothing at 2:5, so `A::` offered one of the class's two constructors and a hover on the
        // decorated one answered nothing — the decorator was invisible in the member list while `A()` was there.
        //
        // Guarded by "no declarator names anything", which is what keeps every ordinary function away from this: its
        // declarator holds the name, so the loop already bound it.
        //
        // **And guarded by "the declaration has no qualifier"**, which is what keeps every *qualified definition*
        // away from it. `declared_name` refuses a `::`-qualified name on purpose (line 3038), so `void Pair::Go() { }`
        // satisfied "no declarator names anything", `get_name` read the qualifier `Pair`, and the declaration bound a
        // **constructor `Pair` at file scope** — a phantom fact with no declaration behind it. Measured on a fixture
        // of three out-of-line definitions: every one of them produced one, so a file of nothing but
        // `int Type::member()` declared a function named `Type` for each member, and the code lens drew a
        // `0 references` over a line that declares nothing. The name of a qualified definition belongs to the scope
        // its qualifier names, and the loop above is where that happens.
        if qualified_name.is_none()
            && declarators(node)
                .iter()
                .all(|declarator| declared_name(declarator).is_none())
            && let Some(declaration) = cpp_parser::CppDeclaration::cast(node.clone())
            && declaration.get_param_list().is_some()
            && let Some(token) = declaration.get_name()
        {
            let text = token.get_name_text().to_string();
            if let Some(name) = name_from_text(&text, node) {
                // **The kind is the one the declaration is**, not `Function`: a constructor's `DeclKind` and its
                // `parameter_list` read are both decided by this, and `Function` made the fact say `A` with no
                // parameters — the fact existed and disagreed with its own declaration about what it was.
                self.bind(
                    inner,
                    name,
                    BindingKind::Constructor,
                    node,
                    cpp_parser::source_range(token.get_range()),
                );
            }
        }

        // The body of a function, which the grammar puts beside the declarator rather than inside it. Walking
        // it into the scope the declarator opened is what makes a local variable local.
        // **A lambda written in a declarator's own subtree.** `declarator_as` reads a declarator for its name
        // and its parameters and never walks its children, so `auto f = [](int x) { … };` — where the lambda is
        // **inside** the declarator — reached nothing. `item()`'s own `LambdaExpr` arm covers the ones a
        // statement walk meets; this covers the ones written in an initialiser.
        for declarator in declarators(node) {
            for lambda in cpp_parser::typed_descendants::<cpp_parser::CppLambdaExpr>(&declarator) {
                self.lambda(lambda.syntax(), outer);
            }
        }

        if let Some(function) = function_scope
            && let Some(body) = body
        {
            self.items(&body, function);
        }

        // **Not fixed here, and the measurement is why.** A constructor's member-initializer list holds a use of
        // each parameter — `Name(const int f) : first(f) { … }` — and the grammar puts it in a `MemberInitializer`
        // node **beside** the declarator, so nothing walks it into the function scope. Adding that walk here was
        // tried and changed nothing, because the scope it would walk into is never reached: `function_body` does not
        // find this declaration's `CompoundStat` either. Instrumented, the declaration's children are
        // `["Declarator", "MemberInitializer", "MemberInitializer"]` while the body exists elsewhere in the tree, so
        // the walker creates no function scope for a constructor whose declarator carries a member-initializer list.
        // See `tests/completion.rs`'s ignored `a_constructors_parameters_are_in_scope`.
    }

    /// The names a structured binding pattern declares, if this declaration has one.
    ///
    /// Searched for among the **declarators** rather than across the whole declaration: a `StructuredBinding`
    /// node anywhere in the subtree would also be found inside a function's body, and returning early on that
    /// is how the enclosing function lost its own name and scope — the pattern below belongs to a different
    /// declaration.
    fn structured_binding_names(node: &CppSyntaxNode) -> Option<Vec<CppSyntaxNode>> {
        for declarator in declarators(node) {
            if let Some(binding) = declarator
                .descendants()
                .find(|child| cpp_parser::CppStructuredBinding::can_cast(child.kind().into()))
            {
                return Some(binding.children().collect());
            }
        }

        None
    }

    /// Walk a declaration's specifier sequence, reading any class or enum written there.
    ///
    /// The three outcomes are the three shapes C++ writes these in, and they are worth separating because the
    /// name is in a different place in each:
    ///
    /// ```text
    /// enum class Color { Red };    the name and body are in the specifier      -> Bound
    /// class Widget;                the specifier has only the keyword, and the
    ///                              identifier the declarator holds *is* the class -> InDeclarator
    /// class Widget w;              the class is in the specifier, `w` is not    -> Bound
    /// ```
    fn specifiers(
        &mut self,
        node: &CppSyntaxNode,
        outer: ScopeId,
        inner: ScopeId,
        is_friend: bool,
    ) -> SpecifierName {
        let Some(specifiers) = first_child(node, CppSyntaxKind::DeclSpecifierSeq) else {
            return SpecifierName::None;
        };

        for child in specifiers.children() {
            match CppSyntaxKind::from(child.kind()) {
                // Handled through the declarators by the caller.
                CppSyntaxKind::InitDeclarator | CppSyntaxKind::Declarator => {}
                CppSyntaxKind::ClassDef
                | CppSyntaxKind::StructDef
                | CppSyntaxKind::UnionDef
                | CppSyntaxKind::ClassDecl
                | CppSyntaxKind::StructDecl
                | CppSyntaxKind::UnionDecl => {
                    if !is_friend {
                        self.class_like(&child, outer, inner, BindingKind::Class);
                    }
                    // **The declaration may declare something else as well**, and this used to return before the
                    // caller could look: `struct S { int n; } s;` and `enum E { A } e;` write a declarator *inside
                    // the same declaration as the definition*, so `s` and `e` were never bound and never appeared as
                    // facts. Measured on the four spellings:
                    //
                    // ```text
                    //   struct S { int n; } s;   ->  Type:S, Variable:n          (no `s`)
                    //   struct { int a; } x;     ->  Variable:a                  (no `x`)
                    //   enum E { A } e;          ->  Type:E, Variable:A          (no `e`)
                    //   class C {} c;            ->  Type:C                      (no `c`)
                    // ```
                    //
                    // So the definition is bound here and the **search continues**: the loop has nothing else to say
                    // about a definition, and the caller's declarator branch is what binds `s`. Returning `None`
                    // rather than `Bound` is what lets it — `Bound` means "this declaration named its entity in the
                    // specifiers", which is true only when no declarator follows.
                    if declarators(node).is_empty() {
                        return SpecifierName::Bound;
                    }
                }
                // **A `friend` declaration wraps a declaration of its own** — `friend bool operator==(…) { … }` is
                // `FriendDecl { Declaration { InitDeclarator … CompoundStat } }` — and the specifier walk is where
                // it is reached: the `friend` is a child of the *specifier sequence*, not of the declaration that
                // holds the class body. Walking the wrapper is what reads the friend function's parameters and its
                // body; the friend's own *name* is kept out of the class's members by `is_friend` in `declaration`.
                //
                // Measured: without this, an inline friend's declarator was never reached (the outer declaration
                // answers zero declarators), so its parameters were bound nowhere and every use of `left`/`right`
                // in `classes.cpp` read as undeclared.
                CppSyntaxKind::FriendDecl => {
                    self.items(&child, outer);
                }
                CppSyntaxKind::EnumDef | CppSyntaxKind::EnumClassDef => {
                    if !is_friend {
                        self.enum_like(&child, outer, inner);
                    }
                    // **And a declarator may follow here too** — `enum E { A } e;` declares `e` in the same
                    // declaration as the definition, exactly as `struct S { … } s;` does. See the note on the
                    // class-like arm above; measured, `e` had no fact at all.
                    if declarators(node).is_empty() {
                        return SpecifierName::Bound;
                    }
                }
                // The bare-keyword forms, which is what the grammar produces for `class Widget;` and for
                // `enum class Color { ... }` alike.
                CppSyntaxKind::BuiltinType => {
                    let Some(binding) = class_like_binding_of(&child) else {
                        continue;
                    };

                    if is_friend {
                        return SpecifierName::Bound;
                    }

                    // **A tag named *beside* the keyword is not the declarator's name.** `struct CallInfo *previous;`
                    // is `DeclSpecifierSeq [struct, NameExpr(CallInfo)]` plus a declarator: the keyword names the tag
                    // in an elaborated-type-specifier, and the declarator declares a **variable**. The bare-keyword
                    // path below read that shape as "the keyword alone, so the declarator holds the class" and bound
                    // `previous` as a class — measured, `inspect facts` filed it as `type in CallInfo`, so the
                    // semantic-token pass coloured every such field as a type (reported from an editor on Lua 5.5.0's
                    // `ldebug.c`, `ci->previous`).
                    //
                    // `class Widget w;` is the same shape and gains the other half: the tag is bound here (an
                    // elaborated-type-specifier declares the tag in the enclosing scope, [basic.lookup.elab]) and `w`
                    // is bound as the variable it is, which the keyword-only path skipped because it read the
                    // declarator as the class.
                    if let Some((tag, tag_range)) = specifiers
                        .children()
                        // **The tag is a `NamedType` here, not a `NameExpr`**: the grammar wraps the specifier's
                        // name in the type node `struct CallInfo` produces, and a search for the bare `NameExpr` found
                        // nothing on the shape this rule was written for. `specifier_name` walks into whichever of
                        // the two it is given.
                        .find(|child| {
                            matches!(
                                CppSyntaxKind::from(child.kind()),
                                CppSyntaxKind::NameExpr | CppSyntaxKind::NamedType
                            )
                        })
                        .and_then(|name| specifier_name(&name))
                    {
                        // **The tag is declared in the nearest enclosing namespace, not in the class.**
                        // [basic.lookup.elab] puts an elaborated-type-specifier's declaration where the *use* is, and
                        // a member declaration is not a scope a tag can live in — binding it in `outer` put a member
                        // named after the tag into every class that wrote `struct X *field;`.
                        let mut target = outer;
                        while self.table.scope(target).is_some_and(|scope| {
                            matches!(scope.kind, ScopeKind::Class | ScopeKind::Enum)
                        }) {
                            let Some(parent) =
                                self.table.scope(target).and_then(|scope| scope.parent)
                            else {
                                break;
                            };
                            target = parent;
                        }
                        // **And only when the scope does not already declare it.** `struct CallInfo { struct CallInfo
                        // *previous; }` names the tag in the *class's own* specifier and again in every field's — and
                        // the class binding is already there, so re-binding it per field would leave the scope with a
                        // dozen declarations of one name and turn a jump into `Ambiguous`. The tag is declared *once*
                        // ([basic.lookup.elab] declares it, it does not redeclare it), so an existing binding is the
                        // answer and this adds nothing.
                        let already = self.table.scope(target).is_some_and(|scope| {
                            scope
                                .bindings
                                .iter()
                                .any(|held| held.name.is(&tag.spelled()) && held.kind == binding)
                        });
                        if !already {
                            self.bind(target, tag, binding, &child, tag_range);
                        }
                        if declarators(node).is_empty() {
                            return SpecifierName::Bound;
                        }
                        continue;
                    }

                    let named_here = self.bare_class_like(&child, outer, inner, binding);

                    // The scoped-enum form carries its name; the forward-declaration form does not, and what
                    // looks like a variable declarator is the class itself.
                    return if named_here {
                        SpecifierName::Bound
                    } else {
                        SpecifierName::InDeclarator(binding)
                    };
                }
                _ => {}
            }
        }

        SpecifierName::None
    }

    /// **The scope a `::`-qualified declaration's qualifier names**, or `None` when this file has not built one.
    ///
    /// The walk is **segment by segment from the outermost**, and each step appends the next name to what it has so
    /// far: a name is found by the qualified spelling a scope records ([`crate::ScopeTree::scope_with_qualified_name`]),
    /// so `a::b::c` is found by looking for `a`, then `a::b`, then `a::b::c`.
    ///
    /// # Why not the whole qualifier at once
    ///
    /// Because a **template argument list** is not part of any scope's name:
    ///
    /// ```text
    /// void Box<int>::grow(int n) { … }     the class's scope is named `Box`, not `Box<int>`
    /// int Box<int>::Inner::deep = 0;       and the nested one is `Box::Inner`
    /// ```
    ///
    /// Asking for `Box<int>::Inner` finds nothing and the declaration falls back to the scope it was written in —
    /// which is the failure this function exists to prevent, and it is silent: the members of `Inner` are then
    /// attributed to the file. Measured: `int Box<int>::count = 0;` declared **no fact at all** and
    /// `int Box<int>::Inner::deep = 0;` produced a fact whose scope was `None`.
    ///
    /// A segment that names no scope ends the walk and answers `None` rather than continuing past it: `a::X<int>::b`
    /// where `a::X` is unknown is unknown, and guessing the last segment that happened to match would attribute the
    /// declaration to an unrelated class of the same name.
    ///
    /// # What a segment is, and why the template arguments are simply dropped
    ///
    /// Read from the **tokens**, not by splitting the text: `<` and `>` nest (`Box<Box<int>>::grow`), and a
    /// character-level split gets that wrong. Everything from a `<` to its matching `>` is skipped, and what is
    /// left is the segment's name — which for `Box<int>` is `Box`, the name the class's scope actually records.
    fn scope_of_a_qualifier(&self, qualifier: &str) -> Option<ScopeId> {
        let mut segments: Vec<String> = Vec::new();
        let mut depth = 0usize;
        let mut letters = String::new();

        for character in qualifier.chars() {
            match character {
                '<' => depth += 1,
                '>' => depth = depth.saturating_sub(1),
                ':' if depth == 0 => {
                    if !letters.is_empty() {
                        segments.push(std::mem::take(&mut letters));
                    }
                }
                _ if depth == 0 => letters.push(character),
                _ => {}
            }
        }

        if !letters.is_empty() {
            segments.push(letters);
        }

        let mut walked = String::new();
        let mut found = None;

        for segment in segments {
            if !walked.is_empty() {
                walked.push_str("::");
            }
            walked.push_str(&segment);

            found = self.table.scope_with_qualified_name(&walked);
            found?;
        }

        found
    }

    /// **A qualifier read the way C++ reads it: from the scope it was written in, then from the file.**
    ///
    /// `scope_of_a_qualifier` matches the name as written against the qualified names the table records, which are
    /// absolute. A definition inside a namespace writes only the part that is relative to it —
    ///
    /// ```text
    /// namespace report {
    ///     class Archive { void put(const Entry& entry); };
    ///     void Archive::put(const Entry& entry) { … }
    /// }
    /// ```
    ///
    /// — so `Archive` matched nothing while the class's qualified name is `report::Archive`, and that one miss sent a
    /// **same-file** definition down the "the class is in a header" path, where it bound nothing and opened no function
    /// scope: reported from a reader as `entry` and `line` "not declared" in their own bodies.
    ///
    /// The order is the language's: the qualifier is looked up in the enclosing scope first (which is what makes a name
    /// inside a namespace find that namespace's class), and only then as an absolute name. Namespaces, classes and the
    /// translation unit only — a function scope contributes no prefix, because its name is not part of any qualified
    /// name.
    fn scope_of_the_qualifier(&self, qualifier: &str, from: ScopeId) -> Option<ScopeId> {
        let mut ancestor = Some(from);
        let mut seen = std::collections::HashSet::new();
        while let Some(scope) = ancestor {
            if !seen.insert(scope) {
                break;
            }
            let Some(data) = self.table.scope(scope) else {
                break;
            };
            let usable = matches!(
                data.kind,
                ScopeKind::TranslationUnit
                    | ScopeKind::Namespace
                    | ScopeKind::Class
                    | ScopeKind::Enum
            );
            if usable && let Some(found) = self.scope_of_a_qualifier_inside(qualifier, scope) {
                return Some(found);
            }
            ancestor = data.parent;
        }
        self.scope_of_a_qualifier(qualifier)
    }

    /// [`ScopeWalker::scope_of_a_qualifier`] with `prefix` — the enclosing scope's qualified name — in front.
    fn scope_of_a_qualifier_inside(&self, qualifier: &str, prefix: ScopeId) -> Option<ScopeId> {
        let base = self.table.qualified_name_of(prefix);
        let mut segments: Vec<String> = Vec::new();
        let mut depth = 0usize;
        let mut letters = String::new();
        for character in qualifier.chars() {
            match character {
                '<' => depth += 1,
                '>' => depth = depth.saturating_sub(1),
                ':' if depth == 0 => {
                    if !letters.is_empty() {
                        segments.push(std::mem::take(&mut letters));
                    }
                }
                _ if depth == 0 => letters.push(character),
                _ => {}
            }
        }
        if !letters.is_empty() {
            segments.push(letters);
        }
        if segments.is_empty() {
            return None;
        }

        let mut walked = base.unwrap_or_default();
        let mut found = None;
        for segment in segments {
            if !walked.is_empty() {
                walked.push_str("::");
            }
            walked.push_str(&segment);
            found = self.table.scope_with_qualified_name(&walked);
            found?;
        }
        found
    }
    /// One declarator: a name, possibly a function, possibly with a body.
    ///
    /// `as_kind` overrides what the declarator would otherwise declare, for the case where a class-like
    /// keyword in the specifiers says the identifier here names a class or an enum rather than a variable.
    ///
    /// `outer` and `inner` are the two scopes the declaration is being read in — the same scope for an ordinary
    /// declaration, and different for a templated one ([`ScopeWalker::declaration_parts`]). A declared name goes in
    /// `outer`, which is where unqualified lookup would find it; a qualified one goes in the scope its qualifier
    /// names, which is why neither parameter is used for it below.
    ///
    /// Returns the function scope it opened, when it opened one, so that the caller can walk a body the grammar
    /// placed beside the declarator rather than inside it.
    /// **The parameters and the body of a definition whose qualifier names nothing here** — see the call site.
    ///
    /// Opens the one scope the function owns and binds nothing into the file: the function's *name* belongs to the
    /// class in another file, and a body is not a place a name can be found from.
    ///
    /// **The scope is named with the definition's own qualified spelling** — `Widget::grow` — because that name is
    /// the only thing the body has to know *which class* it is a member of: `this` is typed from the cursor's
    /// innermost scope's qualified name ([`class_of_the_enclosing_definition`]), so an unnamed scope left `this->`
    /// answering `Unknown(UnknownType("this"))` inside every out-of-line member definition — the ordinary layout of
    /// every `.cpp` there is. Measured in
    /// `tests/completion.rs::a_member_function_defined_in_another_file_sees_its_class`, which is that fixture.
    fn read_the_inside_of_a_foreign_definition(&mut self, node: &CppSyntaxNode, outer: ScopeId) {
        let Some(body) = function_body(node) else {
            return;
        };
        let Some(declarator) = declarators(node).into_iter().next() else {
            return;
        };

        let range = span_of(
            cpp_parser::source_range(declarator.text_range()),
            cpp_parser::source_range(body.text_range()),
        );
        // The qualifier names no scope *here*, but it is still the answer to "which class is this a member of",
        // and it is read by the **same** reader that decided the site is foreign — one implementation, so "is the
        // class here" and "which class is it" cannot come to disagree. (It used to read the specifier sequence
        // directly, which is where the grammar wrote the name while an out-of-class definition's qualified name was
        // mistaken for its return type.)
        let spelled = the_qualified_name_of_a_declaration(node)
            .map(|(qualifier, (name, _))| format!("{qualifier}::{}", name.text()));
        let function = match &spelled {
            Some(spelled) => {
                // **The class this file *does* have, when the qualifier names one.** The path here is for a definition
                // whose class comes from another file, but the same shape is written for a class declared three lines up:
                // `struct W { void f(); }; void W::f() { a = 1; }`. Hanging the function scope off the file scope left
                // the body unable to see the class's members — measured, every out-of-class definition in a file produced
                // *"`a` is not declared"* while `W` was declared above it. The qualifier is what decides, and when it names
                // a scope this file built, that scope is the parent.
                let qualifier = spelled.rsplit_once("::").map(|(qualifier, _)| qualifier);
                let parent = qualifier
                    .and_then(|qualifier| self.scope_of_the_qualifier(qualifier, outer))
                    .unwrap_or(outer);
                self.table.create_named_scope(
                    ScopeKind::Function,
                    Some(parent),
                    Some(range),
                    Some(spelled),
                )
            }
            None => self
                .table
                .create_scope(ScopeKind::Function, Some(outer), Some(range)),
        };

        for parameter_list in parameter_lists(&declarator) {
            self.parameters(&parameter_list, function);
        }

        self.items(&body, function);
    }

    /// **Is `text` a value in `scope` or one of its ancestors?** — the question that tells a variable's initialiser
    /// from a parameter declaration: `std::unique_lock<std::mutex> lock(mutex, …);` declares `lock` only if `mutex` can
    /// be a parameter, and a name this file binds as a variable cannot.
    ///
    /// A **type** name deliberately does not count: `int count(value);` declares a function `count` when `value` is a
    /// type, and the language says so before either reading is looked at.
    fn a_value_named(&self, scope: ScopeId, text: &str) -> bool {
        if text.is_empty() {
            return false;
        }
        let mut current = Some(scope);
        while let Some(id) = current {
            let Some(data) = self.table.scope(id) else {
                return false;
            };
            if data.bindings.iter().any(|binding| {
                matches!(
                    binding.kind,
                    BindingKind::Variable | BindingKind::Enumerator
                ) && binding.name.is(text)
            }) {
                return true;
            }
            current = data.parent;
        }
        false
    }

    fn declarator_as(
        &mut self,
        declarator: &CppSyntaxNode,
        outer: ScopeId,
        inner: ScopeId,
        is_friend: bool,
        as_kind: Option<BindingKind>,
        body: Option<&CppSyntaxNode>,
    ) -> Option<ScopeId> {
        // **`void Widget::grow() { … }` is a member of `Widget`**, and this is where that is decided — for
        // everything written in the declaration and, through the scope the body is walked into, for everything
        // written in the body.
        //
        // # The two spellings, which is the whole difficulty
        //
        // The grammar puts the name of a definition in one of two places, and it depends on whether the name is
        // qualified:
        //
        // ```text
        // void grow(Widget& other) { … }          DeclSpecifierSeq["void"] InitDeclarator["grow(…)"]   → declarator
        // void Widget::grow(Widget& other) { … }  DeclSpecifierSeq["void Widget::grow"] InitDeclarator["(…)"] → specifier
        // ```
        //
        // In the second the declarator holds **only the parameter list**, so a reader that looks for the name in
        // the declarator finds none and gives up — which is exactly what this builder did: the definition opened no
        // function scope, the body was walked into the file scope, and a completion after `other.` inside it
        // declined the whole query because the cursor was in no class at all. Measured: the same cursor *inside*
        // the class body offered the private member correctly, so the only difference was where the definition was
        // written, which is not a difference C++ makes.
        //
        // # The qualifier decides the enclosing scope
        //
        // `Widget::grow` declares `grow` **in `Widget`**, which is also what makes a `private` member nameable in
        // the body. That holds for a variable written the same way (`int Box<int>::count = 0;`) and for a nested
        // class (`int Box<int>::Inner::deep = 0;`), and in all three the answer is the scope the qualifier names.
        // When it names no scope this file has built — a class from a header, a spelling this file only declares —
        // the answer is the scope the declaration was written in, which is where a declaration that qualifies
        // nothing belongs: the honest fallback rather than a failure.
        // The spelling the function scope below carries: a qualified definition writes its name in the specifier, and
        // that is the only place the class it belongs to is written.
        let mut qualified_spelling = None;
        let qualified =
            qualified_declarator_name(declarator).or_else(|| qualified_specifier_name(declarator));
        let (enclosing, name, name_range) = match qualified {
            Some((qualifier, name)) => {
                qualified_spelling = name
                    .0
                    .identifier_text()
                    .map(|name| format!("{qualifier}::{name}"));
                (
                    self.scope_of_the_qualifier(&qualifier, outer)
                        .unwrap_or(outer),
                    name.0,
                    name.1,
                )
            }
            // The name it introduces is the **last** segment — `grow`, not `Widget::grow` — so a qualified
            // spelling is read above rather than by `declared_name`, which refuses one precisely because the
            // unqualified lookup it exists for cannot find it.
            None => match declared_name(declarator) {
                Some((name, name_range)) => (outer, name, name_range),
                // **A friend definition whose name `declared_name` cannot read.** `friend bool
                // operator==(Base const& left, Base const& right) { … }` declares no member — a hidden friend is
                // found by ADL — so returning here was right about the *name* and wrong about everything else: the
                // body was walked into the class scope with no function scope at all, its parameters were bound
                // nowhere, and every use of `left` and `right` read as undeclared. Four findings on
                // `classes.cpp` of the C++ corpus.
                //
                // The name is not needed to read the inside: the scope hangs off `outer`, the parameters go in it,
                // and the body is walked into it by the caller. Nothing is bound here.
                None => {
                    let function = self.table.create_scope(
                        ScopeKind::Function,
                        Some(outer),
                        Some(cpp_parser::source_range(declarator.text_range())),
                    );
                    for parameter_list in parameter_lists(declarator) {
                        self.parameters(&parameter_list, function);
                    }
                    return Some(function);
                }
            },
        };

        // **Is this a function's declarator?** — asked of the grammar's shape: the declarator that *names* something,
        // risen through the declarators around it while there is no pointer between them, and the answer is whether
        // one of them has a parameter list of its own (`noptr-declarator: declarator-id ( params )`).
        //
        // The reading this replaces looked at the **text**: a declarator starting with `(*` or `(&` was a pointer to a
        // function and therefore a variable. That is right for `int (*fp)(int) = negate;` — whose name sits in `(*fp)`
        // with no list, which is why the rule was written — and wrong for a **function returning a function pointer**,
        // which starts the same way: measured on `int (*maker(int a))(int b);`, `maker` came out a `variable` of type
        // `int(int)*`, so its calls, signature help and hover all described an object. The structural question
        // separates them: `maker`'s name is in a declarator with `(int a)`, `fp`'s is in one with no list and a `*`.
        let is_function = the_declarator_that_names_it_has_a_list(declarator);

        // **A class-like keyword in the specifiers settles the question**: whatever the declarator looks like, the
        // identifier is the class or the enum, and `class Widget w;` cannot happen — a second declarator would
        // be a second variable of that type.
        if let Some(kind) = as_kind {
            self.bind(enclosing, name, kind, declarator, name_range);
            return None;
        }

        // **`T x(a, b);` is a function declaration only while `a` and `b` can be parameters.**
        //
        // The grammar cannot tell `std::unique_lock<std::mutex> lock(mutex, std::defer_lock);` from a declaration of
        // a function `lock` — `mutex` alone *looks* like an unnamed parameter of type `mutex`, which is how `void f(int);`
        // writes one. What settles it is the one thing a parameter list cannot hold: a **value**. `mutex` is a variable
        // of this file, so the parentheses are an initialiser and `lock` is an object.
        //
        // Measured on `test_cpp/src/concurrency.cpp:32`: hovering the variable answered "lock — a function, declared in a
        // function body", and every `lock.lock()` in the block after it resolved against that phantom. `mutex` at line
        // 20 is a variable of the same file, which is exactly the evidence the standard's rule needs.
        //
        // Only a declaration inside a **block** is ambiguous, and one name is enough: `T x(a, b)` is a declaration only
        // if *every* entry parses as a parameter, so a single known value refuses it.
        let parentheses_hold_a_value = is_function
            && declarator
                .ancestors()
                .any(|ancestor| cpp_parser::CppCompoundStat::can_cast(ancestor.kind().into()))
            && parameter_lists(declarator).iter().any(|list| {
                list.children().any(|parameter| {
                    let Some(named) = parameter
                        .descendants()
                        .find(|child| cpp_parser::CppNameExpr::can_cast(child.kind().into()))
                    else {
                        return false;
                    };
                    let spelled = named.text().to_string();
                    let last = spelled.rsplit("::").next().unwrap_or(&spelled).trim();
                    // A qualified name is not this file's to answer (`std::defer_lock` is a constant in a header);
                    // the unqualified ones are, and that is where the variable `mutex` lives.
                    !spelled.contains("::") && self.a_value_named(enclosing, last)
                })
            });

        if !is_function || parentheses_hold_a_value {
            // A variable is declared in the scope it is written in, initialiser or not. The initialiser is not
            // a scope of its own: `int x = x;` refers to an earlier `x`, so the name being declared and the
            // name being read live in the same scope, and a scope around the initialiser would put the read
            // outside the scope of the declaration it reads.
            self.bind(
                enclosing,
                name,
                BindingKind::Variable,
                declarator,
                name_range,
            );
            return None;
        }

        // **A function whose name is its own class's is a constructor**, wherever the definition is written.
        //
        // `Pattern::Pattern() { … }` at file scope repeats the class's name, and the class is not in hand at this
        // point — but its *spelling* is: a qualified declarator whose last two segments are equal is the language's
        // own definition of a constructor ([class.ctor]: a constructor has no name of its own). The class-body
        // conversion below reaches the same answer for the declaration, and this is the other half.
        //
        // Measured: the out-of-class definition was bound as `Function`, so a highlighter drew the class's name as a
        // *method* while the constructor declared in the class body was already `Constructor` — one name, two colours.
        let kind = if is_a_constructor_declarator(declarator) {
            BindingKind::Constructor
        } else {
            function_binding_kind(&name)
        };
        // **A friend declaration declares no member** — see the note on the `declared_name` fallback above; the
        // scope below is still opened, because a friend *definition* owns its parameters and its body.
        if !is_friend {
            self.bind(enclosing, name, kind, declarator, name_range);
        }

        // A declaration with nothing to put in a scope opens none. `int size() const;` is a member function
        // declaration: its parameters are a *type*, not names, and it has no body — so a scope for it would be
        // an empty one that a consumer reports as "this function has no locals" rather than "this function was
        // not defined here".
        let has_parameters = parameter_lists(declarator)
            .iter()
            .any(|list| list.children().next().is_some());

        if body.is_none() && !has_parameters {
            return None;
        }

        // The parameters and the body share one scope, which is what C++ does: a parameter is visible in the
        // body and not outside it, and the body does not nest inside the parameter list. The scope hangs off
        // `inner` so that a templated function's parameters can see the template's parameters — and off
        // `enclosing` instead when a qualifier named a class, which is the `Widget::grow` case above.
        let parent = if enclosing == outer { inner } else { enclosing };
        //
        // The range reaches to the end of the body when there is one, because a scope is looked up by offset:
        // a cursor on a local declaration is inside the body, which is *past* the declarator, and a scope that
        // ended at the parameter list would leave the whole body resolving to the enclosing class.
        let range = match body {
            Some(body) => span_of(
                cpp_parser::source_range(declarator.text_range()),
                cpp_parser::source_range(body.text_range()),
            ),
            None => cpp_parser::source_range(declarator.text_range()),
        };

        // **`enclosing`, not `inner`.** For an ordinary declaration the two are the same scope and this makes no
        // difference; for a `Widget::grow` definition written outside its class they are not, and the difference
        // is the whole point of the qualified reading above: the body has to hang off `Widget` for the cursor in
        // it to be *in* `Widget` — which is what makes a `private` member nameable there. Measured with `inner`:
        // the cursor's class list was empty and a completion after `other.` offered four public members where
        // five were nameable.
        // **And the scope carries the definition's qualified spelling.** A qualified definition writes its name in the
        // *specifier* (`inline void Widget::grow(…)`), so `declared_name` reads none from the declarator and the scope was
        // left unnamed. That name is what `class_of_the_enclosing_definition` reads to answer `this`, and what a reader sees
        // as the function's own name. Measured on MSVC's `comutil.h`: `inline _bstr_t::_bstr_t() …` produced an unnamed
        // function scope, so the member-access check could not tell it was inside `_bstr_t` and reported
        // "`m_Data` is private in the class that declares it, and this is not that class's own code" — inside that class's
        // own constructor.
        let function = match qualified_spelling {
            Some(spelling) => self.table.create_named_scope(
                ScopeKind::Function,
                Some(parent),
                Some(range),
                Some(&spelling),
            ),
            None => self
                .table
                .create_scope(ScopeKind::Function, Some(parent), Some(range)),
        };

        for parameter_list in parameter_lists(declarator) {
            self.parameters(&parameter_list, function);
        }

        Some(function)
    }

    /// A class-like keyword written without a declarator to carry its name: `enum class Color { Red };`.
    ///
    /// Returns whether the specifier **named** the entity itself, which is what tells the two bare-keyword
    /// forms apart and is the only thing the caller needs to know:
    ///
    /// * `enum class Color { ... }` — the name and body are children of the specifier, so it is named here and
    ///   the specifier's declarator list is empty.
    /// * `class Widget;` — the specifier holds only the keyword, and the identifier in the *declarator* is the
    ///   class itself, so the caller must not read it as a variable.
    fn bare_class_like(
        &mut self,
        specifier: &CppSyntaxNode,
        outer: ScopeId,
        inner: ScopeId,
        binding: BindingKind,
    ) -> bool {
        let scope_kind = match binding {
            BindingKind::Enum => ScopeKind::Enum,
            _ => ScopeKind::Class,
        };

        // **The specifier names the entity itself, and `declared_name` cannot see it.** `enum class Color { … }` is
        // a `BuiltinType` specifier whose children are the keywords, a `NameExpr` and the body: there is no
        // declarator to walk, and the fallback — a node's last *direct token* identifier — finds nothing, because
        // every identifier here is inside a child node. So the name is read from the `NameExpr` the specifier
        // holds, and the scope below is created **named**: an unnamed enum scope is what made every enumerator's
        // fact `scope: None`, which is why `E::Yes` never resolved, `Yes` was drawn as a variable rather than as an
        // enum member, and a bare `Yes` was reachable from anywhere in the project.
        let named = specifier_name(specifier).or_else(|| declared_name(specifier));
        let named_here = named.is_some();
        let named_text = named.as_ref().map(|(name, _)| name.kind.text());

        if let Some((name, name_range)) = named {
            self.bind(outer, name, binding, specifier, name_range);
        }

        // A forward declaration — `class Widget;` — has no body, so no scope: the caller reads the name from
        // the declarator and there is nothing else here.
        let has_body = specifier
            .descendants()
            .any(|child| cpp_parser::CppCompoundStat::can_cast(child.kind().into()));

        if !has_body {
            return named_here;
        }

        let scope = self.table.create_named_scope(
            scope_kind,
            Some(inner),
            Some(cpp_parser::source_range(specifier.text_range())),
            named_text.as_deref(),
        );

        // The enumerators, for an enum written with a body. A plain `enum Color { Red };` reaches here with
        // `Color` in its declarator instead, and the enumerators still belong to this scope.
        for body in specifier
            .descendants()
            .filter(|child| cpp_parser::CppCompoundStat::can_cast(child.kind().into()))
        {
            self.enumerators(&body, scope);
        }

        named_here
    }

    /// The parameters of a function declarator.
    fn parameters(&mut self, list: &CppSyntaxNode, scope: ScopeId) {
        for (declarator, declared) in parameters_of(list) {
            // An unnamed parameter — `void f(int);` — declares nothing, which is ordinary C++ rather than a gap.
            if let Some((name, name_range)) = declared {
                self.bind(scope, name, BindingKind::Variable, &declarator, name_range);
            }
        }
    }

    /// A construct that opens a scope for a statement: a loop, a branch, a `switch`, a `try`.
    ///
    /// The scope is what makes `for (int i = 0; ...)` bind `i` where the loop can see it and the enclosing
    /// block cannot, and what makes two sibling branches free to declare the same name.
    fn statement_scope(&mut self, node: &CppSyntaxNode, parent: ScopeId) {
        let scope = self.table.create_scope(
            ScopeKind::Block,
            Some(parent),
            Some(cpp_parser::source_range(node.text_range())),
        );

        self.items(node, scope);
    }

    /// `done:` — a label, which lives in a name space of its own.
    /// **A lambda's scope**: the parameters it writes, and the body they are in scope for.
    ///
    /// The node is a child of a declarator — `auto f = [](double a) { … };` is
    /// `InitDeclarator(Declarator(… LambdaExpr …))` — and no walk reached it: `item()` had no arm for it, so
    /// every declaration written in a lambda body was missing from the scope tree and therefore from the index.
    /// Measured on the fixture: 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`, and the lambda's parameter `a` was missing too.
    ///
    /// A `CompoundStat` would open a `Block` on its own, but a lambda is a *function* without a name: its
    /// parameters belong in a scope the body is inside, which is why this is `ScopeKind::Lambda` and not a block.
    fn lambda(&mut self, node: &CppSyntaxNode, scope: ScopeId) {
        let inner = self.table.create_scope(
            ScopeKind::Lambda,
            Some(scope),
            Some(cpp_parser::source_range(node.text_range())),
        );
        // **A lambda may write its own template parameter list** — `[]<typename T>(T value) { … }`, C++20's template
        // lambda. Its parameters are bound in a scope of their own, exactly as a `template <…>` head's are, and the
        // parameter list and the body are walked **inside** it so that `T` is visible where the lambda is written and
        // not outside. Measured: `T` was the one token in `[]<typename T>` that the semantic pass had no declaration
        // for, and a hover on it had nothing to say.
        let mut inside = inner;
        if let Some(list) = node
            .children()
            .find(|child| cpp_parser::CppTemplateParamList::can_cast(child.kind().into()))
        {
            let parameters = self.table.create_scope(
                ScopeKind::TemplateParameters,
                Some(inner),
                Some(cpp_parser::source_range(list.text_range())),
            );
            self.template_parameters(&list, parameters);
            inside = parameters;
        }
        for list in node
            .children()
            .filter(|child| cpp_parser::CppParamList::can_cast(child.kind().into()))
        {
            self.parameters(&list, inside);
        }
        for body in node
            .children()
            .filter(|child| cpp_parser::CppCompoundStat::can_cast(child.kind().into()))
        {
            self.items(&body, inside);
        }
    }

    fn label(&mut self, node: &CppSyntaxNode, scope: ScopeId) {
        if let Some((name, name_range)) = declared_name(node) {
            self.bind(scope, name, BindingKind::Label, node, name_range);
        }
    }

    /// Add a binding, ignoring a scope that cannot hold it.
    ///
    /// The refusal is the table's, and it is deliberate rather than defensive: a label in a namespace and a
    /// variable in a template parameter list are constructs that do not exist, so a binding that reaches one is
    /// a sign the walk misread the tree. Dropping it leaves a gap a consumer can see; placing it would make
    /// the scope report a name that cannot be used there.
    fn bind(
        &mut self,
        scope: ScopeId,
        name: Name,
        kind: BindingKind,
        node: &CppSyntaxNode,
        name_range: cpp_parser::SourceRange,
    ) {
        self.table.add_binding(
            scope,
            Binding {
                name,
                kind,
                // **The declaration, without the trivia written after it.**
                //
                // A node absorbs the whitespace that follows its last token — see the grammar's note on
                // `parse_access_specifier` for why that is usually what you want — so `node.text_range()` for
                // `struct String;` runs through the newline, and the field stops being "the whole declaration" and
                // becomes "the declaration and whatever was written after it". Measured from a fact:
                //
                // ```text
                //   struct String;       Type "String" range 0..15 = "struct String;\n"
                //   struct S { int n; }  Type "S"      range 0..19 = "struct S { int n; }"
                // ```
                //
                // The second is right; the first included a newline that belongs to the file. Trimmed here rather
                // than narrowed to the name, because [`crate::DeclFact::range`] is documented as *"the whole
                // declaration, for a go-to-definition highlight"* — that is the answer callers want, minus the trivia.
                range: without_trailing_trivia(node),
                name_range,
                scope,
                origin: None,
            },
        );
    }
}

/// **A node's span, backed up over the trivia it absorbed** — see the note where this is called.
///
/// # Why this descends instead of scanning the node's own children
///
/// The first version walked the node's **direct** children backwards and stopped at the first that was not
/// trivia — and for every braced declaration that stopped immediately, because the last child is the body:
///
/// ```text
/// Syntax(NamespaceDecl)@0..55
///   Token(NamespaceKeyword)@0..9
///   Syntax(NameExpr)@10..12
///   Syntax(CompoundStat)@12..55        ← not trivia, so the scan stopped here
///     …
///     Token(Newline)@53..55 "\r\n"     ← …and this is where the trivia actually is
/// ```
///
/// The trailing newline is a child of the **body**, so it survived, and a namespace's declared range ran to the end
/// of the file. Measured: `namespace ns { … }` in a 55-byte file bound as `0..55` while the `}` ends at 53, which
/// made every outline entry for a namespace, class or function one line too long — a fold that swallows the blank
/// line after it, and a breadcrumb whose "whole declaration" is really "the rest of the file".
///
/// So the walk follows the chain of **last** children down to the deepest one that holds a real token, which is
/// where the declaration actually ends, and takes the trivia off from there.
pub(crate) fn without_trailing_trivia(node: &CppSyntaxNode) -> cpp_parser::SourceRange {
    let range = cpp_parser::source_range(node.text_range());
    let end = significant_end(node).unwrap_or(range.end_offset());
    cpp_parser::SourceRange::new(
        range.start_offset,
        end.max(range.start_offset) - range.start_offset,
    )
}

/// Where `node`'s last **significant** token ends, descending through trailing child nodes.
///
/// `None` when the node holds nothing but trivia, which the caller reads as "keep the node's own span": there is
/// then nothing to trim to.
fn significant_end(node: &CppSyntaxNode) -> Option<usize> {
    // Reversed, so the first significant thing found is the last one written.
    for element in node
        .children_with_tokens()
        .collect::<Vec<_>>()
        .into_iter()
        .rev()
    {
        match element.clone().into_token() {
            Some(token) => {
                if !cpp_parser::is_trivia(cpp_parser::CppTokenKind::from(token.kind())) {
                    return Some(cpp_parser::source_range(token.text_range()).end_offset());
                }
                // Trivia: this token does not end the declaration, so keep looking backwards.
            }
            None => {
                let inner = element
                    .into_node()
                    .expect("a node-or-token is one of the two");
                match significant_end(&inner) {
                    // The child holds something real: the declaration ends where that ends.
                    Some(inner_end) => return Some(inner_end),
                    // All trivia — a comment between two members — so keep looking backwards.
                    None => continue,
                }
            }
        }
    }

    // Every child, and every leaf inside them, was trivia. The caller reads the `None` as "keep the node's own
    // span", which is the only honest answer when there is nothing significant to trim to.
    None
}

/// Where the name of a class-like declaration was written.
///
/// The three shapes C++ spells these in, and the reason a single "did the specifier name it" boolean is not
/// enough: the name is in a different place in each, and reading the wrong place binds the wrong name — which
/// is how `class Widget;` ends up declaring a variable called `Widget`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SpecifierName {
    /// No class-like specifier here, so the declarators declare ordinary names.
    None,
    /// The specifier carried the name, and the declarators hold variables of that type.
    Bound,
    /// The specifier had only the keyword: the identifier in the declarator **is** the entity.
    InDeclarator(BindingKind),
}

/// The body of a function, which the grammar places beside or around the declarator rather than inside it.
///
/// Several shapes reach here and all of them occur in real code:
///
/// ```text
/// int f() { ... }                    the body is a direct child of the declaration
/// struct S { void m() { ... } };     inside a class body, inside the specifier sequence
/// void f() { ... }                   the body hangs off the *declarator*, which is not a direct child
/// S(int a) : x(a) { ... }            a constructor, whose member-initializer list comes first
/// ```
///
/// A **constructor's** declaration is a wrapper: the grammar closes the declaration once its name, parameter list and
/// member-initializer list are read, then reopens it around the body with `CompleteMarker::precede`, so the body is a
/// direct child of the declaration that carries the initializer list — the first arm finds it, and no special case is
/// needed.
///
/// It used to need one, because the grammar put the body **beside** the declaration:
/// `Declaration@11..26` with `CompoundStat@26..42` as a following sibling. That is what this function used to look
/// for, and what made a constructor open a scope its parameters were bound in while reaching none of them — the
/// scope's range was the declarator alone. The grammar fix is `parse_constructor_declaration`; this is the reading it
/// left behind.
///
/// The search is over the declarators rather than over the whole subtree, so a `CompoundStat` belonging to
/// something else — a lambda's body in an initialiser — is not mistaken for this function's.
fn function_body(node: &CppSyntaxNode) -> Option<CppSyntaxNode> {
    if let Some(direct) = first_child(node, CppSyntaxKind::CompoundStat) {
        return Some(direct);
    }

    for declarator in declarators(node) {
        for child in declarator.children() {
            if cpp_parser::CppCompoundStat::can_cast(child.kind().into()) {
                return Some(child);
            }
        }
    }

    // A member function's body is inside the class body, which is inside the specifier sequence.
    let specifiers = first_child(node, CppSyntaxKind::DeclSpecifierSeq)?;
    for child in specifiers.descendants() {
        if !cpp_parser::CppClassBody::can_cast(child.kind().into()) {
            continue;
        }

        for member in child.children() {
            if let Some(body) = function_body(&member) {
                return Some(body);
            }
        }
    }

    None
}

/// The parameter lists of a function declarator, outermost first.
///
/// Searched through the declarator's subtree rather than among its direct children, because the grammar does
/// not put them in one fixed place: `void f(int)` has the list one level down inside a nested `Declarator`,
/// while `void (*f)(int)` has it inside a `FunctionType`, and a search that assumed either shape would bind no
/// parameters at all for the other.
///
/// The walk stops at a **body**, which is what keeps a parameter list belonging to a nested lambda or a nested
/// class out of this function's scope: `void f() { auto g = [](int inner) {}; }` must not put `inner` in `f`.
/// A list *inside* another parameter list — a function-pointer parameter — is left alone for a different
/// reason: its names belong to the type, not to this function.
fn parameter_lists(declarator: &CppSyntaxNode) -> Vec<CppSyntaxNode> {
    // **The name's own lists, and only those** — see [`the_lists_of_the_name`], which is the same walk the
    // function-or-variable question uses. The subtree scan this replaces collected the lists of *types* too:
    // `int (*maker(int a))(int b);` bound `b` — a parameter of the returned pointer's type — as a file-scope variable.
    if let Some(naming) = the_naming_declarator(declarator) {
        return the_lists_of_the_name(naming).collect();
    }

    // **A declarator with no name** — a qualified definition (`void Widget::grow(int)`), whose name the specifier
    // sequence took — keeps the subtree reading, which is the only thing that can find its lists. A body is skipped so
    // that a nested lambda's or a nested class's parameters are not this function's.
    fn collect(node: &CppSyntaxNode, out: &mut Vec<CppSyntaxNode>) {
        for child in node.children() {
            match CppSyntaxKind::from(child.kind()) {
                CppSyntaxKind::ParameterList => out.push(child),
                CppSyntaxKind::CompoundStat | CppSyntaxKind::ClassBody => {}
                CppSyntaxKind::Declarator => collect(&child, out),
                _ => {}
            }
        }
    }

    let mut lists = Vec::new();
    collect(declarator, &mut lists);
    lists
}

/// **Does this declarator spell `Class::Class`?** — a constructor's out-of-class definition.
///
/// A destructor (`Class::~Class`) already has its own kind from the name. This is the spelling that differs from an
/// ordinary member definition (`Class::Member`) only in that the last two segments are equal, which is exactly the
/// language's rule: a constructor is a function with no name of its own, written with its class's.
///
/// The class segment may carry template arguments (`Box<int>::Box`), which are not part of the name being compared.
fn is_a_constructor_declarator(declarator: &CppSyntaxNode) -> bool {
    // **The two segments, as the tree reads them.** The declarator's name is a `CppNameExpr` whose segments are its
    // children, and `qualified_declarator_name` / `qualified_specifier_name` already return the qualifier and the
    // introduced name separately — so the last segment is a `Name`, not a slice of the declarator's whole spelling. The
    // previous version searched for a name node and re-split its text, which also matched a `::` inside a template
    // argument, and depended on `trim` for a `::` written after a newline.
    let Some((qualifier, (name, _))) =
        qualified_declarator_name(declarator).or_else(|| qualified_specifier_name(declarator))
    else {
        return false;
    };
    let Some(last) = name.identifier_text() else {
        return false;
    };
    let class = qualifier.rsplit("::").next().unwrap_or(qualifier.as_str());
    let class = class.split('<').next().unwrap_or(class).trim();
    !class.is_empty() && last == class
}
/// The name is what decides: a constructor and an ordinary function are spelled the same way and differ only in
/// that a constructor's name is its class's, which this layer cannot know — a class is being built at the same
/// time. What *is* readable from the name alone is the three special forms, and those are worth separating
/// because a consumer treats them differently: a destructor is not found by ordinary lookup, and an operator is
/// found by the operator it is.
fn function_binding_kind(name: &Name) -> BindingKind {
    match name.kind {
        crate::symbol::NameKind::Destructor(_) => BindingKind::Destructor,
        crate::symbol::NameKind::Conversion(_) => BindingKind::ConversionFunction,
        crate::symbol::NameKind::Operator(_) => BindingKind::OperatorFunction,
        crate::symbol::NameKind::Literal(_) => BindingKind::LiteralOperator,
        crate::symbol::NameKind::Identifier(_) => BindingKind::Function,
    }
}

/// **Does this declaration hold a body that declares members?** — an enum's enumerators, a class's members.
///
/// The question [`ScopeWalker::declaration`] asks before walking a declaration that names nothing: `enum { A, B };` and
/// `struct { int x; } s;` both declare members under a name of their own (`s` for the second), and an unnamed one
/// still declares them.
fn declares_a_body(node: &CppSyntaxNode) -> bool {
    node.descendants().any(|child| {
        matches!(
            CppSyntaxKind::from(child.kind()),
            CppSyntaxKind::EnumDef
                | CppSyntaxKind::EnumClassDef
                | CppSyntaxKind::ClassDef
                | CppSyntaxKind::StructDef
                | CppSyntaxKind::UnionDef
        )
    })
}

/// Does this `Declaration` go through the declaration path **without declaring anything here**?
///
/// The question the most vexing parse forces on any parser without a table of type names. `f(x);` — a call —
/// and `int(x);` — a declaration of `x` — are the same tokens, so the grammar reads both as a declaration; what
/// distinguishes them at this layer is that the call has **no declarator name**, because the identifier sits in
/// a parenthesised declarator rather than where a declared name goes.
///
/// Answered by asking the AST layer rather than by walking the tree again: `CppDeclaration::get_name` is
/// already the "which name does this declare" rule, and it looks only where a name may be. A second
/// implementation here would be free to disagree with the first, and consumers use both.
///
/// # The shape `get_name` cannot answer for
///
/// A declaration whose name is **`::`-qualified**. The grammar puts `void Widget::grow(int)`'s name in the specifier
/// sequence — the declarator holds only `(int)` — so `get_name` finds nothing and answers `None`, the same answer it
/// gives a call statement. Those declarations are handled **before** this is asked
/// ([`ScopeWalker::names_a_scope_this_file_has`]), because the answer for them is never "unnamed here": they are
/// either a member of a class this file declares or a declaration about a scope this file does not have, and the
/// second is the only case that reaches this function's caller as a `true`.
///
/// `false` for every node that is not a `Declaration`, because the other declaration kinds state their name
/// differently and already handle an absent one — an anonymous namespace, an unnamed `class {}`.
fn is_unnamed_declaration(node: &CppSyntaxNode) -> bool {
    if !cpp_parser::CppDeclaration::can_cast(node.kind().into()) {
        return false;
    }

    // **An operator declaration names something and has no identifier.** `int operator*() const;` is a declaration
    // the AST calls nameless (`get_name_text` answers `None`, the same answer `f(x);` gives), so it was skipped
    // before any name was read — and a class's operators were never members of it. Measured: `members_of("Money")`
    // listed only the data member, and every operator rule was looking for a fact that had never been built.
    //
    // The keyword is looked for **outside the initializer**, because `int y = x.operator+();` holds one as a call
    // and names `y`: what makes the declaration an operator's is that the keyword is in its own declarator.
    let declares_an_operator = node
        .children()
        .filter(|child| !cpp_parser::CppInitializer::can_cast(child.kind().into()))
        .flat_map(|child| child.descendants_with_tokens())
        .filter_map(|element| element.into_token())
        .any(|token| CppTokenKind::from(token.kind()) == CppTokenKind::OperatorKeyword);
    if declares_an_operator {
        return false;
    }

    // **A declarator that names something settles it too.** `int (*fp)(int) = negate;` has no name in the specifier, and the
    // AST's own name reader answers `None` for a parenthesised declarator — so this called the declaration "unnamed", the
    // walker stopped before reading the declarator, and the variable was never declared: measured, `definitions("fp")`
    // answered `NotDeclaredHere` inside the function that declares it, and the undeclared-identifier check reported the
    // file's own variable.
    if declarators(node)
        .iter()
        .any(|declarator| declared_name(declarator).is_some())
    {
        return false;
    }

    match cpp_parser::CppDeclaration::cast(node.clone()) {
        Some(declaration) => declaration.get_name_text().is_none(),
        // Not castable, so the AST layer has no opinion and this layer should not invent one.
        None => false,
    }
}

/// **Does this declaration name a class or namespace this file has built?**
/// **Does this declaration name something through a `::`-qualified declarator?**
///
/// `void Box<int>::grow(int n) { … }` and `int Box<int>::count = 0;` both declare a name, and the AST's
/// `get_name_text` answers `None` for both — the same answer it gives `f(x);`, which declares nothing. Three
/// conditions together tell them apart, and each is here because leaving it out accepts something it should not:
///
/// ```text
/// a `::` in a name under the specifier sequence   `void Box<int>::grow` — and NOT `f(x);`, whose `x` is an
///                                                 argument the specifier sequence never mentions
/// …outside the declarators                        a parameter's type is not this declaration's name:
///                                                 `int f(std::string s);` declares `f`
/// …and a declarator with no name of its own       `ns::Widget w;` writes a qualified *type* and a declarator
///                                                 that names `w`, and that is the ordinary path's reading
/// ```
///
/// The second condition is a walk that stops at every `Declarator`, which is what keeps a qualified type **inside**
/// a declarator — a parameter, a return type — from being read as the declaration's own name.
fn declaration_is_qualified(node: &CppSyntaxNode) -> bool {
    let Some(specifiers) = first_child(node, CppSyntaxKind::DeclSpecifierSeq) else {
        return false;
    };

    if !mentions_a_qualified_name(&specifiers, true) {
        return false;
    }

    // A declarator that names something is the declaration's name; what is left is a declaration whose name was
    // written where a type goes.
    //
    // **An `operator` keyword in a declarator is a name too.** The AST's reader answers `None` for an operator
    // (`get_name_text` looks for an identifier), so "no identifier outside a parameter list" is true of it and of a
    // bare parameter list alike — and the difference is the keyword. Measured on a class in
    // `test_cpp/src/containers.cpp:63`: `std::size_t operator()(std::string const& value) const { … }` was read as a
    // **`::`-qualified declaration** — the `::` of the *return type* is in the specifier sequence and outside every
    // declarator — so the walk asked whether `std::size_t` named a scope this file had built, got `false`, and bound
    // nothing. `Hashed` had no member and `containers.cpp` had 43 declarations without its operator; the hover on
    // `operator` then fell through to the keyword's meaning. The pair that named the cause: `bool operator<(…)` was
    // fine and `std::size_t operator<(…)` was not — the return type, not the operator.
    !declarators(node)
        .iter()
        .any(|declarator| named_in_a_declarator(declarator) || spells_an_operator(declarator))
}

/// Does this declarator spell an operator's name — `operator<`, `operator()`, `operator bool`?
///
/// The keyword anywhere in the declarator, which is where a declared name lives. `int y = x.operator+();` puts one in
/// an *initializer*, which is not this declaration's name — the caller excludes the initializer by asking the
/// declarators, not the declaration.
pub(crate) fn spells_an_operator(declarator: &CppSyntaxNode) -> bool {
    declarator
        .descendants_with_tokens()
        .filter_map(|element| element.into_token())
        .any(|token| CppTokenKind::from(token.kind()) == CppTokenKind::OperatorKeyword)
}

/// Does anything written **outside a declarator** in this subtree spell a `::`-qualified name?
///
/// `inside_a_declarator` says whether the walk is already inside one: the specifier sequence starts outside, and
/// every `Declarator` puts the walk inside for the rest of its subtree.
///
/// # It stops at the bodies and at the nested declarations, and that is the whole correctness of it
///
/// The question is about **this declaration's own name**, which is written either in the specifier sequence or in
/// a declarator — both of them outside every body. Everything a body encloses is a different declaration's text,
/// and a qualified name in there says nothing about this one.
///
/// Measured, and it is why `std::string` could not be found: `class basic_string { … }` is 94 KB of members, and
/// members write qualified names all over it (`allocator_traits<_Alloc>::…`, `pointer_traits<pointer>::…`). So the
/// walk found a `::`, called the class definition a **qualified declaration**, asked whether the qualifier named a
/// scope *this file* had built, got `false`, and returned before binding anything. The class then had no binding
/// and therefore no fact: `cooked(<xstring>)` held 157 declarations and `basic_string` was not one of them,
/// because `declaration_is_qualified` had thrown the definition away.
///
/// Note that the declarator rule alone does not cover this — a *class body* is not inside a declarator, which is
/// exactly how a member's `X::y` came to be read as the class's own name.
fn mentions_a_qualified_name(node: &CppSyntaxNode, outside_a_declarator: bool) -> bool {
    for child in node.children() {
        let kind = CppSyntaxKind::from(child.kind());

        // Another declaration's text, or a part of this one that is not its name. This declaration's name cannot
        // be in there, and a `::` in it is something else's business.
        //
        // **`BaseSpecifier` is the second half of the lesson `ClassBody` taught**, and it is the same mistake one
        // node over: `struct W : Base<A::B> {};` writes `A::B` in its specifier sequence, the walk found a `::`,
        // called the declaration qualified, asked whether `A::B` named a scope *this file* had built, got `false`,
        // and returned before binding anything — so `W` had no binding and therefore **no fact at all**.
        //
        // Measured, and it is why the standard library loses whole classes: a base clause is where a class
        // template names the template it derives from, and qualified names are the ordinary way to write that —
        // `struct allocator_traits : conditional_t<…, _Default_allocator_traits<_Alloc>, …>` in MSVC's
        // `xmemory:755` is the one that led here, and it produced no fact for `allocator_traits` while every
        // unqualified base beside it did. The parser is not at fault: the tree is
        // `StructDef > [NameExpr(W), Colon, BaseSpecifier(Base<A::B>)]` and it parses with no errors.
        if matches!(
            kind,
            CppSyntaxKind::ClassBody
                | CppSyntaxKind::Declaration
                | CppSyntaxKind::CompoundStat
                | CppSyntaxKind::BaseSpecifier
        ) {
            continue;
        }

        if outside_a_declarator && kind == CppSyntaxKind::NameExpr && is_qualified(&child) {
            return true;
        }

        let still_outside = outside_a_declarator && kind != CppSyntaxKind::Declarator;
        if mentions_a_qualified_name(&child, still_outside) {
            return true;
        }
    }

    false
}

/// Does this declarator hold a name of its own — an identifier that is not inside a parameter list?
///
/// **The identifier token, not the `NameExpr`**, because a qualified name in the specifier sequence is also a
/// `NameExpr` — and the two are exactly what this whole reading has to tell apart. What a declarator that names
/// something has, and a bare parameter list does not, is an identifier written in it.
fn named_in_a_declarator(declarator: &CppSyntaxNode) -> bool {
    for child in declarator.children_with_tokens() {
        if let Some(token) = child.clone().into_token() {
            if CppTokenKind::from(token.kind()) == CppTokenKind::Identifier {
                return true;
            }

            continue;
        }

        if let Some(node) = child.into_node() {
            // A parameter list is a type, not this declarator's name, and so is everything below one.
            if cpp_parser::CppParamList::can_cast(node.kind().into()) {
                continue;
            }

            if named_in_a_declarator(&node) {
                return true;
            }
        }
    }

    false
}

/// The first direct child of a kind.
fn first_child(node: &CppSyntaxNode, kind: CppSyntaxKind) -> Option<CppSyntaxNode> {
    node.children()
        .find(|child| CppSyntaxKind::from(child.kind()) == kind)
}

/// The name a `MacroCall` invokes, as the file spells it.
///
/// The shape is `MacroCall > NameExpr > Identifier`, which every rule that reads an invocation produces
/// (`parse_macro_call`, `parse_a_macro_that_stands_for_a_declaration`, …), and the first identifier is the name in
/// all of them: what may follow inside the `NameExpr` is trivia, and what may follow *outside* it is the macro's
/// arguments or nothing at all.
fn invocation_name(node: &CppSyntaxNode) -> Option<String> {
    let name = first_child(node, CppSyntaxKind::NameExpr)?;

    name.children_with_tokens()
        .filter_map(|child| child.into_token())
        .find(|token| CppTokenKind::from(token.kind()) == CppTokenKind::Identifier)
        .map(|token| token.text().to_string())
}

/// Which kind of entity a bare class-like keyword introduces, if that is what this specifier is.
///
/// `class Widget;` and `enum class Color { ... }` reach the scope walker as a `BuiltinType` holding the
/// keyword, rather than as the `ClassDef` and `EnumClassDef` nodes that a definition with a declarator
/// produces. The keyword is therefore what identifies them, and the caller needs to know *which* keyword:
/// a name found here is a class in the first case and an enumerator-bearing enum in the second.
///
/// `None` for every other builtin type — `int`, `unsigned char`, `void` — which is the case that has to stay
/// cheap, because most specifiers are one.
fn class_like_binding_of(specifier: &CppSyntaxNode) -> Option<BindingKind> {
    let mut is_enum = false;
    let mut is_class_like = false;

    for token in specifier
        .children_with_tokens()
        .filter_map(|child| child.into_token())
    {
        match CppTokenKind::from(token.kind()) {
            // `enum class E` and `enum struct E` carry both keywords, and the entity is an enum: the `class`
            // there selects the scoped form and does not introduce a class.
            CppTokenKind::EnumKeyword => is_enum = true,
            CppTokenKind::ClassKeyword
            | CppTokenKind::StructKeyword
            | CppTokenKind::UnionKeyword => {
                is_class_like = true;
            }
            _ => {}
        }
    }

    match (is_enum, is_class_like) {
        (true, _) => Some(BindingKind::Enum),
        (false, true) => Some(BindingKind::Class),
        (false, false) => None,
    }
}

/// The init-declarators of a declaration, or the declarators when there is no init wrapper.
///
/// `int a, b;` has two init-declarators; `int a;` has one; a declaration of a class has neither. The fallback
/// matters for the shapes the grammar produces without an initialiser, where the declarator is a direct child.
///
/// # The nested `Declaration` a constructor is written with
///
/// A constructor's declaration is a wrapper: the grammar reads the name, the parameter list and the member-initializer
/// list as one declaration, then reopens a declaration around the body with `CompleteMarker::precede` — so the node
/// this is asked about holds a **`Declaration`** child that holds the declarator, and a search of the direct children
/// finds none:
///
/// ```text
/// Declaration@11..42            ← the wrapper, whose children this function is asked about
///   Declaration@11..26          ← the declaration proper: Declarator, MemberInitializer
///   CompoundStat@26..42         ← the body `precede` wrapped it with
/// ```
///
/// Measured on `struct Name { Name(const int f) : first(f) { … } };`: with no declarator found, no function scope was
/// opened at all — the tree held only `TranslationUnit` and `Class`, and the constructor's parameters were bound
/// nowhere, which is why neither `: first(f)` nor the body could see them.
///
/// Descending one level is what the shape asks for, and it is written as a **search rather than a rule about
/// constructors**: a declaration whose declarators live in a nested declaration is exactly what wrapping produces, and
/// the search stops at the first level, so it cannot wander into a body.
/// **Does this declarator carry a parameter list of its own** — as opposed to one written inside its initializer?
///
/// A declarator holding a ParameterList names a function; that is the rule the scope builder has always used, and
/// it was asked of descendants(). An **initializer is an expression**, and an expression may contain a parameter
/// list that declares nothing about this declarator: uto ids = items | std::views::filter([](const Item& item)
/// { return item.id > 0; }); holds the lambda's. Reading it as the declarator's made ids a **function** —
/// measured on a <ranges> pipeline, its fact was kind: Function with no parameters, so its hover read ids(…)
/// and its type could never be asked, which is why nothing downstream of the pipe worked. Nothing inside an
/// initializer declares this declarator, so that subtree is skipped.
/// **Does the declarator that names something have a parameter list of its own** — is this a function's?
///
/// The grammar asks it structurally: `noptr-declarator: declarator-id ( params )`, so the list is a **child** of the
/// declarator whose other child is the name. Two shapes need the rise through the chain, and both are measured:
///
/// ```text
/// void (named) (int x);          named  → (named) → (named)(int x)      no pointer on the way: the list is named's
/// int (*fp)(int);                *fp                                    a pointer first: a variable, the list is the type's
/// int (*maker(int a))(int b);    *maker(int a)                          has its own `(int a)` first: a function
/// ```
///
/// A declarator with no name anywhere (a qualified definition, `void Widget::grow(int)`, whose name the specifier
/// sequence took) falls back to the subtree search the callers had.
fn the_declarator_that_names_it_has_a_list(declarator: &CppSyntaxNode) -> bool {
    let Some(naming) = the_naming_declarator(declarator) else {
        return a_parameter_list_of_the_declarator(declarator);
    };
    the_lists_of_the_name(naming).next().is_some()
}

/// **The declarator whose direct children include the name** — `declarator_id` in the grammar's `noptr-declarator`.
///
/// The innermost one, because the parents are wrappers: `(*maker(int a))(int b)` nests three declarators and the name
/// `maker` is a direct child of the second. `None` for a declarator that names nothing, which is a qualified
/// definition whose name the specifier sequence took (`void Widget::grow(int)`).
fn the_naming_declarator(declarator: &CppSyntaxNode) -> Option<CppSyntaxNode> {
    use cpp_parser::CppAstNode;
    let mut naming = declarator.clone();
    loop {
        if naming
            .children()
            .any(|child| cpp_parser::CppNameExpr::can_cast(child.kind().into()))
        {
            return Some(naming);
        }
        naming = naming
            .children()
            .find(|child| cpp_parser::CppDeclarator::can_cast(child.kind().into()))?;
    }
}

/// **The parameter lists that belong to the name**, its own first, risen through the declarators around it — and
/// **stopping at a pointer or a reference**, because a list beyond one belongs to a *type* rather than to the function.
///
/// ```text
/// void (named) (int x);          named → (named) → (named)(int x)   one list, the name's
/// int (*maker(int a))(int b);    *maker(int a)                      `(int a)` first, then the `*` stops the rise:
///                                                                   `(int b)` is the returned pointer's
/// int (*fp)(int);                *fp                                a `*` and no list: a variable, the list is the type's
/// ```
///
/// Measured on `int (*maker(int a))(int b);` before this: the subtree scan collected both lists, and `b` — a parameter
/// of the *returned pointer's* type — was bound as a file-scope variable.
fn the_lists_of_the_name(
    naming: cpp_parser::CppSyntaxNode,
) -> impl Iterator<Item = cpp_parser::CppSyntaxNode> {
    use cpp_parser::CppAstNode;
    let mut lists: Vec<cpp_parser::CppSyntaxNode> = Vec::new();
    let mut current = Some(naming);
    while let Some(node) = current {
        for child in node.children() {
            if cpp_parser::CppParamList::can_cast(child.kind().into()) {
                lists.push(child);
            }
        }
        if let Some(typed) = cpp_parser::CppDeclarator::cast(node.clone())
            && (typed.is_a_pointer() || typed.is_a_reference())
        {
            break;
        }
        current = node
            .parent()
            .filter(|parent| cpp_parser::CppDeclarator::can_cast(parent.kind().into()));
    }
    lists.into_iter()
}
fn a_parameter_list_of_the_declarator(node: &CppSyntaxNode) -> bool {
    use cpp_parser::CppAstNode;
    for child in node.children() {
        if cpp_parser::CppSyntaxKind::from(child.kind()) == cpp_parser::CppSyntaxKind::Initializer {
            continue;
        }
        if cpp_parser::CppParamList::can_cast(child.kind().into()) {
            return true;
        }
        if a_parameter_list_of_the_declarator(&child) {
            return true;
        }
    }
    false
}

fn declarators(node: &CppSyntaxNode) -> Vec<CppSyntaxNode> {
    // **A zero-width declarator names nothing.** The grammar synthesises one after a specifier sequence that
    // consumed the whole declaration, and a `friend` definition is the shape that produces it: the inner
    // declaration's declarator belongs to the friend (`FriendDecl { Declaration { InitDeclarator … } }`), and the
    // outer declaration is left with an empty `InitDeclarator` at the end of the file. Kept, `declarator_as` opened
    // a function scope over no tokens at all — measured on `classes.cpp`, where the friend `operator==`'s real
    // declarator was never reached and its body was walked into nothing.
    let a_declarator = |child: &CppSyntaxNode| {
        matches!(
            CppSyntaxKind::from(child.kind()),
            CppSyntaxKind::InitDeclarator | CppSyntaxKind::Declarator
        ) && !child.text_range().is_empty()
    };

    let init: Vec<CppSyntaxNode> = node
        .children()
        .filter(|child| cpp_parser::CppInitDeclarator::can_cast(child.kind().into()))
        .filter(a_declarator)
        .collect();

    if !init.is_empty() {
        return init;
    }

    let direct: Vec<CppSyntaxNode> = node
        .children()
        .filter(|child| cpp_parser::CppDeclarator::can_cast(child.kind().into()))
        .filter(a_declarator)
        .collect();

    if !direct.is_empty() {
        return direct;
    }

    node.children()
        .filter(|child| cpp_parser::CppDeclaration::can_cast(child.kind().into()))
        .flat_map(|wrapped| declarators(&wrapped))
        .collect()
}

/// The name a declaration declares, and the range of just that name.
///
/// Two shapes reach this, and which one a construct uses is not predictable from its kind: some declarations
/// carry a `NameExpr` child (`void f(int)` has `f` inside a declarator's name node) while others carry the
/// identifier as a **direct token** (`Red` in `enum { Red }`, `done` in `done: return;`). Both are tried,
/// because assuming either one leaves whole categories of declaration unnamed — enumerators and labels, which
/// is exactly what the first version of this did.
///
/// `None` when there is no name to read — an anonymous namespace, a `static_assert`, a construct the grammar
/// recovered from.
///
/// A **qualified** name is refused: `int ns::count;` declares something in `ns`, and splitting it here would
/// bind `count` in the enclosing scope, where it cannot be used. A using-declaration is the one construct that
/// *does* want the last component, and it reads it itself.
/// **The name a class-like specifier declares itself** — `Color` for `enum class Color { … }`.
///
/// The two spellings are not the same shape in this grammar:
///
/// ```text
/// enum class Color { Red };   DeclSpecifierSeq > BuiltinType > [EnumKeyword, ClassKeyword, NameExpr, CompoundStat]
/// class Widget { … };         the name is in the *declarator*, which the caller reads
/// ```
///
/// so this answers only the first: it looks for the `NameExpr` before the body and stops at the body, which is what
/// keeps an enumerator's identifier from being read as the enumeration's name. `None` means the specifier names
/// nothing — a forward declaration, or an anonymous `enum { A };` — and then the caller has nothing to bind.
fn specifier_name(specifier: &CppSyntaxNode) -> Option<(Name, cpp_parser::SourceRange)> {
    for element in specifier.descendants_with_tokens() {
        let Some(node) = element.as_node() else {
            let Some(token) = element.as_token() else {
                continue;
            };
            if CppTokenKind::from(token.kind()) != CppTokenKind::Identifier {
                continue;
            }
            let text = token.text();
            let name = name_from_text(text, specifier)?;
            return Some((name, cpp_parser::source_range(token.text_range())));
        };
        if cpp_parser::CppCompoundStat::can_cast(node.kind().into()) {
            return None;
        }
    }

    None
}

/// **The name a `typedef` gives an anonymous class** — `typedef struct { … } Name;` — or `None` for anything else.
///
/// A C struct is usually declared behind a typedef with no tag at all, and the tag is where the grammar puts a class's
/// name: `declared_name` looks *along the declarator*, and for this shape the declarator belongs to the typedef rather
/// than to the class, so the class answers "unnamed" and its members are filed under a scope nothing can ask about.
/// The typedef's own name is the only name the type has, so it is the one the scope takes.
///
/// The search is deliberately narrow: **up** to the declaration that starts with `typedef`, and then the **last**
/// identifier before its `;`. A class with a tag (`typedef struct Foo { … } Foo;`) is answered by `declared_name` first
/// and never reaches here, which is what keeps a pointer typedef (`typedef struct Foo { … } *FooPtr;`) out — its last
/// identifier is not a class name, and only the untagged shape can reach this path.
fn the_typedef_name_around(node: &CppSyntaxNode) -> Option<String> {
    // **The declaration this body belongs to has to *be* the `typedef`.**
    //
    // The first version asked "does any ancestor hold a `typedef` token?", and `ancestors()` reaches the
    // **`TranslationUnit`** — whose descendants hold every `typedef` in the file. So an anonymous class that is a
    // *member* of another class borrowed the name of the next typedef in the header: measured on neovim's
    // `ex_cmds_defs.h`, `struct exarg`'s nested `struct { bool file; bool bar; } magic;` was filed under
    // `exarg::SubReplacementString`, the name of a typedef declared a hundred lines later.
    //
    // The nearest declaration-like ancestor is the one that owns the specifiers this body was written in, so it is
    // the one that answers. Both spellings are accepted — the parser produces a `TypedefDecl` of its own for this,
    // and a `Declaration` whose text begins with the keyword is the same thing written the general way.
    let declaration = node
        .ancestors()
        .find_map(cpp_parser::CppDeclaration::cast)?;
    // **The two spellings of `typedef`**, asked of the declaration rather than of its text.
    let owns_a_typedef = declaration.is_a_typedef();
    if !owns_a_typedef {
        return None;
    }

    // **Only the identifiers *after* the body count.** The name a typedef gives its type is written outside the braces,
    // and the first version of this stopped at the first `;` — which is `int a;` *inside* the body of
    // `typedef struct { int a; int b; } Object;` — so the answer was **`a`**: the class scope took the first member's
    // name, every use of `Object` asked a class called `a` for its members, and the fixture's
    // `Class Some("a") -> ["a", "b"]` is what that looked like.
    let body_end = node
        .children()
        .find(|child| {
            cpp_parser::CppClassBody::can_cast(child.kind().into())
                || cpp_parser::CppCompoundStat::can_cast(child.kind().into())
        })
        .map(|body| usize::from(body.text_range().end()))
        .unwrap_or(0);

    let mut last = None;
    for element in declaration.syntax().descendants_with_tokens() {
        let Some(token) = element.into_token() else {
            continue;
        };
        if usize::from(token.text_range().start()) < body_end {
            continue;
        }
        if CppTokenKind::from(token.kind()) == CppTokenKind::Identifier {
            last = Some(token.text().to_string());
        }
    }

    // A name that is the class's own tag (`struct Name { … }`) never reaches here, so anything found is the typedef's.
    last.filter(|name| !name.is_empty())
}
fn declared_name(node: &CppSyntaxNode) -> Option<(Name, cpp_parser::SourceRange)> {
    // The name is looked for *only* along the declarator-to-name path. That restriction is the whole
    // correctness of this function: a search that descends freely finds the first identifier anywhere, which
    // for `a = b;` is `a` inside the initializer and for `use(x);` is the argument — so a scope ends up
    // declaring names that a statement merely *uses*.
    if let Some(name_node) = name_node_along_declarator(node) {
        // A qualified name declares something in the scope it qualifies, not here: `int ns::Widget::count = 0;`
        // declares a member of `ns::Widget`, and binding `count` in this file's scope would put a name in scope
        // that cannot be used unqualified — and collide with every other `count`.
        if is_qualified(&name_node) {
            return None;
        }

        // **An operator declaration has no identifier to find** — `operator*`, `operator[]`, `operator()` are the
        // keyword plus a token, and a conversion (`operator int`) is the keyword plus a type. Its spelling is still
        // a name every lookup can be keyed on (`std::vector::operator[]`), and it is what the operator rules read:
        // without this, `int operator*() const;` declared **nothing**, so a class's operators were not members at
        // all and `*money` could not find one.
        if name_node
            .descendants_with_tokens()
            .filter_map(|child| child.into_token())
            .any(|token| CppTokenKind::from(token.kind()) == CppTokenKind::OperatorKeyword)
        {
            let spelling = name_node.text().to_string();
            let spelling = spelling.trim();
            // **The symbol, not the whole spelling.** The name node's text *includes* the keyword
            // (`operator*`), and `Name::operator` writes the keyword back — so passing the text whole produced
            // `operator operator*`, which no lookup for `operator*` matches.
            let symbol = spelling
                .strip_prefix("operator")
                .map(str::trim)
                .unwrap_or(spelling);
            if !symbol.is_empty() {
                return Some((
                    Name::operator(symbol),
                    cpp_parser::source_range(name_node.text_range()),
                ));
            }
        }

        let token = first_identifier_in_name(&name_node)?;
        let text = token.text();

        // **The name node's own range when the token has none.** A destructor's declarator holds a `NameExpr` whose
        // child is a nested `Declaration` rather than an identifier, so the token found here covers nothing — and a
        // range of nothing is what every consumer would slice the file with, giving a member row with no label. The
        // node spans the whole spelling (`~Derived`), which is what `NameKind::Destructor` holds.
        let range = if token.text_range().is_empty() {
            cpp_parser::source_range(name_node.text_range())
        } else {
            cpp_parser::source_range(token.text_range())
        };

        // The **name node** decides what the name is, not the declaration around it. See
        // [`name_from_text`] — the difference is a class whose body contains a destructor.
        if let Some(name) = name_from_text(text, &name_node) {
            return Some((name, range));
        }
    }

    // **A name the declarator does not hold** — a constructor written with a specifier (`explicit A(int x)`) or a
    // destructor (`virtual ~A()`), where the parser keeps the name in the specifier sequence and the declarator is
    // only `(int x)`.
    //
    // [`cpp_parser::CppDeclaration::get_name`] is the reader that knows the arm; asking it here is what makes the
    // **fact** exist, not just the `missing-return` rule that already asks it. Measured before this arm on
    // `struct A { explicit A(int x) : x_(x) {} virtual ~A() {} A() {} }`: the parameter `x` was a fact and the
    // decorated constructor was not, so `A::` offered one of its two constructors and a hover on the declaration
    // answered nothing. The decorator was invisible in the member list while `A()` was there — a difference no reader
    // of the class can explain.
    //
    // Asked **last**, so every declaration whose declarator names it is unchanged, and only for a declaration: a
    // declarator and a parameter reach this function too.
    if let Some(declaration) = cpp_parser::CppDeclaration::cast(node.clone())
        && let Some(token) = declaration.get_name()
    {
        let text = token.get_name_text().to_string();
        if let Some(name) = name_from_text(&text, node) {
            return Some((name, cpp_parser::source_range(token.get_range())));
        }
    }

    // A node that names something with a direct token has no `NameExpr` to walk: an enumerator is
    // `EnumeratorDecl["Red"]` and a label is `LabelStat["done" ":"]`. Neither can hold an initializer, so the
    // token is unambiguous here in a way it would not be further down the tree.
    let token = last_identifier(node)?;
    let text = token.text();
    let name = name_from_text(text, node)?;

    Some((name, cpp_parser::source_range(token.text_range())))
}

/// A function's parameters, in order: each one's declarator, and the name it declares where it declares one.
///
/// The one reading of "what are this function's parameters", shared by the two consumers that need it: the scope
/// builder, which binds the named ones, and the inlay hints, which label an argument at a call site with the
/// parameter it lands in.
///
/// # Why the *unnamed* parameters are kept
///
/// `void f(int, int b);` is ordinary C++ and declares nothing for its first parameter — but it still occupies the
/// first position, and a hint is placed **by position**. A reading that dropped the unnamed ones would put `b`
/// against the first argument, which is a wrong answer rather than a missing one; the `None` in its place is what
/// keeps the alignment.
///
/// # Why a parameter's name is the declarator's
///
/// [`declared_name`] is the reading that decides what a declaration introduces, and a parameter's declarator is
/// what introduces the parameter: `void f(int (*cb)(int a));` has a parameter named `cb`, and the `a` inside the
/// nested parameter list belongs to the function pointer's own type.
pub(crate) fn parameters_of(
    list: &CppSyntaxNode,
) -> Vec<(CppSyntaxNode, Option<(Name, cpp_parser::SourceRange)>)> {
    list.children()
        .filter(|child| cpp_parser::CppParam::can_cast(child.kind().into()))
        .map(|parameter| {
            let declared = parameter
                .children()
                .filter(|child| cpp_parser::CppDeclarator::can_cast(child.kind().into()))
                .find_map(|declarator| declared_name(&declarator));

            (parameter, declared)
        })
        .collect()
}

/// The segments of a namespace's name, outermost first: `["a", "b"]` for `namespace a::b { }`.
///
/// Empty for an anonymous namespace, and for one whose name could not be read — both mean "this construct
/// introduces nothing", which is the same answer [`declared_name`] gives by returning `None`.
///
/// # Why the top-level identifiers are the answer
///
/// `namespace a::b` parses as **one** `NamespaceDecl` whose `NameExpr` holds both identifiers, while
/// `namespace a { namespace b {` parses as two declarations and therefore two `NameExpr`s. Reading the direct
/// identifier tokens of the name node is what makes the two agree, and it is the only reading that does: the
/// last identifier alone gives `a::b` the single segment `b`, the first alone gives it `a`, and neither can
/// produce `a::b::C`.
///
/// A **class** name is deliberately not read this way. `struct a::C { int member; };` is an out-of-line
/// definition of a class `a::C`, so its scope's qualified name is `a::C` — but `a` is a namespace that already
/// exists, a segment this declaration does not introduce and must not claim as its own scope. Namespaces are
/// the one construct where a `::` in the name *is* a nesting the declaration creates.
fn namespace_segments(node: &CppSyntaxNode) -> Vec<String> {
    namespace_segments_with_ranges(node)
        .into_iter()
        .map(|(name, _)| name)
        .collect()
}

/// [`namespace_segments`] with the range each segment was written at.
///
/// A binding's `name_range` is what a rename edits and what a reference search matches, so it has to be the
/// segment's own span and not the whole declaration's: collapsing them is the difference between renaming `b`
/// in `namespace a::b` and renaming the entire namespace declaration.
fn namespace_segment_ranges(node: &CppSyntaxNode) -> Vec<cpp_parser::SourceRange> {
    namespace_segments_with_ranges(node)
        .into_iter()
        .map(|(_, range)| range)
        .collect()
}

/// The segments of a namespace's name with their ranges, outermost first.
fn namespace_segments_with_ranges(node: &CppSyntaxNode) -> Vec<(String, cpp_parser::SourceRange)> {
    let Some(name) = first_child(node, CppSyntaxKind::NameExpr) else {
        // `namespace { }` — anonymous. No node at all rather than an empty one, because there is no name to
        // have written.
        return Vec::new();
    };

    name.children_with_tokens()
        .filter_map(|child| child.into_token())
        .filter(|token| CppTokenKind::from(token.kind()) == CppTokenKind::Identifier)
        .map(|token| {
            (
                token.text().to_string(),
                cpp_parser::source_range(token.text_range()),
            )
        })
        .collect()
}

/// The `NameExpr` naming a declarator, following only the nodes that carry a declared name.
///
/// Stopping at anything else is what keeps an initializer, an argument list, and a function body out of the
/// search — see [`declared_name`] for what going further costs.
fn name_node_along_declarator(node: &CppSyntaxNode) -> Option<CppSyntaxNode> {
    match CppSyntaxKind::from(node.kind()) {
        CppSyntaxKind::NameExpr => return Some(node.clone()),
        // A wrapper carrying a type or a template parameter rather than an expression. Descending is what
        // reaches `T` in `template <typename T>` and in `T d[N]`, neither of which has a declarator of its own
        // around the name.
        CppSyntaxKind::DeclSpecifierSeq
        | CppSyntaxKind::TemplateParameter
        | CppSyntaxKind::TypenameType
        | CppSyntaxKind::TemplateType
        | CppSyntaxKind::NamedType
        | CppSyntaxKind::QualifiedType
        | CppSyntaxKind::PointerType
        | CppSyntaxKind::ReferenceType
        | CppSyntaxKind::RValueReferenceType
        | CppSyntaxKind::BuiltinType => {
            for child in node.children() {
                if let Some(found) = name_node_along_declarator(&child) {
                    return Some(found);
                }
            }

            return None;
        }
        CppSyntaxKind::Declarator => {
            // A nested declarator is the derived-type part — `int *p` has the star in an outer declarator — so
            // the search continues through it rather than stopping at the first one.
            //
            // **A nested declarator that names nothing does not end the search.** `int (*fp)(int)` is
            // `Declarator (*fp) > Declarator *fp > [Declarator *, NameExpr fp]`, and the star declarator holds no name —
            // returning its `None` stopped the walk two levels above the `NameExpr`, so a local function pointer declared
            // **nothing**: `definitions("fp")` answered `NotDeclaredHere` in the function that declares it, and the
            // undeclared-identifier check reported the file's own variable.
            for child in node.children() {
                if cpp_parser::CppDeclarator::can_cast(child.kind().into())
                    && let Some(found) = name_node_along_declarator(&child)
                {
                    return Some(found);
                }
            }

            for child in node.children() {
                if cpp_parser::CppNameExpr::can_cast(child.kind().into()) {
                    return Some(child);
                }
            }

            return None;
        }
        _ => {}
    }

    // An `InitDeclarator` is the usual entry point: the declarator inside it names the entity, and an
    // initializer beside it does not.
    for child in node.children() {
        if matches!(
            CppSyntaxKind::from(child.kind()),
            CppSyntaxKind::Declarator | CppSyntaxKind::NameExpr
        ) && let Some(found) = name_node_along_declarator(&child)
        {
            return Some(found);
        }
    }

    None
}

/// The first identifier belonging to a name node, looking through nested name nodes.
///
/// A `NameExpr` may hold its identifier directly (`first`, from a binding pattern) or hold another `NameExpr`
/// that holds it (a qualified or templated name). Both are searched, because the two shapes are produced for
/// constructs that this layer cannot tell apart by kind alone.
fn first_identifier_in_name(node: &CppSyntaxNode) -> Option<cpp_parser::CppSyntaxToken> {
    if let Some(token) = last_identifier(node) {
        return Some(token);
    }

    for child in node.children() {
        if !cpp_parser::CppNameExpr::can_cast(child.kind().into()) {
            continue;
        }
        if let Some(token) = first_identifier_in_name(&child) {
            return Some(token);
        }
    }

    None
}

/// The range covering both of two ranges.
///
/// A function's scope has to reach from its declarator to the end of its body, because a scope is looked up by
/// offset and the body lies *past* the declarator. Taking just the declarator's range leaves every local
/// declaration resolving to the enclosing scope, which is a wrong answer rather than a missing one: completion
/// inside a function would offer the class's members and none of its locals.
fn span_of(
    first: cpp_parser::SourceRange,
    second: cpp_parser::SourceRange,
) -> cpp_parser::SourceRange {
    let start = first.start_offset.min(second.start_offset);
    let end = first.end_offset().max(second.end_offset());

    cpp_parser::SourceRange {
        start_offset: start,
        length: end.saturating_sub(start),
    }
}

/// The `NameExpr` a declaration names itself with, looking through the declarator wrappers.
///
/// Search is depth-first, and it stops at the **deepest** name first.
///
/// The search is depth-first and stops at the first name, which is what the declarator grammar guarantees:
/// the outermost name in a declarator is the one being declared, and anything nested is a parameter or a
/// return type. A *name* is the exception, because a name can contain one: `using ns::f;` is written as an
/// outer `NameExpr` for the first segment with the rest of the name inside it, so the outermost node's own
/// tokens are `ns` and its `::`. Descending before answering is what makes the answer the last component —
/// the thing the statement introduces — rather than the qualifier.
fn find_name_node(node: &CppSyntaxNode) -> Option<CppSyntaxNode> {
    if !cpp_parser::CppNameExpr::can_cast(node.kind().into()) {
        return find_name_child(node);
    }

    find_name_child(node).or_else(|| Some(node.clone()))
}

/// The deepest name inside `node`, if it has one.
fn find_name_child(node: &CppSyntaxNode) -> Option<CppSyntaxNode> {
    for child in node.children() {
        // A parameter list belongs to the signature rather than to the name, and a body is a different scope.
        // Skipping them keeps `void f(int g)` from reporting `g` as the declared name, and keeps a class body
        // from being searched for the class's own name.
        if matches!(
            CppSyntaxKind::from(child.kind()),
            CppSyntaxKind::ParameterList | CppSyntaxKind::CompoundStat | CppSyntaxKind::ClassBody
        ) {
            continue;
        }

        if let Some(found) = find_name_node(&child) {
            return Some(found);
        }
    }

    None
}

/// The class name of an **elaborated type specifier**: the `Widget` of `class Widget;`.
///
/// The grammar writes that declaration flat — `class` is one specifier and `Widget` the next — so the name is
/// the type written beside the class-like keyword rather than a declarator's. Asked only when the declaration has
/// no declarator at all; with one, the declarator is the name and this would report the type instead.
fn elaborated_type_name(node: &CppSyntaxNode) -> Option<(Name, cpp_parser::SourceRange)> {
    let specifiers = first_child(node, CppSyntaxKind::DeclSpecifierSeq)?;

    let has_class_keyword = specifiers.children().any(|child| {
        CppSyntaxKind::from(child.kind()) == CppSyntaxKind::BuiltinType
            && is_class_like_keyword_token(&child)
    });
    if !has_class_keyword {
        return None;
    }

    // Either wrapper: this reader wants the name a type was written with, and whether it carried template
    // arguments is a different question — see [`CppSyntaxKind::NamedType`] for why there are two kinds.
    let name_node = specifiers.children().find(|child| {
        matches!(
            CppSyntaxKind::from(child.kind()),
            CppSyntaxKind::TemplateType | CppSyntaxKind::NamedType
        )
    })?;

    let token = first_identifier_in_name(&name_node)?;
    let name = name_from_text(token.text(), node)?;

    Some((name, cpp_parser::source_range(token.text_range())))
}

/// Is this built-in specifier a class-like keyword?
fn is_class_like_keyword_token(node: &CppSyntaxNode) -> bool {
    node.children_with_tokens()
        .filter_map(|element| element.into_token())
        .any(|token| {
            matches!(
                token.kind(),
                cpp_parser::CppKind::Token(CppTokenKind::ClassKeyword)
                    | cpp_parser::CppKind::Token(CppTokenKind::StructKeyword)
                    | cpp_parser::CppKind::Token(CppTokenKind::UnionKeyword)
                    | cpp_parser::CppKind::Token(CppTokenKind::EnumKeyword)
            )
        })
}

/// **The qualifier of a `::`-qualified declaration whose name the grammar put in the declarator.**
///
/// `void Widget::grow(int)` declares `grow`, and it declares it *in `Widget`* — the two facts this returns.
/// `None` for every other declarator, which is the ordinary case and the one whose reading is [`declared_name`].
fn qualified_declarator_name(
    declarator: &CppSyntaxNode,
) -> Option<(String, (Name, cpp_parser::SourceRange))> {
    let node = name_node_along_declarator(declarator)?;

    // Everything up to the final `::` is the qualifier, and what follows it is the name — which is `None` when it
    // is a destructor, an operator or a conversion function. Those are declarations whose name `classify` cannot
    // spell this way, and the honest answer is that this reading does not apply to them rather than a panic: see
    // [`qualified_name`], whose first version took the indexing thread down on a real project.
    if is_qualified(&node) {
        return qualified_name(node);
    }

    None
}

/// **The qualified name a declaration is written with, wherever the grammar put it.**
///
/// One question, two shapes, and every caller that needs "what is this declaration's own name" asks it here rather
/// than choosing a shape:
///
/// ```text
/// int Source::GetLine(int n) { … }   Declarator > NameExpr "Source::GetLine"   ← written against `(`
/// void Box<int>::grow(…) { … }       DeclSpecifierSeq "void Box<int>::grow"    ← the qualifier has template args
/// ```
///
/// The first is what the grammar builds when a qualified name is written straight against a parameter list: a type in
/// a declaration is never followed by `(`, so the name can only be the declarator's. The second stays in the
/// specifier sequence, because `Box` is followed by `<` and a declaration cannot tell that from a return type. Both
/// are the same declaration, and a reader that knows only one of them treats half of a project's definitions as
/// nameless — which is what happened: a body defined out of class could not see its class's members.
///
/// `None` for a declaration whose name is not qualified (the ordinary case) and for one with no name at all.
pub(crate) fn the_qualified_name_of_a_declaration(
    node: &CppSyntaxNode,
) -> Option<(String, (Name, cpp_parser::SourceRange))> {
    declarators(node)
        .iter()
        .find_map(qualified_declarator_name)
        .or_else(|| qualified_specifier_name_of_the_declaration(node))
}

/// **The same, for the other place the grammar puts a qualified name** — the specifier sequence.
///
/// ```text
/// void Widget::grow(Widget& other) { … }   DeclSpecifierSeq["void Widget::grow"] InitDeclarator["(…)"]
/// ```
///
/// The declarator holds only the parameter list, so [`qualified_declarator_name`] finds no name at all and the
/// declaration would be read as one that declares nothing. This is the reader for that shape: the name node is in
/// the specifier sequence, and everything after it — the parameter list, the `const`, the body — is not part of it.
///
/// **Only the name node that carries a `::` is taken.** A specifier sequence is mostly types, and treating the
/// first name in it as the declared name would answer `void` for `void f()`; the qualifier is what makes this
/// unambiguous, and [`is_unnamed_declaration`] has already established that the declaration is this shape before
/// this is called.
fn qualified_specifier_name(
    declarator: &CppSyntaxNode,
) -> Option<(String, (Name, cpp_parser::SourceRange))> {
    let declaration = declarator
        .ancestors()
        .find(|node| cpp_parser::CppDeclaration::can_cast(node.kind().into()))?;

    qualified_specifier_name_of_the_declaration(&declaration)
}

/// The declaration-node form of [`qualified_specifier_name`] — the same reading, for a caller that already holds the
/// declaration rather than one of its declarators.
fn qualified_specifier_name_of_the_declaration(
    declaration: &CppSyntaxNode,
) -> Option<(String, (Name, cpp_parser::SourceRange))> {
    qualified_name(qualified_specifier_name_node(declaration)?)
}

/// **The name node of a declaration whose name the grammar put in the specifier sequence.**
///
/// `None` for every declaration that is not that shape — which is every ordinary declaration, and also the
/// qualified declaration whose qualifier names a scope this file has not built. The two callers want that answer
/// for different reasons and must get the same one:
///
/// * [`ScopeWalker::names_a_scope_this_file_has`] asks it to decide whether the declaration is this file's to bind
///   at all, and reads the qualifier off the node;
/// * [`qualified_specifier_name`] asks it for the name to bind.
fn qualified_specifier_name_node(declaration: &CppSyntaxNode) -> Option<CppSyntaxNode> {
    if !declaration_is_qualified(declaration) {
        return None;
    }

    let specifiers = first_child(declaration, CppSyntaxKind::DeclSpecifierSeq)?;

    // **A class definition's name is the class's, and a `::` inside its head is not the declaration's.** A partial
    // specialization writes a dependent type in its argument list — `struct B<A<T>, void_t<typename A<T>::From>>` —
    // and this reader took `A<T>::From` for the declared name, so the whole declaration was read as an out-of-line
    // definition of a class this file has not built: no binding, no class scope, no members, and no fact. Measured on
    // `tests/types.rs::a_partial_specialization_is_a_declaration_with_a_pattern`, where `specifiers` was never called
    // for the specialization at all.
    if specifiers.children().any(|child| {
        matches!(
            CppSyntaxKind::from(child.kind()),
            CppSyntaxKind::ClassDef
                | CppSyntaxKind::StructDef
                | CppSyntaxKind::UnionDef
                | CppSyntaxKind::EnumDef
                | CppSyntaxKind::EnumClassDef
        )
    }) {
        return None;
    }

    // A **descendant**, not a child: the grammar writes a qualified name inside a wrapper — `DeclSpecifierSeq >
    // TemplateType > NameExpr` for `void Box<int>::grow` — so a search of the direct children finds nothing and
    // the declaration is read as one that declares nothing. That a qualified name is here at all is what
    // `declaration_is_qualified` established, and it is the only `::` in this declaration's specifiers.
    cpp_parser::typed_descendants::<cpp_parser::CppNameExpr>(&specifiers)
        .find(|name| name.is_qualified())
        .map(|name| name.syntax().clone())
}

/// One `::`-qualified name node, as everything before the name and the name itself — `None` when what follows the
/// last separator is not a plain identifier (a destructor, an operator, a conversion function), which the caller
/// reads by other means.
///
/// # Why the *segments* of the tree, and not the name node's own tokens
///
/// A name node's direct tokens are not its text. `Outer<T>::grow` holds `<`, `T` and `>` in a **child node**, so a
/// reader that walks `children_with_tokens` sees no angle brackets at all, counts a depth of zero everywhere, and
/// believes the `::` inside `<A::B>` is a separator. Measured on a real project, that ended in
/// `last_identifier(..).expect(..)`: no direct identifier token either, and the **indexing thread panicked** —
/// which the user saw as a status bar that never stopped spinning, because the pump never reached the end of its
/// work.
///
/// So the text is assembled from the **leaves** of the subtree (every token of every descendant), which is the
/// node's text by definition, with trivia dropped as it goes. The qualifier is then everything before the last `::`
/// that is outside every `<…>`.
fn qualified_name(node: CppSyntaxNode) -> Option<(String, (Name, cpp_parser::SourceRange))> {
    /// The subtree's text, with trivia dropped, as characters — and for each one the token it came from.
    struct Spelled {
        characters: Vec<char>,
        /// `(the token, how many characters of it came before this one)`.
        origins: Vec<(cpp_parser::CppSyntaxToken, usize)>,
    }

    fn spell(node: &CppSyntaxNode, into: &mut Spelled) {
        for child in node.children_with_tokens() {
            if let Some(token) = child.clone().into_token() {
                let kind = CppTokenKind::from(token.kind());

                if matches!(
                    kind,
                    CppTokenKind::Whitespace
                        | CppTokenKind::LineComment
                        | CppTokenKind::BlockComment
                ) {
                    continue;
                }

                for (at, character) in token.text().chars().enumerate() {
                    into.characters.push(character);
                    into.origins.push((token.clone(), at));
                }

                continue;
            }

            if let Some(child) = child.into_node() {
                spell(&child, into);
            }
        }
    }

    let mut spelled = Spelled {
        characters: Vec::new(),
        origins: Vec::new(),
    };
    spell(&node, &mut spelled);

    // The last `::` outside every `<…>`. The characters come from tokens rather than from `node.text()`, so a `::`
    // written in a comment is not here to be counted.
    let mut depth = 0usize;
    let mut last_separator = None;
    let mut at = 0usize;

    while at < spelled.characters.len() {
        match spelled.characters[at] {
            '<' => depth += 1,
            '>' => depth = depth.saturating_sub(1),
            ':' if depth == 0 && spelled.characters.get(at + 1) == Some(&':') => {
                last_separator = Some(at);
                at += 1;
            }
            _ => {}
        }

        at += 1;
    }

    let last_separator = last_separator?;
    let after_the_separator = last_separator + 2;

    let qualifier: String = spelled.characters[..last_separator].iter().collect();
    let written: String = spelled.characters[after_the_separator..].iter().collect();

    // **A destructor, an operator and a conversion function are not identifiers** (`~Widget`, `operator+`,
    // `operator bool`), and this is what tells them apart: what follows the separator has to be one identifier and
    // nothing else. The same answer `last_identifier` used to give, without needing a token that may not be there.
    //
    // **The whole name is checked, not the part after its first character** — `f`, `x` and every other one-letter
    // member name came out as `None`, because the remainder of a one-letter name is the empty string and "no
    // characters after the first" was read as "no name". Measured on `struct W { void f(); }; void W::f() { }`:
    // `W::f` resolved to no qualifier at all, the definition's function scope hung off the **file** instead of `W`,
    // and a body written that way could not see its class's members.
    if written
        .chars()
        .next()
        .is_none_or(|first| !is_identifier_start(first))
        || !written.chars().all(is_identifier_character)
    {
        return None;
    }

    // The name is one token by construction, so its range is that token's — taken from the first character after
    // the separator.
    let (token, offset_in_it) = spelled.origins.get(after_the_separator)?;
    let starts_at = usize::from(token.text_range().start()) + offset_in_it;

    Some((
        qualifier,
        (
            Name::identifier(written.clone()),
            cpp_parser::SourceRange::new(starts_at, written.len()),
        ),
    ))
}

/// C++'s rule for the first character of an identifier, near enough: a letter or an underscore.
///
/// `$` is accepted by some compilers and is deliberately not here — this decides whether a *name* follows a `::`,
/// and everything it rejects (`~`, `operator`, a digit) is something this reading has already decided not to
/// handle rather than something it would get wrong.
fn is_identifier_start(character: char) -> bool {
    character.is_alphabetic() || character == '_'
}

fn is_identifier_character(character: char) -> bool {
    character.is_alphanumeric() || character == '_'
}

/// Is this name written with a qualifier?
fn is_qualified(node: &CppSyntaxNode) -> bool {
    node.children_with_tokens()
        .filter_map(|child| child.into_token())
        .any(|token| CppTokenKind::from(token.kind()) == CppTokenKind::Scope)
}

/// The last identifier token in a node, which is the entity a qualified name ends with.
///
/// **The name node's own tokens only**, so it answers `None` for a name whose segments are child nodes
/// (`Outer<T>::grow`) — see [`qualified_name`], which reads the subtree instead and says why.
fn last_identifier(node: &CppSyntaxNode) -> Option<cpp_parser::CppSyntaxToken> {
    node.children_with_tokens()
        .filter_map(|child| child.into_token())
        .filter(|token| CppTokenKind::from(token.kind()) == CppTokenKind::Identifier)
        .last()
}

/// Turn a declared spelling into a [`Name`], reading the special forms the way C++ writes them.
///
/// The text is the *last* identifier of the declarator, so the operator keyword is gone by the time this is
/// called — which is why the node is consulted as well: whether `+` spells an operator depends on whether
/// `operator` was written, and that token is in the node rather than in the name.
///
/// # `node` must be the **name**, not the declaration around it
///
/// Decided by a bug this cost. Both markers are looked for with `descendants_with_tokens`, so passing a
/// declaration that *contains* the name means looking for them in everything the declaration encloses — and
/// `struct Base { ~Base(); };` then has a `~` in it, which made the **class** `Base` a destructor called `~Base`.
/// The class's own scope was named `~Base` and every member after the destructor landed in it, so the class was
/// never bound at all. A class body containing an `operator` declaration did the same thing with the operator
/// keyword.
///
/// [`declared_name`] therefore passes the node the identifier was found **in** — the declarator's
/// [`NameExpr`](CppSyntaxKind::NameExpr) — and keeps the declaration only for the fallback path, where there is no
/// name node and the token came from the declaration itself.
fn name_from_text(text: &str, node: &CppSyntaxNode) -> Option<Name> {
    let has_operator_keyword = node
        .descendants_with_tokens()
        .filter_map(|child| child.into_token())
        .any(|token| CppTokenKind::from(token.kind()) == CppTokenKind::OperatorKeyword);

    if has_operator_keyword {
        // The lexer produces the operator as its own token right after the keyword, so the identifier found
        // here is a word-form operator (`new`, `delete`) or the beginning of a conversion type.
        return Some(Name::operator(text));
    }

    // **A destructor is spelled `~Name`, and the `~` is not inside the node this is asked about.**
    //
    // It used to be searched for among the node's own tokens, which finds it only when the node *is* the declarator
    // — `~Widget();` writes `Declarator > NameExpr, ParameterList`, so the `~` is the declarator's first token and
    // the `NameExpr` beside it holds a nested `Declaration` rather than an identifier. Looking one level out at the
    // declarator's own spelling is what tells the two apart, and it is the only reading that does not depend on
    // which node the caller happened to pass.
    let declarator_text = node
        .parent()
        .filter(|parent| cpp_parser::CppDeclarator::can_cast(parent.kind().into()))
        .map(|parent| parent.text().to_string())
        .unwrap_or_else(|| node.text().to_string());
    let has_tilde = declarator_text.trim_start().starts_with('~');

    if has_tilde {
        // **The class name, without the `~`, because `NameKind::Destructor`'s `Display` writes it.**
        //
        // The spelling comes from the declarator when the token the walker found has none — which is this case, and
        // why a destructor used to be bound as the empty string: a name with no text is a member row with no label.
        // The `~` is stripped rather than stored because `Display` adds it back, so keeping it would print
        // `~~Derived`. Whitespace goes too: the grammar has forms where it appears (`~ Derived`, `~Derived::name`)
        // and the stored spelling is compared against what a reader writes, which has none.
        let spelling: String = if text.is_empty() {
            declarator_text
        } else {
            text.to_string()
        }
        .chars()
        .filter(|character| !character.is_whitespace())
        .collect();

        let class = spelling.strip_prefix('~').unwrap_or(&spelling);
        // **Up to the parameter list.** The declarator's spelling is the whole `~Derived()`, and only the name is
        // wanted: the `(` is where the name stops on every declaration this is asked about.
        let class = class.split(['(', '<']).next().unwrap_or(class);
        if class.is_empty() {
            return None;
        }
        return Some(Name::destructor(class));
    }

    if text.is_empty() {
        return None;
    }

    Some(Name::identifier(text))
}

/// The module-shaped names a file declares, for a consumer that wants them without walking the tree.
///
/// Separate from [`build_scopes`] because a module name is not in a scope: it is matched against the module
/// graph. Kept here so that everything that reads a *name* out of the syntax lives in one place.
pub fn declared_module_names(root: &CppSyntaxNode) -> Vec<DeclName> {
    let mut names = Vec::new();

    for node in root.descendants() {
        match CppSyntaxKind::from(node.kind()) {
            CppSyntaxKind::ModuleDecl => {
                if let Some(name) = module_name_of(&node, CppSyntaxKind::ModuleName) {
                    names.push(DeclName::Module(name));
                }
                if let Some(partition) = module_name_of(&node, CppSyntaxKind::ModulePartition) {
                    names.push(DeclName::Partition(partition));
                }
            }
            CppSyntaxKind::ImportDecl => {
                if let Some(name) = module_name_of(&node, CppSyntaxKind::ModuleName) {
                    names.push(DeclName::Module(name));
                }
                if let Some(partition) = module_name_of(&node, CppSyntaxKind::ModulePartition) {
                    names.push(DeclName::Partition(partition));
                }
            }
            _ => {}
        }
    }

    names
}

/// The dotted name inside a module or partition node, as a qualified name.
fn module_name_of(node: &CppSyntaxNode, wrapper: CppSyntaxKind) -> Option<QualifiedName> {
    let holder = if wrapper == CppSyntaxKind::ModuleName {
        node.clone()
    } else {
        first_child(node, wrapper)?
    };

    let components: Vec<String> = holder
        .children_with_tokens()
        .filter_map(|child| child.into_token())
        .filter(|token| CppTokenKind::from(token.kind()) == CppTokenKind::Identifier)
        .map(|token| token.text().to_string())
        .collect();

    if components.is_empty() {
        return None;
    }

    Some(QualifiedName::from_components(components))
}

/// A binding origin for a declaration reached through an `#include`.
///
/// Exposed so that a caller assembling a table across files can mark the bindings it copies in, without this
/// module needing to know that includes exist.
pub fn included_origin(file: crate::paths::FileId) -> BindingOrigin {
    BindingOrigin::Included { file }
}

/// A binding origin for a declaration produced by a macro.
pub fn macro_origin(
    macro_name: impl Into<String>,
    definition: cpp_parser::SourceRange,
) -> BindingOrigin {
    BindingOrigin::MacroExpansion {
        macro_name: macro_name.into(),
        definition,
    }
}

/// The syntax kinds this layer reads a declaration out of, for a consumer auditing coverage.
///
/// Returned rather than documented so that a test can assert the set has not silently shrunk, which is the
/// failure mode of a match with a catch-all arm: a construct added to the grammar reaches the walker's
/// `descend` and contributes nothing, and nothing complains.
pub fn declaring_kinds() -> &'static [CppSyntaxKind] {
    &[
        CppSyntaxKind::NamespaceDecl,
        CppSyntaxKind::ClassDef,
        CppSyntaxKind::StructDef,
        CppSyntaxKind::UnionDef,
        CppSyntaxKind::ClassDecl,
        CppSyntaxKind::StructDecl,
        CppSyntaxKind::UnionDecl,
        CppSyntaxKind::EnumDef,
        CppSyntaxKind::EnumClassDef,
        CppSyntaxKind::TemplateDecl,
        CppSyntaxKind::TypedefDecl,
        CppSyntaxKind::UsingDecl,
        CppSyntaxKind::UsingDirective,
        CppSyntaxKind::Declaration,
        CppSyntaxKind::LabelStat,
    ]
}

/// Is this node a declaration the walk is expected to have read a name from?
///
/// Used by the coverage test: a node of one of these kinds that contributed no binding is either unnamed or a
/// gap, and only a test can tell which.
pub fn declares_a_binding(node: &CppSyntaxNode) -> bool {
    declaring_kinds().contains(&CppSyntaxKind::from(node.kind()))
}

/// A node's kind, by name, for a test that reports what it found.
pub fn kind_name(node: &CppSyntaxNode) -> String {
    format!("{:?}", CppSyntaxKind::from(node.kind()))
}