cpp_code_analysis 0.2.0

The analysis layer of cpp_ls: the preprocessor, symbol scopes, type inference and the semantic checks.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
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
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198
19199
19200
19201
19202
19203
19204
19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215
19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
19256
19257
19258
19259
19260
19261
19262
19263
19264
19265
19266
19267
19268
19269
19270
19271
19272
19273
19274
19275
19276
19277
19278
19279
19280
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296
19297
19298
19299
19300
19301
19302
19303
19304
19305
19306
19307
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332
19333
19334
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346
19347
19348
19349
19350
19351
19352
19353
19354
19355
19356
19357
19358
19359
19360
19361
19362
19363
19364
19365
19366
19367
19368
19369
19370
19371
19372
19373
19374
19375
19376
19377
19378
19379
19380
19381
19382
19383
19384
19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399
19400
19401
19402
19403
19404
19405
19406
19407
19408
19409
19410
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443
19444
19445
19446
19447
19448
19449
19450
19451
19452
19453
19454
19455
19456
19457
19458
19459
19460
19461
19462
19463
19464
19465
19466
19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477
19478
19479
19480
19481
19482
19483
19484
19485
19486
19487
19488
19489
19490
19491
19492
19493
19494
19495
19496
19497
19498
19499
19500
19501
19502
19503
19504
19505
19506
19507
19508
19509
19510
19511
19512
19513
19514
19515
19516
19517
19518
19519
19520
19521
19522
19523
19524
19525
19526
19527
19528
19529
19530
19531
19532
19533
19534
19535
19536
19537
19538
19539
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552
19553
19554
19555
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573
19574
19575
19576
19577
19578
19579
19580
19581
19582
19583
19584
19585
19586
19587
19588
19589
19590
19591
19592
19593
19594
19595
19596
19597
19598
19599
19600
19601
19602
19603
19604
19605
19606
19607
19608
19609
19610
19611
19612
19613
19614
19615
19616
19617
19618
19619
19620
19621
19622
19623
19624
19625
19626
19627
19628
19629
19630
19631
19632
19633
19634
19635
19636
19637
19638
19639
19640
19641
19642
19643
19644
19645
19646
19647
19648
19649
19650
19651
19652
19653
19654
19655
19656
19657
19658
19659
19660
19661
19662
19663
19664
19665
19666
19667
19668
19669
19670
19671
19672
19673
19674
19675
19676
19677
19678
19679
19680
19681
19682
19683
19684
19685
19686
19687
19688
19689
19690
19691
19692
19693
19694
19695
19696
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712
19713
19714
19715
19716
19717
19718
19719
19720
19721
19722
19723
19724
19725
19726
19727
19728
19729
19730
19731
19732
19733
19734
19735
19736
19737
19738
19739
19740
19741
19742
19743
19744
19745
19746
19747
19748
19749
19750
19751
19752
19753
19754
19755
19756
19757
19758
19759
19760
19761
19762
19763
19764
19765
19766
19767
19768
19769
19770
19771
19772
19773
19774
19775
19776
19777
19778
19779
19780
19781
19782
19783
19784
19785
19786
19787
19788
19789
19790
19791
19792
19793
19794
19795
19796
19797
19798
19799
19800
19801
19802
19803
19804
19805
19806
19807
19808
19809
19810
19811
19812
19813
19814
19815
19816
19817
19818
19819
19820
19821
19822
19823
19824
19825
19826
19827
19828
19829
19830
19831
19832
19833
19834
19835
19836
19837
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848
19849
19850
19851
19852
19853
19854
19855
19856
19857
19858
19859
19860
19861
19862
19863
19864
19865
19866
19867
19868
19869
19870
19871
19872
19873
19874
19875
19876
19877
19878
19879
19880
19881
19882
19883
19884
19885
19886
19887
19888
19889
19890
19891
19892
19893
19894
19895
19896
19897
19898
19899
19900
19901
19902
19903
19904
19905
19906
19907
19908
19909
19910
19911
19912
19913
19914
19915
19916
19917
19918
19919
19920
19921
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931
19932
19933
19934
19935
19936
19937
19938
19939
19940
19941
19942
19943
19944
19945
19946
19947
19948
19949
19950
19951
19952
19953
19954
19955
19956
19957
19958
19959
19960
19961
19962
19963
19964
19965
19966
19967
19968
19969
19970
19971
19972
19973
19974
19975
19976
19977
19978
19979
19980
19981
19982
19983
19984
19985
19986
19987
19988
19989
19990
19991
19992
19993
19994
19995
19996
19997
19998
19999
20000
20001
20002
20003
20004
20005
20006
20007
20008
20009
20010
20011
20012
20013
20014
20015
20016
20017
20018
20019
20020
20021
20022
20023
20024
20025
20026
20027
20028
20029
20030
20031
20032
20033
20034
20035
20036
20037
20038
20039
20040
20041
20042
20043
20044
20045
20046
20047
20048
20049
20050
20051
20052
20053
20054
20055
20056
20057
20058
20059
20060
20061
20062
20063
20064
20065
20066
20067
20068
20069
20070
20071
20072
20073
20074
20075
20076
20077
20078
20079
20080
20081
20082
20083
20084
20085
20086
20087
20088
20089
20090
20091
20092
20093
20094
20095
20096
20097
20098
20099
20100
20101
20102
20103
20104
20105
20106
20107
20108
20109
20110
20111
20112
20113
20114
20115
20116
20117
20118
20119
20120
20121
20122
20123
20124
20125
20126
20127
20128
20129
20130
20131
20132
20133
20134
20135
20136
20137
20138
20139
20140
20141
20142
20143
20144
20145
20146
20147
20148
20149
20150
20151
20152
20153
20154
20155
20156
20157
20158
20159
20160
20161
20162
20163
20164
20165
20166
20167
20168
20169
20170
20171
20172
20173
20174
20175
20176
20177
20178
20179
20180
20181
20182
20183
20184
20185
20186
20187
20188
20189
20190
20191
20192
20193
20194
20195
20196
20197
20198
20199
20200
20201
20202
20203
20204
20205
20206
20207
20208
20209
20210
20211
20212
20213
20214
20215
20216
20217
20218
20219
20220
20221
20222
20223
20224
20225
20226
20227
20228
20229
20230
20231
20232
20233
20234
20235
20236
20237
20238
20239
20240
20241
20242
20243
20244
20245
20246
20247
20248
20249
20250
20251
20252
20253
20254
20255
20256
20257
20258
20259
20260
20261
20262
20263
20264
20265
20266
20267
20268
20269
20270
20271
20272
20273
20274
20275
20276
20277
20278
20279
20280
20281
20282
20283
20284
20285
20286
20287
20288
20289
20290
20291
20292
20293
20294
20295
20296
20297
20298
20299
20300
20301
20302
20303
20304
20305
20306
20307
20308
20309
20310
20311
20312
20313
20314
20315
20316
20317
20318
20319
20320
20321
20322
20323
20324
20325
20326
20327
20328
20329
20330
20331
20332
20333
20334
20335
20336
20337
20338
20339
20340
20341
20342
20343
20344
20345
20346
20347
20348
20349
20350
20351
20352
20353
20354
20355
20356
20357
20358
20359
20360
20361
20362
20363
20364
20365
20366
20367
20368
20369
20370
20371
20372
20373
20374
20375
20376
20377
20378
20379
20380
20381
20382
20383
20384
20385
20386
20387
20388
20389
20390
20391
20392
20393
20394
20395
20396
20397
20398
20399
20400
20401
20402
20403
20404
20405
20406
20407
20408
20409
20410
20411
20412
20413
20414
20415
20416
20417
20418
20419
20420
20421
20422
20423
20424
20425
20426
20427
20428
20429
20430
20431
20432
20433
20434
20435
20436
20437
20438
20439
20440
20441
20442
20443
20444
20445
20446
20447
20448
20449
20450
20451
20452
20453
20454
20455
20456
20457
20458
20459
20460
20461
20462
20463
20464
20465
20466
20467
20468
20469
20470
20471
20472
20473
20474
20475
20476
20477
20478
20479
20480
20481
20482
20483
20484
20485
20486
20487
20488
20489
20490
20491
20492
20493
20494
20495
20496
20497
20498
20499
20500
20501
20502
20503
20504
20505
20506
20507
20508
20509
20510
20511
20512
20513
20514
20515
20516
20517
20518
20519
20520
20521
20522
20523
20524
20525
20526
20527
20528
20529
20530
20531
20532
20533
20534
20535
20536
20537
20538
20539
20540
20541
20542
20543
20544
20545
20546
20547
20548
20549
20550
20551
20552
20553
20554
20555
20556
20557
20558
20559
20560
20561
20562
20563
20564
20565
20566
20567
20568
20569
20570
20571
20572
20573
20574
20575
20576
20577
20578
20579
20580
20581
20582
20583
20584
20585
20586
20587
20588
20589
20590
20591
20592
20593
20594
20595
20596
20597
20598
20599
20600
20601
20602
20603
20604
20605
20606
20607
20608
20609
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621
20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642
20643
20644
20645
20646
20647
20648
20649
20650
20651
20652
20653
20654
20655
20656
20657
20658
20659
20660
20661
20662
20663
20664
20665
20666
20667
20668
20669
20670
20671
20672
20673
20674
20675
20676
20677
20678
20679
20680
20681
20682
20683
20684
20685
20686
20687
20688
20689
20690
20691
20692
20693
20694
20695
20696
20697
20698
20699
20700
20701
20702
20703
20704
20705
20706
20707
20708
20709
20710
20711
20712
20713
20714
20715
20716
20717
20718
20719
20720
20721
20722
20723
20724
20725
20726
20727
20728
20729
20730
20731
20732
20733
20734
20735
20736
20737
20738
20739
20740
20741
20742
20743
20744
20745
20746
20747
20748
20749
20750
20751
20752
20753
20754
20755
20756
20757
20758
20759
20760
20761
20762
20763
20764
20765
20766
20767
20768
20769
20770
20771
20772
20773
20774
20775
20776
20777
20778
20779
20780
20781
20782
20783
20784
20785
20786
20787
20788
20789
20790
20791
20792
20793
20794
20795
20796
20797
20798
20799
20800
20801
20802
20803
20804
20805
20806
20807
20808
20809
20810
20811
20812
20813
20814
20815
20816
20817
20818
20819
20820
20821
20822
20823
20824
20825
20826
20827
20828
20829
20830
20831
20832
20833
20834
20835
20836
20837
20838
20839
20840
20841
20842
20843
20844
20845
20846
20847
20848
20849
20850
20851
20852
20853
20854
20855
20856
20857
20858
20859
20860
20861
20862
20863
20864
20865
20866
20867
20868
20869
20870
20871
20872
20873
20874
20875
20876
20877
20878
20879
20880
20881
20882
20883
20884
20885
20886
20887
20888
20889
20890
20891
20892
20893
20894
20895
20896
20897
20898
20899
20900
20901
20902
20903
20904
20905
20906
20907
20908
20909
20910
20911
20912
20913
20914
20915
20916
20917
20918
20919
20920
20921
20922
20923
20924
20925
20926
20927
20928
20929
20930
20931
20932
20933
20934
20935
20936
20937
20938
20939
20940
20941
20942
20943
20944
20945
20946
20947
20948
20949
20950
20951
20952
20953
20954
20955
20956
20957
20958
20959
20960
20961
20962
20963
20964
20965
20966
20967
20968
20969
20970
20971
20972
20973
20974
20975
20976
20977
20978
20979
20980
20981
20982
20983
20984
20985
20986
20987
20988
20989
20990
20991
20992
20993
20994
20995
20996
20997
20998
20999
21000
21001
21002
21003
21004
21005
21006
21007
21008
21009
21010
21011
21012
21013
21014
21015
21016
21017
21018
21019
21020
21021
21022
21023
21024
21025
21026
21027
21028
21029
21030
21031
21032
21033
21034
21035
21036
21037
21038
21039
21040
21041
21042
21043
21044
21045
21046
21047
21048
21049
21050
21051
21052
21053
21054
21055
21056
21057
21058
21059
21060
21061
21062
21063
21064
21065
21066
21067
21068
21069
21070
21071
21072
21073
21074
21075
21076
21077
21078
21079
21080
21081
21082
21083
21084
21085
21086
21087
21088
21089
21090
21091
21092
21093
21094
21095
21096
21097
21098
21099
21100
21101
21102
21103
21104
21105
21106
21107
21108
21109
21110
21111
21112
21113
21114
21115
21116
21117
21118
21119
21120
21121
21122
21123
21124
21125
21126
21127
21128
21129
21130
21131
21132
21133
21134
21135
21136
21137
21138
21139
21140
21141
21142
21143
21144
21145
21146
21147
21148
21149
21150
21151
21152
21153
21154
21155
21156
21157
21158
21159
21160
21161
21162
21163
21164
21165
21166
21167
21168
21169
21170
21171
21172
21173
21174
21175
21176
21177
21178
21179
21180
21181
21182
21183
21184
21185
21186
21187
21188
21189
21190
21191
21192
21193
21194
21195
21196
21197
21198
21199
21200
21201
21202
21203
21204
21205
21206
21207
21208
21209
21210
21211
21212
21213
21214
21215
21216
21217
21218
21219
21220
21221
21222
21223
21224
21225
21226
21227
21228
21229
21230
21231
21232
21233
21234
21235
21236
21237
21238
21239
21240
21241
21242
21243
21244
21245
21246
21247
21248
21249
21250
21251
21252
21253
21254
21255
21256
21257
21258
21259
21260
21261
21262
21263
21264
21265
21266
21267
21268
21269
21270
21271
21272
21273
21274
21275
21276
21277
21278
21279
21280
21281
21282
21283
21284
21285
21286
21287
21288
21289
21290
21291
21292
21293
21294
21295
21296
21297
21298
21299
21300
21301
21302
21303
21304
21305
21306
21307
21308
21309
21310
21311
21312
21313
21314
21315
21316
21317
21318
21319
21320
21321
21322
21323
21324
21325
21326
21327
21328
21329
21330
21331
21332
21333
21334
21335
21336
21337
21338
21339
21340
21341
21342
21343
21344
21345
21346
21347
21348
21349
21350
21351
21352
21353
21354
21355
21356
21357
21358
21359
21360
21361
21362
21363
21364
21365
21366
21367
21368
21369
21370
21371
21372
21373
21374
21375
21376
21377
21378
21379
21380
21381
21382
21383
21384
21385
21386
21387
21388
21389
21390
21391
21392
21393
21394
21395
21396
21397
21398
21399
21400
21401
21402
21403
21404
21405
21406
21407
21408
21409
21410
21411
21412
21413
21414
21415
21416
21417
21418
21419
21420
21421
21422
21423
21424
21425
21426
21427
21428
21429
21430
21431
21432
21433
21434
21435
21436
21437
21438
21439
21440
21441
21442
21443
21444
21445
21446
21447
21448
21449
21450
21451
21452
21453
21454
21455
21456
21457
21458
21459
21460
21461
21462
21463
21464
21465
21466
21467
21468
21469
21470
21471
21472
21473
21474
21475
21476
21477
21478
21479
21480
21481
21482
21483
21484
21485
21486
21487
21488
21489
21490
21491
21492
21493
21494
21495
21496
21497
21498
21499
21500
21501
21502
21503
21504
21505
21506
21507
21508
21509
21510
21511
21512
21513
21514
21515
21516
21517
21518
21519
21520
21521
21522
21523
21524
21525
21526
21527
21528
21529
21530
21531
21532
21533
21534
21535
21536
21537
21538
21539
21540
21541
21542
21543
21544
21545
21546
21547
21548
21549
21550
21551
21552
21553
21554
21555
21556
21557
21558
21559
21560
21561
21562
21563
21564
21565
21566
21567
21568
21569
21570
21571
21572
21573
21574
21575
21576
21577
21578
21579
21580
21581
21582
21583
21584
21585
21586
21587
21588
21589
21590
21591
21592
21593
21594
21595
21596
21597
21598
21599
21600
21601
21602
21603
21604
21605
21606
21607
21608
21609
21610
21611
21612
21613
21614
21615
21616
21617
21618
21619
21620
21621
21622
21623
21624
21625
21626
21627
21628
21629
21630
21631
21632
21633
21634
21635
21636
21637
21638
21639
21640
21641
21642
21643
21644
21645
21646
21647
21648
21649
21650
21651
21652
21653
21654
21655
21656
21657
21658
21659
21660
21661
21662
21663
21664
21665
21666
21667
21668
21669
21670
21671
21672
21673
21674
21675
21676
21677
21678
21679
21680
21681
21682
21683
21684
21685
21686
21687
21688
21689
21690
21691
21692
21693
21694
21695
21696
21697
21698
21699
21700
21701
21702
21703
21704
21705
21706
21707
21708
21709
21710
21711
21712
21713
21714
21715
21716
21717
21718
21719
21720
21721
21722
21723
21724
21725
21726
21727
21728
21729
21730
21731
21732
21733
21734
21735
21736
21737
21738
21739
21740
21741
21742
21743
21744
21745
21746
21747
21748
21749
21750
21751
21752
21753
21754
21755
21756
21757
21758
21759
21760
21761
21762
21763
21764
21765
21766
21767
21768
21769
21770
21771
21772
21773
21774
21775
21776
21777
21778
21779
21780
21781
21782
21783
21784
21785
21786
21787
21788
21789
21790
21791
//! Many files at once: the summaries, the edges between them, and the queries that need both.
//!
//! [`crate::index`] turns one file into a [`FileSummary`]. This module is what holds a project's worth of them
//! and answers the questions that cross a file boundary — which is the whole reason an index exists, and the
//! layer calls `resolve`.
//!
//! # Why the reverse map is built here and not stored
//!
//! A summary stores the includes its own file *writes* — direct edges, one per `#include`. The map from a header
//! back to the files that include it is therefore **derived**, and it is derived here, in memory, from the
//! summaries as they are loaded. Writing it to disk would be storing a conclusion: it is a fact about the graph
//! rather than about any file, so it would have no single file to go stale with, and the first inconsistency
//! between it and the summaries would be invisible. Rebuilding it costs one pass over the includes, which is
//! what the summaries are for.
//!
//! # What visible means here
//!
//! ```text
//! a.h  declares Widget
//! b.h  #include "a.h"
//! c.cpp #include "b.h"      -> Widget is visible in c.cpp
//! d.cpp (nothing)           -> Widget is not visible in d.cpp, even though it is in the project
//! ```
//!
//! So a name is visible in a file when the file **transitively includes** the file that declares it. That is a
//! graph reachability question, and it is answered without re-reading anything: the edges are in the summaries.
//!
//! # The one case this cannot decide, and what it says instead
//!
//! An `#include` written inside an `#if` is a fact about the text, not about a compilation: whether the compiler
//! took that branch depends on macros the index does not have. So a declaration reached only through a
//! **guarded** include is reported as [`Known::Unknown`] rather than as visible or invisible — the same rule the
//! rest of the crate follows, and the reason [`IncludeFact`](crate::summary::IncludeFact) carries a guard at all.

use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
use std::path::{Path, PathBuf};
use std::sync::Arc;

use cpp_parser::CppSyntaxKind;

use super::names::{NameIndex, Posting};
use crate::Visibility;
use crate::file::paths::normalize_path;
use crate::include::graph::Marked;
use crate::preprocess::directive::IncludeForm;
use crate::sema::types::{Type, TypeBindings, parse_type_spelling};
use crate::summary::{DeclFact, DeclKind, FactGuard, FileSummary, MacroFact};
use crate::symbol::{Known, UnknownReason};

/// How many files a visibility walk will cross before giving up.
///
/// A backstop rather than a policy: real include graphs are shallow (the walker's own limit is
/// [`crate::MAX_INCLUDE_DEPTH`]), and a corpus that exceeds this is one whose summaries disagree with its
/// includes — which the visited set already handles. The number is here so that the *round* count of a
/// pathological graph cannot become an unbounded amount of work on a keystroke.
const MAX_VISIBILITY_DEPTH: usize = 128;

/// **Where an `#include` points** — the target a reader asks about by pointing at the header's name.
///
/// The fourth answer a "go to definition" can give, beside a declaration, an overload set and a macro, and the one
/// it was missing: nothing in the file *declares* `vector`, so every question the jump is built out of — the scope
/// walk, the index by name, the macro table — answers nothing at all for `#include <vector>`, and a reader who
/// ctrl-clicks it is told there is no definition to go to.
///
/// The name is the spelling between the delimiters (`vector`, `sys/types.h`), which is what the resolver searched
/// for and what a reader wrote; the delimiters are the *form*, which is why [`HeaderTarget::form`] is separate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HeaderTarget {
    /// The spelling between the delimiters, and — for [`IncludeForm::Macro`] — the macro's name.
    pub spelling: String,
    pub form: IncludeForm,
    /// The directive, as a range in the file **being edited**, which is what a client highlights.
    ///
    /// The whole `#include <vector>` rather than the name inside it, and that is the honest range: a jump to a
    /// header lands at the top of a file whose contents have nothing to do with this one, and highlighting the
    /// directive that asked for it is what tells the reader *why* they are looking at it.
    pub range: cpp_parser::SourceRange,
    /// The file it resolved to, as a path a client can open.
    pub resolved: PathBuf,
}

/// The `#include` whose **directive** covers `offset`, if there is one and it resolved.
///
/// # What it answers, and what it deliberately does not
///
/// * `Yes(target)` — the cursor is on an `#include` line and the resolver found the file. The spelling is the one
///   written, which is what a client shows; the path is where the file is, which is what it opens.
/// * `Unknown(NotDeclaredHere)` — the line is an `#include` and **nothing was found** for it: a header outside every
///   search path, or one whose file was deleted since. Not `No`, and the distinction is the one the rest of this
///   module keeps: "the index cannot see it" is a different claim from "there is no such thing".
/// * `Unknown(UnparsableName)` — the cursor is not on an `#include` at all. Either nothing is here, or what is here
///   is a different kind of name (a macro include's target is [`ProjectIndex::macro_definition`]'s question).
/// * `Unknown(ConditionalCompilation)` — the `#include` is inside an `#if` this layer cannot evaluate, so whether
///   the file is part of the translation unit is not known.
///
/// The directive's own range is what the cursor is matched against rather than the header-name token, and the two
/// differ on purpose: a reader who points at `#include` or at the `<` means the same thing as one who points at
/// `vector`, and the tree has no node for the second half of the line when the lexer never folded it.
pub fn header_at(
    index: &ProjectIndex,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    offset: usize,
) -> Known<HeaderTarget> {
    // The tree answers *which line*, because only the tree knows where the cursor is; the summary answers *where it
    // points*, because resolution happened when the file was read and re-running the search here would be a second
    // implementation of the resolver.
    let Some((spelling, name_range)) = crate::sema::resolve::header_name_at(root, offset) else {
        return Known::Unknown(UnknownReason::UnparsableName);
    };

    let Some(summary) = index.summary(path) else {
        // The file's own reading is not in the index, so nothing here knows where its includes resolved. The
        // spelling is what the caller pointed at, and saying it is better than an empty reason.
        return Known::Unknown(UnknownReason::UnresolvedInclude(Box::from(
            spelling.as_str(),
        )));
    };

    // The fact whose **directive** covers the name: `range` is the whole `#include …` line, and the name sits
    // inside it. A file has few includes, so this is a scan of a handful of ranges.
    let Some(fact) = summary.includes.iter().find(|include| {
        include.range.start_offset <= name_range.start_offset
            && include.range.end_offset() >= name_range.end_offset()
    }) else {
        return Known::Unknown(UnknownReason::UnparsableName);
    };

    match fact.guard {
        FactGuard::Unconditional => {}
        FactGuard::Region(_) => {
            // The directive is inside an `#if`. Whether it is part of the translation unit is a question this
            // layer answers elsewhere (`index::environment::visibility_at`) and this query does not ask, so the
            // honest answer is the one every other conditional answer in this module gives.
            return Known::Unknown(UnknownReason::ConditionalCompilation);
        }
    }

    // **A macro include's target is a macro.** `#include HEADER` names a name, and what it expands to is the
    // preprocessor's answer — which is the same question `#define` answers, so it goes to the same place rather
    // than being guessed at here.
    if fact.form == IncludeForm::Macro {
        return Known::Unknown(UnknownReason::UnresolvedInclude(Box::from(
            fact.spelling.as_str(),
        )));
    }

    match &fact.resolved {
        Some(resolved) => Known::Yes(HeaderTarget {
            spelling: fact.spelling.clone(),
            form: fact.form,
            range: fact.range,
            resolved: resolved.clone(),
        }),
        // **The search ran and found nothing** — the header is on no include path this project configured, or the
        // file it named has been deleted since. `UnresolvedInclude` is exactly this reason, and it is the one the
        // rest of the crate already uses for a declaration reachable only through an include nobody could find.
        None => Known::Unknown(UnknownReason::UnresolvedInclude(Box::from(
            fact.spelling.as_str(),
        ))),
    }
}

/// Which declaration something refers to, using **both** layers.
///
/// The entry point a feature should call, and the reason it exists rather than each caller composing the two:
/// C++ resolves a name in a fixed order, and getting that order wrong is a jump to the wrong file rather than an
/// error. The order is:
///
/// ```text
/// 1. this file's scopes        — a local shadows a header's declaration, always
/// 2. this file's own top-level — a declaration written here is not the header's
/// 3. the headers it includes   — reached through the include graph
/// ```
///
/// # What it takes, and why each half is a reference
///
/// `scopes` and `root` are the file's own analysis, which [`crate::build_scopes`] and the parser produce — the
/// caller has them because it just parsed the file. The index holds the *other* files. Neither is derivable from
/// the other: the index has no scopes for the open buffer, and the scopes know nothing outside it.
///
/// # The two reasons that reach step 3, and the one that does not
///
/// [`UnknownReason::NotDeclaredHere`] means the name is not in this file, which is exactly what step 3 is for.
/// [`UnknownReason::Ambiguous`] does **not** mean that: the name *is* here, more than once, and looking in the
/// headers would be answering a different question. So it stops.
///
/// Everything else stops too — a name that could not be read, a conditional the analysis cannot evaluate — for
/// the same reason: the failure is not "not here".
pub fn definition_across_files(
    index: &ProjectIndex,
    declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    offset: usize,
) -> Known<ProjectDefinition> {
    match definitions_across_files(index, declaring, scopes, root, path, offset) {
        Known::Yes(mut found) => {
            // **A synonym is not a second entity, and a definition beats a forward declaration.** Both rules were in
            // `ProjectIndex::definition` and neither was here, so every query on this path answered `Ambiguous` for a
            // name a module re-exports: measured on `test_module`'s `import std;` file, `std::cout` had two candidates
            // — `std.cc:1588 using std::cout;` (kind `Other`) and `iostream:65 extern ostream cout;` — and `std::map`
            // had three: the same kind of synonym, the **definition** in `stl_map.h`, and a forward declaration in
            // `stl_multimap.h`. See `docs/buglist.md` section 10.
            if found
                .found
                .iter()
                .any(|declaration| declaration.fact.kind != DeclKind::Other)
            {
                found
                    .found
                    .retain(|declaration| declaration.fact.kind != DeclKind::Other);
            }
            if found.found.len() > 1 {
                let definitions: Vec<&ProjectDefinition> = found
                    .found
                    .iter()
                    .filter(|declaration| declaration.fact.definition)
                    .collect();
                if let [only] = definitions.as_slice() {
                    return Known::Yes((*only).clone());
                }
                // **Several *definitions* of one type are a class template and its specializations**, and the general
                // one is the one with the most template parameters: `std::vector` has the primary in `stl_vector.h`
                // (two) and the `vector<bool>` specialization in `stl_bvector.h` (one), and a reader jumping on
                // `std::vector` means the primary. Restricted to `Type`, because a **function** overload set is
                // several definitions too and "the most parameters" would pick one for a call nobody made.
                if definitions.len() > 1
                    && definitions
                        .iter()
                        .all(|declaration| declaration.fact.kind == DeclKind::Type)
                    && let Some(general) = definitions
                        .iter()
                        .max_by_key(|declaration| declaration.fact.parameters.len())
                {
                    return Known::Yes((*general).clone());
                }
            }
            match found.found.len() {
                1 => Known::Yes(found.found.remove(0)),
                _ => Known::Unknown(UnknownReason::Ambiguous(Box::from(
                    // The spelling the cursor wrote, read back from the tree rather than taken from the list: a reader
                    // asking "which `find` is this" wants the name they pointed at, not the qualified name of whichever
                    // overload happens to sort first.
                    crate::sema::resolve::qualified_name_at(root, offset)
                        .map(|(written, _)| written)
                        .unwrap_or_default(),
                ))),
            }
        }
        Known::Unknown(reason) => Known::Unknown(reason),
        Known::No => Known::No,
    }
}

/// **[`member_across_files`] as a list** — every declaration of the member, in the class the object's type names.
///
/// # Why this is a different question from "where is this name declared"
///
/// A member written after a `.` is not looked up among the names in scope: it is looked up **in the type of the
/// object**, and the difference is measured on one real file — `line.empty()` asked by name answers with **twelve**
/// declarations of `empty` (every `empty` in the standard library, from classes the reader never mentioned) while
/// asked of the object's type it is `basic_string`'s two. The name query is a heuristic that happens to work often
/// enough to be worth keeping as a fallback; this is the reading.
///
/// The set is [`members_of`]'s, filtered by name: that walk already follows bases and already hides what a nearer
/// level hides, which is exactly the set of declarations a name in this position can refer to — and it is the same
/// walk the completion after `.` shows, so a jump and the list a reader was just looking at cannot disagree.
pub fn member_definitions_across_files(
    index: &ProjectIndex,
    declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    offset: usize,
) -> Known<ProjectDefinitions> {
    let memo = TypeMemo::default();
    let Some(access) = crate::sema::resolve::member_access_at(root, offset) else {
        return Known::Unknown(UnknownReason::UnparsableName);
    };

    if access.member.is_empty() {
        return Known::Unknown(UnknownReason::UnparsableName);
    }

    let Known::Yes((object_type, _)) = type_of_expression_memoed(
        &memo,
        index,
        declaring,
        scopes,
        root,
        path,
        &access.object,
        0,
    ) else {
        let Known::Unknown(reason) = type_of_expression_memoed(
            &memo,
            index,
            declaring,
            scopes,
            root,
            path,
            &access.object,
            0,
        ) else {
            unreachable!("the first match established that this is an `Unknown`")
        };
        return Known::Unknown(reason);
    };

    // **The class, not the type**: `std::vector<int>` is a type and `std::vector` is what has members — and a query
    // handed the whole spelling asks about a class nobody declares, which is one of the shapes that made a member
    // access on a standard container answer nothing. A reference is seen through here because C++ sees through it
    // (a member of a `Widget&` is a member of `Widget`); a pointer is **not**, because reaching the pointee is a `*`
    // the caller writes and this query cannot take for it.
    let Some(class) = member_access_class(&object_type) else {
        return Known::Unknown(UnknownReason::UnknownType(Box::from(
            object_type.to_string(),
        )));
    };

    let members = match members_of(index, scopes, root, path, &class) {
        Known::Yes(members) => members,
        Known::Unknown(reason) => return Known::Unknown(reason),
        Known::No => {
            return Known::Unknown(UnknownReason::UnknownType(Box::from(
                object_type.to_string(),
            )));
        }
    };

    let found: Vec<ProjectDefinition> = members
        .members
        .iter()
        .filter(|member| member.fact.name == access.member)
        .map(|member| ProjectDefinition {
            file: member.file.clone(),
            fact: member.fact.clone(),
        })
        .collect();

    if found.is_empty() {
        // **Not a definite no**: the class may be a template this layer does not instantiate, or inherit from one
        return Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(format!(
            "{class}::{}",
            access.member
        ))));
    }

    Known::Yes(ProjectDefinitions {
        found,
        // A member behind a conditional `#if` inside a class body is a fact of its file like any other, and
        // `members_of` offers what it found; the count is about *includes*, which is a question this path never
        // asks. Zero rather than a guess.
        conditional: 0,
    })
}

/// **[`definition_across_files`] as a list** — see [`ProjectIndex::definitions`] for what the list is.
///
/// The two answers are one query: this one, and the single-answer form restricted to the names that have exactly
/// one declaration. A consumer that can show several locations should ask this one, because "ambiguous" is not an
/// answer a client can use.
pub fn definitions_across_files(
    index: &ProjectIndex,
    declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    offset: usize,
) -> Known<ProjectDefinitions> {
    // **A cursor on a member asks about the object's type, not about the name.** `line.empty()` is
    // `std::basic_string::empty`, and asking by name instead reaches every `empty` in the library — measured, 12
    // declarations against `basic_string`'s 2. So the member question goes first, and the name query answers only
    // when the member question *cannot be asked*:
    //
    // * the object's type is unknown — a heuristic answer beats a dead end, and this is what answered before the
    //   member path existed;
    // * a type that **is** known and does not have the member is not that case: answering with another class's
    //   member of the same name would be a jump to a place the language does not name, which the handler's own
    //   rule ("a wrong location is worse than none") forbids.
    // **Whether the cursor is on a member access**, decided once: the member question below asks it, and the name
    // query needs the same fact for a different reason — see the `NotDeclaredHere` arm at the end.
    let naming_a_member = crate::sema::resolve::member_access_at(root, offset).is_some();
    if naming_a_member {
        match member_definitions_across_files(index, declaring, scopes, root, path, offset) {
            Known::Yes(found) => return Known::Yes(found),
            // The member question could not be asked (the object's type is unknown) **or** was answered with
            // nothing, and both fall through to the name query — which is what answered before the member path
            // existed. The second case is a deliberate trade rather than an oversight: a member list is never a
            // claim of completeness ([`MemberList::unlisted`]), so "this class does not have that member" and "this
            // class's bases could not be read" arrive here looking the same, and a name-based list is a jump that
            // usually lands right rather than no jump at all. Measured: `std::cin.eof()` is inherited through
            // `basic_ios`, and while `std::basic_istream` is declared three times the base walk cannot open it —
            // the name query still has `eof` among its candidates.
            Known::Unknown(_) | Known::No => {}
        }
    }

    match crate::sema::resolve::definitions_at(scopes, root, offset) {
        // **An overload set, which the condition in a signature can narrow.** The scope tree keeps both declarations —
        // measured: the translation unit holds `describe` twice — while the *singular* query takes the first and stops,
        // so `describe(1.5)` answered the `enable_if<is_integral<T>>` overload because it is written first. See
        // [`the_overload_a_call_names`].
        Known::Yes(candidates) if candidates.len() > 1 => {
            let chosen = the_overload_a_call_names(
                index,
                declaring,
                scopes,
                root,
                path,
                offset,
                &candidates,
            )
            .unwrap_or_else(|| candidates[0].clone());
            let scope =
                crate::sema::resolve::qualified_name_at(root, offset).and_then(|(written, _)| {
                    written
                        .rsplit_once("::")
                        .map(|(scope, _)| scope.trim_start_matches("::").to_string())
                        .filter(|scope| !scope.is_empty())
                });
            let local = scopes.declares_a_local(chosen.scope);
            return Known::Yes(ProjectDefinitions::one(ProjectDefinition::from_binding(
                path, chosen, scope, local,
            )));
        }
        Known::Yes(mut candidates) => {
            let binding = candidates.remove(0);
            // The scope the answer was reached *through*, when the cursor wrote one: `ns` for `ns::Widget`. A bare
            // name has none, and a leading `::` means the global name space, which is no scope at all.
            let scope =
                crate::sema::resolve::qualified_name_at(root, offset).and_then(|(written, _)| {
                    written
                        .rsplit_once("::")
                        .map(|(scope, _)| scope.trim_start_matches("::").to_string())
                        .filter(|scope| !scope.is_empty())
                });

            // A definition answer can be a *local*: the cursor is inside the same body the name was declared in,
            // which is exactly when `definition_at` resolves it here rather than sending it to the index. Saying
            // so matters because the caller may hand this answer on to a consumer asking whether the name is
            // reachable elsewhere. Asked before the binding is moved, and from the tree that can answer it.
            let local = scopes.declares_a_local(binding.scope);

            return Known::Yes(ProjectDefinitions::one(ProjectDefinition::from_binding(
                path, binding, scope, local,
            )));
        }
        Known::Unknown(UnknownReason::NotDeclaredHere(name)) => {
            // The single-file layer has already established the spelling, so the project layer is asked about
            // exactly that name rather than re-reading the cursor — and it answers with the list, which is the
            // whole point of this function.
            //
            // **Which list depends on whether the cursor names a member**, and the two differ by a scope rule
            // rather than by a preference. A member access whose object's type is unknown still wants the member
            // (`std::cin.eof()` is the measured case: the base walk cannot open `basic_istream`, and `eof` is
            // reachable only by name), so it asks for every scope. So does a cursor inside a definition written
            // `void C::g() { … }`, whose body may name `C`'s members with no object and no qualifier at all —
            // see [`inside_a_definition_written_with_a_qualifier`]. Everything else is an ordinary name lookup, and
            // an ordinary name does not reach into a class: measured on a two-file project, go-to-definition on
            // `printf` in a `.cpp` answered **three** declarations — a class's member, its out-of-class definition,
            // and `stdio.h`'s `printf` — while the only one the file can name is the last.
            // **A qualified name whose class does not declare it itself** — `Derived::instances`, where `instances`
            // is a static member of `Base`. The scope tree has no binding for it (the derived class declares nothing
            // of that name), while the member walk [`members_of`] goes through the bases. A reader writing the derived
            // class's name is asking for its base's member: measured on `test_cpp/src/classes.cpp:141`,
            // `Derived::instances()` had no hover while `Base::instances()` and `derived.name()` both did.
            if let Some((qualifier, last)) = name.rsplit_once("::")
                && !qualifier.is_empty()
                && !last.is_empty()
                && let Known::Yes(list) = members_of(index, scopes, root, path, qualifier)
            {
                let inherited: Vec<ProjectDefinition> = list
                    .members
                    .into_iter()
                    .filter(|member| member.fact.name == last)
                    .map(|member| ProjectDefinition {
                        file: member.file,
                        fact: member.fact,
                    })
                    .collect();
                if !inherited.is_empty() {
                    return Known::Yes(ProjectDefinitions {
                        found: inherited,
                        conditional: 0,
                    });
                }
            }
            return if naming_a_member || inside_a_definition_written_with_a_qualifier(root, offset)
            {
                index.definitions(&name, path)
            } else {
                index.definitions_in_scope(&name, path)
            };
        }
        Known::Unknown(reason) => return Known::Unknown(reason),
        Known::No => {}
    }

    // `No` from the single-file layer means the offset is not in a name the scopes could place at all — on
    // punctuation, or past the end — so there is nothing to look up anywhere.
    Known::Unknown(UnknownReason::UnparsableName)
}
///
/// A concept's body is written in terms of its parameter, so expanding `integral<double>` means substituting `double` for
/// that name. Read from the concept's own declaration rather than guessed from the use site.
fn the_concept_parameters(root: &cpp_parser::CppSyntaxNode, name: &str) -> Option<String> {
    for declaration in root.descendants() {
        if cpp_parser::CppSyntaxKind::from(declaration.kind())
            != cpp_parser::CppSyntaxKind::ConceptDecl
        {
            continue;
        }
        let text = declaration.text().to_string();
        let Some(at) = text.find('=') else {
            continue;
        };
        let declared = text[..at].split_whitespace().last().unwrap_or_default();
        if declared != name {
            continue;
        }
        // **The `template <…>` is a *sibling* of the `ConceptDecl`**, not part of it: measured, the tree is
        // `Declaration > [TemplateDecl, ConceptDecl]` and the concept node's own text is `concept integral = …`. So the
        // parameter list is read from the enclosing declaration.
        let with_the_parameters = declaration
            .parent()
            .map(|parent| parent.text().to_string())
            .unwrap_or(text);
        return template_parameters_in(&with_the_parameters)
            .into_iter()
            .next();
    }
    None
}

/// **A concept's right-hand side**, found by name: `template <typename T> concept integral = std::is_integral_v<T>;`
/// answers `std::is_integral_v<T>`.
///
/// Searched in the tree the caller holds — the file being edited and, when a `.cpp` is asking, the header its class is
/// declared in, which is the same walk the condition itself takes. Only the *definition* is read: a concept that composes
/// other concepts (`concept signed_integral = integral<T> && is_signed_v<T>`) answers a name this layer cannot expand, so
/// the verdict is `None` and the candidate stays.
fn the_concept_definition(root: &cpp_parser::CppSyntaxNode, name: &str) -> Option<String> {
    for declaration in root.descendants() {
        if cpp_parser::CppSyntaxKind::from(declaration.kind())
            != cpp_parser::CppSyntaxKind::ConceptDecl
        {
            continue;
        }
        let text = declaration.text().to_string();
        let Some(at) = text.find('=') else {
            continue;
        };
        // `concept integral = …` — the name is the word before the `=`.
        let declared = text[..at].split_whitespace().last().unwrap_or_default();
        if declared != name {
            continue;
        }
        let body = text[at + 1..].trim().trim_end_matches(';').trim();
        if !body.is_empty() {
            return Some(body.to_string());
        }
    }
    None
}

/// **The overload a call actually names**, when the condition in its signature can decide it.
///
/// ```cpp
/// template <typename T>
/// typename std::enable_if<std::is_integral<T>::value, std::string>::type describe(T);
/// template <typename T>
/// typename std::enable_if<std::is_floating_point<T>::value, std::string>::type describe(T);
///
/// describe(1.5);      // the second, and only the condition says so
/// ```
///
/// The scope tree keeps **both** declarations — measured, the translation unit holds `describe` twice — and until this
/// function existed the answer was the first of them for either call, because the singular query takes the first binding
/// of the name and stops. What separates the two is the `enable_if` in the *return type*, so the narrowing is:
///
/// * a candidate whose condition is **false** for the call's argument types is dropped;
/// * a candidate with no condition, or with one this layer cannot decide, is **kept** — deleting on "cannot tell" is how
///   a reader loses the overload their program chose;
/// * the answer is used only when exactly one candidate survives.
///
/// The argument types are bound to the declaration's template parameters **in order** (`describe(T)` with
/// `describe(1.5)` binds `T = double`), which is the one deduction this needs and the one it can do exactly.
fn the_overload_a_call_names(
    index: &ProjectIndex,
    declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    offset: usize,
    candidates: &[crate::Binding],
) -> Option<crate::Binding> {
    // **The call the cursor's name is the callee of.** A name that is not called has no arguments, so there is nothing to
    // decide a condition against and the set stands as it is.
    let name = crate::sema::resolve::expression_at(root, offset)?;
    let call = name.ancestors().find(|node| {
        cpp_parser::CppSyntaxKind::from(node.kind()) == cpp_parser::CppSyntaxKind::CallExpr
    })?;
    // **The arguments are the call's children after the callee**, and not always wrapped in an `ArgumentList`: measured,
    // `describe(1.5)` is `CallExpr > [IdentifierExpr, LiteralExpr]`. Asking only for the wrapper found none and answered
    // "this name is not called", which is why the narrowing never ran.
    let arguments: Vec<cpp_parser::CppSyntaxNode> = match call.children().find(|node| {
        cpp_parser::CppSyntaxKind::from(node.kind()) == cpp_parser::CppSyntaxKind::ArgumentList
    }) {
        Some(list) => list.children().collect(),
        None => call.children().skip(1).collect(),
    };
    let argument_types: Vec<Option<String>> = arguments
        .iter()
        .map(|argument| {
            match type_of_expression(index, declaring, scopes, root, path, argument, 0) {
                Known::Yes((found, _)) => Some(found.to_string()),
                _ => None,
            }
        })
        .collect();
    if argument_types.is_empty() {
        return None;
    }

    let mut survivors = Vec::new();
    for candidate in candidates {
        let Some(the_candidate) =
            node_covering(root, candidate.name_range.start_offset, candidate.range)
        else {
            survivors.push(candidate.clone());
            continue;
        };
        // **The whole declaration, not the declarator.** A binding ranges over the declarator — `describe(T value)` —
        // and the `enable_if` is in the *return type*, which is a specifier of the enclosing declaration. Measured: the
        // binding's text was `describe(T value)` for both overloads, so the condition was never found and nothing narrowed.
        let declaration_node = the_candidate
            .ancestors()
            .find(|node| {
                cpp_parser::CppSyntaxKind::from(node.kind())
                    == cpp_parser::CppSyntaxKind::Declaration
            })
            .unwrap_or_else(|| the_candidate.clone());
        let declaration = declaration_node.text().to_string();
        // **A `requires` clause is read from its own node**, because the clause and the declaration that follows it are
        // separated by nothing but a newline: a text scan cannot tell `requires is_integral_v<T>` from
        // `requires is_integral_v<T> std::string describe(T)`. `enable_if` is a name inside the type, so it is found in
        // the text and needs no node.
        let requires_clause = declaration_node
            .descendants()
            .find(|node| {
                cpp_parser::CppSyntaxKind::from(node.kind())
                    == cpp_parser::CppSyntaxKind::RequiresClause
            })
            .map(|node| node.text().to_string())
            .and_then(|text| crate::sema::constraint::a_requires_clause(&text).map(str::to_string));
        let condition_owned = requires_clause.as_deref().map(str::to_string).or_else(|| {
            crate::sema::constraint::the_condition_of(&declaration).map(str::to_string)
        });
        // **A constraint written as a *concept*'s name** — `template <integral T>` — holds no expression to evaluate, so
        // the concept's own definition is found and its right-hand side evaluated with the same bindings. Measured: a
        // pair of overloads gated by `integral`/`floating` stayed an unresolved set and the call answered the first.
        let condition_owned = condition_owned.or_else(|| {
            let name = crate::sema::constraint::a_concept_name(&declaration)?;
            the_concept_definition(root, &name)
        });
        let Some(condition) = condition_owned.as_deref() else {
            // An ordinary function, or a template enabled unconditionally.
            survivors.push(candidate.clone());
            continue;
        };
        let parameters = template_parameters_in(&declaration);
        let bound: Vec<(String, String)> = parameters
            .into_iter()
            .zip(argument_types.iter())
            .filter_map(|(parameter, found)| Some((parameter, found.clone()?)))
            .collect();
        // **A concept the condition names is expanded and decided**, recursively: `signed_integral<T>` is
        // `integral<T> && is_signed_v<T>`, and `integral<T>` is another concept. Without this, a composed concept answered
        // "cannot tell" and both candidates stayed — measured, `describe(1.5)` resolved to the `signed_integral` overload.
        let verdict = crate::sema::constraint::satisfies_with(condition, &bound, &mut |name| {
            the_concept_definition(root, name).and_then(|body| {
                the_concept_parameters(root, name).map(|parameter| (parameter, body))
            })
        });
        match verdict {
            Some(false) => {}
            _ => survivors.push(candidate.clone()),
        }
    }

    (survivors.len() == 1).then(|| survivors.remove(0))
}

/// The names a declaration's `template <…>` introduces, in order — `template <typename T, class U>` answers `["T", "U"]`.
fn template_parameters_in(declaration: &str) -> Vec<String> {
    let Some(at) = declaration.find("template") else {
        return Vec::new();
    };
    let after = &declaration[at + "template".len()..];
    let Some(open) = after.find('<') else {
        return Vec::new();
    };
    let mut depth = 0isize;
    let mut close = None;
    for (index, character) in after[open..].char_indices() {
        match character {
            '<' => depth += 1,
            '>' => {
                depth -= 1;
                if depth == 0 {
                    close = Some(open + index);
                    break;
                }
            }
            _ => {}
        }
    }
    let Some(close) = close else {
        return Vec::new();
    };
    after[open + 1..close]
        .split(',')
        .filter_map(|parameter| {
            // `typename T`, `class U`, `typename... Args` — the name is the last word, and a pack keeps its `...`.
            parameter
                .split_whitespace()
                .last()
                .map(|word| word.trim_end_matches("...").trim().to_string())
                .filter(|word| !word.is_empty())
        })
        .collect()
}

/// The names a declaration's `template <…>` introduces, in order — `template <typename T, class U>` answers `["T", "U"]`.
///
/// A member function defined out of class has its class **in another file**, while the scope tree is built from the
/// text of *this* one: `void C::g() { n = 1; }` opens a function scope whose qualifier names no scope here, so `n` is
/// not in any scope the walk can reach and the project layer is asked instead. `n` may well be `C::n`, which is why
/// the scope rule that drops class members from a bare name ([`ProjectIndex::definitions_in_scope`]) must not be
/// applied inside such a body — it would take away the one answer a `.cpp` has.
///
/// # What it reads, and the direction it can be wrong in
///
/// The identifier immediately before the parameter list's `(`: `void C::g(…)` and `auto C::g(…) -> std::string`
/// define a qualified name, while `std::string g(…)` returns a qualified type and defines an unqualified one. The
/// window is bounded by the last whitespace before the `(`, which is what tells those two apart. Written as a
/// spelling rather than a walk of the grammar's own shapes — the declarator of a definition holds only its
/// parameter list, and the name it declares sits in the specifier sequence, which is the seam
/// `sema::scopes::declarator_as` documents. A miss answers `false` and the scope rule applies; it cannot invent a
/// member, because the query it enables is the one that was made before the rule existed.
fn inside_a_definition_written_with_a_qualifier(
    root: &cpp_parser::CppSyntaxNode,
    offset: usize,
) -> bool {
    let mut node = cpp_parser::token_at(root, offset).and_then(|token| token.parent());

    while let Some(current) = node {
        let is_a_definition = cpp_parser::CppSyntaxKind::from(current.kind())
            == cpp_parser::CppSyntaxKind::Declaration
            && current.children().any(|child| {
                cpp_parser::CppSyntaxKind::from(child.kind())
                    == cpp_parser::CppSyntaxKind::CompoundStat
            });
        if is_a_definition {
            let text = current.text().to_string();
            let before_the_parameters = text.split('(').next().unwrap_or_default();
            let name = before_the_parameters
                .split_whitespace()
                .next_back()
                .unwrap_or_default();
            if name.contains("::") {
                return true;
            }
        }

        node = current.parent();
    }

    false
}

/// The answer to a cross-file question about a macro name.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectMacro {
    pub file: PathBuf,
    /// The `#define` or the `#undef` that settles what the name is at the point asked about.
    pub fact: MacroFact,
}

/// Where the macro name written at `offset` is defined — or that it is not a macro there.
///
/// The entry point for "go to definition" on a macro, and the counterpart of [`definition_across_files`]. It needs
/// no scope tree and no second layer, because a macro query is not a name lookup at all: it is a question about
/// **translation order** — which of the `#define`s and `#undef`s written before this point is the last one — and
/// the index already stores every one of them with the offset it was written at.
///
/// [`UnknownReason::UnparsableName`] when the offset is not on a name at all, which is the ordinary answer for
/// most cursor positions.
pub fn macro_across_files(
    index: &ProjectIndex,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    offset: usize,
) -> Known<ProjectMacro> {
    match crate::sema::resolve::name_at(root, offset) {
        Some((name, _)) => index.macro_definition(&name, path, offset),
        None => Known::Unknown(UnknownReason::UnparsableName),
    }
}

/// **One file's cooked reading, as the index keeps it** — what a compiler sees written there, and what the parse of
/// that text complained about.
///
/// The two travel together because they are one reading of one rendering: a caller that handed over the declarations
/// and dropped the errors would make the index answer "nothing is wrong with this file" for a rendering the parser
/// had something to say about, and a caller that replaced the declarations without replacing the errors would
/// publish the *old* file's errors beside the new file's names.
/// **How many cooked readings are kept** — the map is sparse by design, so this only bounds the closure of the
/// open files, not what a query can answer: a miss falls back to the file`s own reading.
const MAX_COOKED_FILES: usize = 512;

#[derive(Debug, Clone, Default)]
pub struct CookedFile {
    /// The declarations the rendering read as, every range mapped back into the file.
    pub declarations: Vec<DeclFact>,
    /// **The macros the rendering was read with** — and this is the half that answers a question the file's own
    /// reading cannot.
    ///
    /// A rendering has no directives left in it: the preprocessor already chose which branches are compiled, so
    /// every `#define` the rendering contains is one that **is** in force, and every fact here carries
    /// `FactGuard::Unconditional`. The file's own reading keeps all of them, each tagged with the region it was
    /// written in, and every consumer then has to **decide those regions again** — which is a second implementation
    /// of the preprocessor's own decision, and it is the one that keeps being wrong.
    ///
    /// Measured on `vcruntime.h`, which writes `_STL_LANG` once per branch of `#ifdef __cplusplus`: the raw reading
    /// files all three, the last of them `0L`, and a lookup that takes "the last binding at or before this offset"
    /// answers `0L` for a file the compiler read as C++20. The rendering holds the taken one and nothing else, so a
    /// consumer that reads **these** has no region to judge.
    pub macros: Vec<MacroFact>,
    /// The rendering's parse errors, placed in the file — see [`crate::CookedDiagnostic`].
    pub diagnostics: Vec<crate::CookedDiagnostic>,
    /// Errors the parse of the rendering reported that **this file cannot show**, because the text they are about is
    /// not written here.
    ///
    /// Kept with the reading rather than with the caller, because it is what makes "no errors" honest: an empty
    /// [`CookedFile::diagnostics`] beside a non-zero count here means the rendering was not clean and the reader
    /// simply cannot be shown where.
    pub unplaced: usize,
}

impl CookedFile {
    /// A reading that found declarations and nothing to report.
    ///
    /// For a caller with facts and no parse of its own — a test that built a rendering by hand, or a future
    /// producer that reads the declarations back from a cache.
    pub fn declarations(declarations: Vec<DeclFact>) -> Self {
        CookedFile {
            declarations,
            macros: Vec::new(),
            diagnostics: Vec::new(),
            unplaced: 0,
        }
    }
}

impl From<crate::IndexedRendering> for CookedFile {
    /// What the index keeps of a rendering's reading: the declarations, **the macros it was read with**, the errors
    /// this file can show, and the count of the ones it cannot.
    ///
    /// The summary itself is still not kept, and the reason stands: a rendering's **directives and includes** are
    /// empty, because that text was spelled out by this crate rather than by the file, and keeping them would invite
    /// a reader to believe them. Macros are the exception and the point — a rendering's macros are the ones the
    /// preprocessor *chose*, with no region left to judge (see [`CookedFile::macros`]).
    fn from(indexed: crate::IndexedRendering) -> Self {
        CookedFile {
            declarations: indexed.summary.declarations,
            macros: indexed.summary.macros,
            diagnostics: indexed.diagnostics,
            unplaced: indexed.unplaced,
        }
    }
}

/// **What one file was read as**, beyond its own summary: the renderings of it, one per translation unit.
///
/// A file's summary is the file read **on its own** — its own text, its own closure, its own environment. A cooked
/// reading is the file read **inside a program**, and a header can be read by several programs: `a.cpp` that defines
/// `_GNU_SOURCE` before including it and `b.cpp` that does not read *different declarations* out of the same bytes.
/// So the readings are kept per program, and which one a lookup uses is decided by the **asking** file's program —
/// see [`ProjectIndex::the_reading_for`].
///
/// The id a [`Posting`] carries is **`0` for the file's own summary** (which lives in `ProjectIndex::summaries`, not
/// here), `1` for the reading it was cooked into on its own, and `2 + its position` for a program's reading — so a
/// reading keeps its id for as long as the file does and a re-read replaces it in place.
#[derive(Debug, Default)]
struct Readings {
    /// The file rendered in its own translation unit — what the per-file cook produces.
    on_its_own: Option<CookedFile>,
    /// The programs that read it, in the order they did.
    in_a_program: Vec<(u64, CookedFile)>,
    /// The last program to read it, which is the reading a caller that cannot name one gets.
    last: Option<u64>,
}

impl Readings {
    /// The id of a program's reading of this file, if it has one.
    fn id_for(&self, program: u64) -> Option<u32> {
        self.in_a_program
            .iter()
            .position(|(held, _)| *held == program)
            .map(|at| at as u32 + 2)
    }

    /// The reading filed under `id`: `1` is the file's own, `2..` are the programs'. `0` — the file's summary — is
    /// not a cooked reading and answers `None`.
    fn reading(&self, id: u32) -> Option<&CookedFile> {
        match id {
            0 => None,
            1 => self.on_its_own.as_ref(),
            id => self
                .in_a_program
                .get(id as usize - 2)
                .map(|(_, reading)| reading),
        }
    }

    /// The id the file's **own** cooked reading has, if it was ever cooked that way.
    const ON_ITS_OWN: u32 = 1;

    /// The reading a caller gets when it has no program to ask for: the last program's, else the file's own.
    fn any(&self) -> Option<&CookedFile> {
        self.last
            .and_then(|program| self.id_for(program))
            .and_then(|id| self.reading(id))
            .or(self.on_its_own.as_ref())
            .or_else(|| self.in_a_program.first().map(|(_, reading)| reading))
    }

    fn every(&self) -> impl Iterator<Item = (u32, &CookedFile)> {
        self.on_its_own
            .iter()
            .map(|reading| (Self::ON_ITS_OWN, reading))
            .chain(
                self.in_a_program
                    .iter()
                    .enumerate()
                    .map(|(at, (_, reading))| (at as u32 + 2, reading)),
            )
    }
}

/// A project's summaries, and the queries that need more than one of them.
///
/// Built incrementally: [`ProjectIndex::insert`] takes a summary that some other layer produced, which is what
/// keeps this type free of any opinion about parsing, caching or the filesystem.
#[derive(Debug, Default)]
pub struct ProjectIndex {
    /// The summaries, by normalized path.
    summaries: HashMap<String, FileSummary>,
    /// The paths **by sequence number**, which is insertion order: a query over all of them is deterministic rather
    /// than `HashMap`-ordered. A definition jump that returned a different file on each run would be a bug that only
    /// shows up in a test that runs twice.
    ///
    /// A map and not a `Vec` so that forgetting a file is a removal rather than a scan of every path — an edit
    /// forgets its file, and on a project of a hundred thousand files a `retain` per keystroke is a cost with
    /// nothing in it that answers anything.
    order: BTreeMap<u32, String>,
    /// The sequence number each file was given the first time it appeared: the reverse of `order`, and the identity
    /// the name index's postings use. **Never reused** — a forgotten file's number stays retired, so a posting can
    /// never come to point at a different file than it was made for.
    sequence: HashMap<String, u32>,
    next_sequence: u32,

    /// The inverted index — see [`crate::index::names`]. Derived from `summaries` and `cooked`, and updated in the
    /// same call that changes either; nothing else writes it.
    names: NameIndex,
    /// For each file, the files that include it. Derived from the summaries; see the module documentation.
    included_by: HashMap<String, BTreeSet<String>>,
    /// **Which file declares each module** — the second visibility edge, beside `included_by`.
    ///
    /// An `import m;` names a *module*, and the file behind it is the project's business rather than the
    /// preprocessor's: this is the map that turns the name into a file. Only **primary interface units** are here
    /// (see [`ProjectIndex::insert_at`]), because those are the units an importer sees.
    ///
    /// Derived from the summaries like `included_by`, and for the same reason: the visibility walk that needs it
    /// holds summaries and nothing else.
    module_interfaces: HashMap<String, String>,
    /// **Every file a module's interface unit was *rendered* from**, by module name — what an importer sees.
    ///
    /// A module is not a header, so the `#include` reconstruction in `walk_the_module_edges` answers a weaker question
    /// than the module does: it evaluates each guard against a state that is not the unit's, and a header the unit
    /// included behind `_HAS_CXX20` — MSVC's `xstring` behind `<string>` — is dropped. Measured on the reader's
    /// project, from `report.cppm` importing `std`:
    ///
    /// ```text
    /// 151 visible file(s), 4110 in `std`, string=[]        ← no std::string
    /// ```
    ///
    /// while the same question from `main.cpp` answered 173 files and `string=["Type"]` — only because that file also
    /// `#include`s a header that pulls the tree in textually. The unit's rendering already decided every guard, once,
    /// for the module ([`crate::RenderedUnit::walked`], 223 files for `std`), so that list is the answer; this field is
    /// where it is kept, filled by [`ProjectIndex::remember_the_unit_closure`].
    unit_closures: std::sync::Mutex<HashMap<String, Vec<String>>>,
    /// The macros a **compilation** starts with, which no summary can hold: the compiler's predefined names and the
    /// command line's `-D`s.
    ///
    /// Every condition stored in a summary is a question about these, and an index that has not been told them
    /// answers `Unknown` for every condition — which is what this type did before the field existed, and what it
    /// still does for a caller that builds an index by hand. See [`crate::index::environment`] for what the field
    /// is complete about and what it deliberately is not.
    macros: Marked,
    /// **What the cooked reading found**, by normalized path — the declarations a compiler sees, and the errors the
    /// parse of the rendering reported.
    ///
    /// A second reading beside the first, and only these two things of it, for reasons that are all about not
    /// lying: a rendering has no directives, so a cooked summary says `includes: []`, `macros: []`, `guards: []` — a
    /// reader that took those at face value would conclude the file includes nothing and defines nothing — and the
    /// two things a rendering knows that the file's own text does not are what it **declares** (the type a macro
    /// declared, `DECLARE_HANDLE(HWND)` declares `HWND__` and `HWND`; the *scope* a namespace-opening macro put it
    /// in, MSVC's `_STD_BEGIN` being `namespace std {`) and what the **parser said about it** — an error against
    /// text no branch, macro or conditional, keeps out of the compiler's sight.
    ///
    /// **Sparse on purpose**: cooking needs the translation unit's environment, so a caller has this for the files
    /// it actually read rather than for the whole project, and a file with no entry here is one nobody cooked.
    ///
    /// **Per program**, because the same bytes read in two translation units are two answers — see [`Readings`].
    cooked: HashMap<String, Readings>,
    /// **The cooked files in the order they arrived** — what [`ProjectIndex::insert_cooked`] evicts from.
    cooked_order: std::collections::VecDeque<String>,
    /// A visibility walk's answer, by the file it was asked about.
    ///
    /// **The whole-walk memo, beside the per-condition one**, and it exists for the reason the numbers say: the walk
    /// builds the closure once (18 ms over 145 files of the MSVC standard library, measured by
    /// `examples/completion_latency.rs`), and a completion asks the same question on every keystroke — a steady-state
    /// query measured **4–5 ms** with the per-condition memo in place and **84–90 ms** without one. The two memos
    /// share a lifetime and therefore a rule: whatever clears `visibility_answers` clears this, because both are
    /// answers that can only change when what the index holds changes.
    ///
    /// Keyed by the root so that a server with several files open keeps at most one answer per file, and storing the
    /// walk's own `Seen` rather than a copy of the pair because that is what the walk produces.
    ///
    /// # Why an entry carries the files it was made of
    ///
    /// **Clearing the whole map on every insert is what made a keystroke pay for the walk.** A pull cooks (inserts)
    /// before it runs the checks, so every pull walked five closures from scratch: measured on `LuaSyntaxTree.cpp`,
    /// 13.0 / 3.6 / 4.9 / 2.8 / 9.2 ms = 33.5 ms of one 200 ms pull. But a walk's answer depends on exactly the
    /// files it read (their includes, their conditions' macros), so a re-read of a file invalidates precisely the
    /// entries whose closure contains it — and editing `LuaSyntaxTree.cpp` drops the walk *from* `LuaSyntaxTree.cpp`
    /// while the four walks from the headers it includes survive. A file the index has **never** seen still clears
    /// the whole map, because a new file can change how an `#include "x.h"` resolves for a closure that does not
    /// contain it. See [`ProjectIndex::insert_at`] and [`ProjectIndex::forget`].
    visibility: std::sync::Mutex<HashMap<String, CachedWalk>>,
    /// What the **condition** on a guarded `#include` was last answered, by `(file, region)`.
    ///
    /// A memo, not a fact: it is cleared whenever a summary is inserted, because that is the only thing that can
    /// change an answer. It exists because the answer is expensive — evaluating one condition builds the file's
    /// whole closure state (`macros_at`) — and the same question is asked once per query and once per walk, over
    /// hundreds of edges. `std::sync::Mutex` rather than a `RefCell` so the index stays `Sync`: a language server
    /// holds one of these behind a lock, and a cache that cost that property would be a bad trade.
    ///
    /// # What clearing it whole costs a request, measured
    ///
    /// **This is the largest remaining term in a completion's latency, and it is the reason a keystroke is slow
    /// exactly while the index is filling.** Every `insert` drops the whole memo, so the next query re-evaluates
    /// every guarded include in its closure from scratch — and during indexing there is an insert every few
    /// milliseconds, so *every* query pays it. Measured on the fixture `crates/cpp_ls/tests/latency.rs` uses, twelve
    /// completions fired from `didOpen`:
    ///
    /// ```text
    ///   the query's own work   #0 350 ms   #1 598 ms   #2 1270 ms   #3+ 2–5 ms
    ///   (all of it here)       at 821 guarded edges, against 3 ms once the inserts stop
    /// ```
    ///
    /// and the split says it is this memo and not the walk: `visible_declarations_upto`'s collection loop measures
    /// **0–2 ms** and the materialisation of its 548 candidates **1–2 ms** on the same queries, while
    /// `visible_files_with_modules` — which asks this memo for every guarded edge — measures 359–588 ms.
    ///
    /// # What the fix is, so the next round does not have to find it again
    ///
    /// The clear is *correct* and it is too wide. An answer for `(file, region)` can change only if the inserted
    /// summary is one the file's closure contains — reachability is decided by the *includers'* edges, which do not
    /// move when a summary arrives, so `ProjectIndex::dependents_of(inserted)` names exactly the files to invalidate.
    /// Two pieces are needed and neither is written yet:
    ///
    /// * the memo needs to be removable **by file** rather than whole (a second map, `file → keys`, or a `retain`);
    /// * the precise edge case: inserting `X` also makes `X`'s own includes reachable from everything that can see
    ///   `X`, and those are inside `dependents_of(X)` already — but an edge `X → S` first becomes visible to the
    ///   walk when **`X`** is inserted, so `X`'s insert has to invalidate the files that can see `X`, which is the
    ///   same rule with `X` in the inserted role.
    ///
    /// The alternative — the one the `FactGuard::Region` arm's own comment names — is the incremental
    /// `macros_at`/`macro_environment` state, one walk per file with conditions answered as they are reached,
    /// which removes the per-edge cost instead of the invalidation.
    visibility_answers: std::sync::Mutex<HashMap<(String, u32), crate::Visibility>>,
    /// **The inference answers that outlive one request** — see [`ProjectIndex::a_remembered_type`].
    ///
    /// `TypeMemo` lives for one request, so a pull, a hover and the next pull ask the same questions of the same tree
    /// again. The key is the file, the expression's range and text, and its kind; the lifetime rule is the one the memos
    /// above have — **every insert and every forget clears it** — so a hit is always an answer about the index as it
    /// stands. Bounded, and cleared when it reaches the bound: an answer is cheap to recompute and a map that grows with
    /// a session is not.
    type_answers: std::sync::Mutex<HashMap<u64, Known<(Type, PathBuf)>>>,
    /// How many questions the memo answered and how many it had to compute — what says whether it is earning its map.
    type_hits: std::sync::atomic::AtomicU64,
    type_misses: std::sync::atomic::AtomicU64,
    /// **The member lists already built, by `(class, the file whose tree was used)`** — see
    /// [`ProjectIndex::cached_member_list`] for the measurement and for how an entry is invalidated.
    ///
    /// This is the one cache here that outlives a request on purpose: a class's members do not change when a reader
    /// types a character somewhere else, and every diagnostics pull asks for the same handful of classes.
    member_lists: std::sync::Mutex<HashMap<(String, PathBuf), CachedMemberList>>,
    /// **A declaration query's answer, by `(spelling, the file it was asked from)`** — see
    /// [`ProjectIndex::definitions`].
    ///
    /// The same repetition as [`ProjectIndex::member_lists`], one layer down: measured on `LuaSource.cpp`, one
    /// diagnostics pull asked **95 of its 99 slow questions about `std`**, and each cost 0.6–1.3 ms. Within a pull
    /// the name set is tiny (`std`, `std::vector`, a handful of members) and the index does not change while the
    /// checks run, so the answer cannot go stale inside that window.
    ///
    /// Cleared wherever [`ProjectIndex::visibility`] is — an insert, a cook, or a forget — because a fact arriving
    /// is exactly what can change it.
    /// **One verdict per guarded declaration** — see `certain_declarations`. A guard costs a macro walk, and the
    /// same fact is asked again on every pull that names the declaration: measured on the real project, the
    /// uncached filter took a diagnostic pull from **28 ms to 71 ms** (`lsp_status`).
    guard_answers: std::sync::Mutex<HashMap<(PathBuf, usize, u32), crate::Visibility>>,
    /// **The macro environment of one `(name, file)`** — [`ProjectIndex::macro_environment`]'s walk, remembered.
    ///
    /// The walk is the expensive half of every macro question and it does not depend on the offset, but it was done
    /// again for every ask. Measured on neovim (`arglist.c`, 853 files in the closure): **1.19 s per walk**, three
    /// identical walks in a row, and the cost landed on the user as `end`: a hover on a member whose name is a macro
    /// (`buf->b_fnum`) took **3.2 s**, and took 3.2 s *again* on the next hover. `semanticTokens` paid it too — one
    /// walk for the whole file's name set, which is what [`ProjectIndex::macro_names_in_force`] is for.
    ///
    /// Invalidated exactly like [`ProjectIndex::visibility`]: an entry is dropped when a file it read is re-read (the
    /// contributors are recorded with it), and the whole map is cleared when a file the index has never seen arrives,
    /// because that can change how an `#include` resolves for a closure that does not contain it.
    macro_environments: std::sync::Mutex<HashMap<(String, String), CachedMacroWalk>>,
    /// **Every macro name in force in one file** — [`ProjectIndex::macro_names_in_force`]'s walk, remembered.
    ///
    /// Same measurement, same invalidation: the colouring pass asks about every identifier in the file and this is
    /// the one question that needs the whole closure, so it is asked once per file rather than once per request.
    macro_names: std::sync::Mutex<HashMap<String, CachedMacroNames>>,
    definition_answers: std::sync::Mutex<HashMap<(String, String), Known<ProjectDefinitions>>>,
    /// **Every path the index has ever filed**, in normalized form — what tells a *re-read* from a *new file*.
    ///
    /// [`ProjectIndex::known_paths`] outlives [`ProjectIndex::forget`] on purpose: an edit is a forget followed by a
    /// re-read, so at the moment the re-read inserts, the summaries map has no entry for the file — and testing that
    /// map made every keystroke look like a brand-new file, which cleared the whole walk memo that the contributor
    /// rule exists to keep. It is a set of `String` and not of ids because `sequence` goes with the summary (see
    /// `forget`), and because a path that was known once must stay known after it is forgotten.
    known_paths: std::collections::HashSet<String>,
}

/// **What evaluating guarded `#include` conditions has cost**, in asks and nanoseconds — see the `FactGuard::Region`
/// arm and the `[visibility]` probe. Only written when `CPPLS_TRACE_TIME` is on, so a normal run does not touch it.
pub(crate) static CONDITION_ASKS: std::sync::atomic::AtomicU64 =
    std::sync::atomic::AtomicU64::new(0);
pub(crate) static CONDITION_NANOS: std::sync::atomic::AtomicU64 =
    std::sync::atomic::AtomicU64::new(0);

/// One entry of [`ProjectIndex::member_lists`]: the members, and **what the answer was made of**.
///
/// The contributors are the files whose facts the list holds — every member's own file. An entry is dropped when one
/// of them changes, which is the narrowest invalidation that is sound without recording which *bases* were walked:
/// a base's members are in the list and carry the base's file.
///
/// # A list with an `unlisted` base, and the generation it was built at
///
/// A gap — "this base is not declared anywhere I can see" — is a statement about the **files that have been read**, not
/// about the class, so such a list used to be remembered at all: every file that mentioned the class rebuilt it.
/// Measured on a real project: `std::vector<LuaSyntaxNode>` 1.7 ms from one file and **20 ms** from the next, twelve
/// lists built per pull and **zero hits**. Remembering it together with the **number of summaries at the time** is
/// sound instead: a file being read is exactly what can fill the gap, so an entry built at an older count is treated as
/// absent. A pull reads nothing new, so the count does not move and the entry is reused.
#[derive(Debug)]
struct CachedMemberList {
    contributors: Vec<PathBuf>,
    list: MemberList,
    read_at: usize,
}

/// How many member lists [`ProjectIndex::member_lists`] may hold before it is emptied.
///
/// A list is a few hundred [`ProjectMember`]s, each with a `DeclFact`, so an entry is tens to a hundred kilobytes and
/// this is a few tens of megabytes at worst. Cleared whole rather than evicted one at a time: the sets that matter
/// are "the classes this file mentions", which are asked together.
const MAX_CACHED_MEMBER_LISTS: usize = 96;

/// One entry of [`ProjectIndex::macro_environments`]: the answer, and **the files it was made of**.
///
/// The contributor rule is [`ProjectIndex::visibility`]'s, for the same reason: a walk's answer is a function of the
/// files it read, so a re-read of one of them invalidates precisely this entry and nothing else.
#[derive(Debug)]
struct CachedMacroWalk {
    contributors: Vec<String>,
    environment: MacroEnvironment,
}

/// One entry of [`ProjectIndex::macro_names`] — the same shape, for the whole-name-set walk.
#[derive(Debug)]
struct CachedMacroNames {
    contributors: Vec<String>,
    names: std::collections::HashSet<String>,
}

/// How many macro walks each memo may hold before it is emptied.
///
/// An environment is one name's candidates (a handful of facts) and a name set is tens of thousands of short strings,
/// so a few hundred entries is tens of megabytes at worst. Cleared whole when full, like the other memos: the sets
/// that matter are "the names this file asks about", which are asked together.
const MAX_CACHED_MACRO_WALKS: usize = 256;

/// How many declaration answers [`ProjectIndex::definition_answers`] may hold before it is emptied.
///
/// A pull asks for a few dozen spellings and the whole point of the memo is that the repeats hit; the bound is
/// there so that a long-running session cannot grow it without limit, and emptying it costs one pull's lookups.
const MAX_DEFINITION_ANSWERS: usize = 4096;

/// How many guard verdicts [`ProjectIndex::a_guard_is_taken`] may hold before it is emptied.
///
/// One per guarded declaration any lookup has asked about — a few thousand on a standard-library closure, each a
/// `(path, offset, region)` and an enum.
const MAX_GUARD_ANSWERS: usize = 16_384;

/// Which member a `obj.member` or `ptr->member` at `offset` names.
///
/// The first query in this crate that needs a **type**: `size` in `widget.size` is not looked up among the names
/// in scope, it is looked up *in the type of `widget`*. So the answer is built in three steps, each of which
/// already existed:
///
/// ```text
/// 1. read the shape          — the object expression and the member's spelling (sema::resolve)
/// 2. infer the object's type — its declaration's `type_of`, in this file or through the index
/// 3. look the member up      — as the qualified name `<type>::<member>`, which the index already matches
/// ```
///
/// Step 3 is why this was cheap to add: a declaration fact records the qualified spelling of the scope it was
/// written in, so `Widget::size` is a question the existing lookup answers. What is new is step 2, and it is the
/// beginning of the `infer` layer — deliberately narrow: the object has to be a
/// **name**, because inferring the type of an arbitrary expression is a different and much larger problem.
///
/// # The four answers
///
/// * `Yes` — the member, declared in the class the object's type names.
/// * `Unknown(UnknownType)` — the object's type could not be worked out: the object is not a plain name, or its
///   declaration says nothing about its type, or the type's name resolves to nothing.
/// * `Unknown(NotDeclaredHere)` — the type is known and the member is not in it. Not a definite no, for the
///   reason every other answer here is not: the class may be a base class, a template, or declared in a header
///   nobody indexed.
/// * `Unknown(UnparsableName)` — the offset is not on a member access at all.
pub fn member_across_files(
    index: &ProjectIndex,
    declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    offset: usize,
) -> Known<ProjectDefinition> {
    let memo = TypeMemo::default();
    let Some(access) = crate::sema::resolve::member_access_at(root, offset) else {
        return Known::Unknown(UnknownReason::UnparsableName);
    };

    // `w.` with nothing after the operator is a member access with no member, and a *jump* needs something to jump
    // to. The question this answers is which declaration the written name refers to, and there is no written name —
    // so this is the same "nothing to look up" as a cursor on punctuation. That the shape is readable at all is
    // what the completion query needs, and it is why the tolerance lives in the shape reader rather than here.
    if access.member.is_empty() {
        return Known::Unknown(UnknownReason::UnparsableName);
    }

    // The type of the object, which is what decides which class the member is looked for in.
    let Known::Yes((written, _)) = type_of_expression_memoed(
        &memo,
        index,
        declaring,
        scopes,
        root,
        path,
        &access.object,
        0,
    ) else {
        let Known::Unknown(reason) = type_of_expression_memoed(
            &memo,
            index,
            declaring,
            scopes,
            root,
            path,
            &access.object,
            0,
        ) else {
            unreachable!("the first match established that this is an `Unknown`")
        };
        return Known::Unknown(reason);
    };

    let Some(class) = member_access_class(&written) else {
        return Known::Unknown(UnknownReason::UnknownType(Box::from(written.to_string())));
    };

    // **No template substitution here**, and the boundary is worth stating: this query answers "where is this
    // member declared", which is a *place* rather than a type. The pairing that finishes a member of a class
    // template is applied by the callers that ask for its type — see [`NamedDeclaration::type_of`] — and applying
    // it here as well would have to rewrite the fact's own spelling, which is what
    // `DeclFact::type_of` is documented to be *as the file wrote it*.
    let found = member_fact(index, scopes, root, path, &class, &access.member, None);
    let Known::Yes((fact, file)) = found else {
        let Known::Unknown(reason) = found else {
            unreachable!("the first match established that this is an `Unknown`")
        };
        return Known::Unknown(reason);
    };

    Known::Yes(ProjectDefinition { file, fact })
}

/// **The class a member access is asked of** — the type's own class, or the class it points at.
///
/// `p->size` and `(*p).size` are the same question, and a language server cannot ask the user to write the
/// second one: a pointer's member access reaches through the pointer, and every consumer of this layer wants
/// the class on the other side. A **reference** is already seen through by [`Type::class_name`], because C++
/// does that for free; a **pointer** is not, because reaching a pointee is otherwise a `*` the caller writes.
///
/// One level, which is the language's own rule: a `Widget**` needs two `*`s, and a query that kept descending
/// would answer about a class the expression does not name.
///
/// The class is returned **owned** rather than borrowed, because the class of a pointee belongs to a type that
/// is itself a shared handle — and a borrow of it would have to outlive a local, which is the shape that ends
/// in unsafe lifetime extension. One `String` per member query is the price of not doing that.
/// **The braced initialiser a declaration was written with** — `std::pair pair{1, 2}` → `{1, 2}`.
///
/// `deduction_inputs` looks for an `Initializer` node, which is the shape `= value` and `(args)` produce; a braced
/// initialisation puts its list beside the declarator instead, so it needs its own reader. `None` for every declaration
/// that is not initialised with braces, and for one in another file (this layer holds one tree).
fn the_braced_initialiser_of(
    root: &cpp_parser::CppSyntaxNode,
    named: &NamedDeclaration,
) -> Option<cpp_parser::CppSyntaxNode> {
    let NamedDeclaration::Here(binding) = named else {
        return None;
    };
    let declarator = crate::sema::types::declarator_declaring(root, binding.name_range)?;
    let parent = declarator.parent()?;
    // **The list is wrapped**: `Pair p{1, 2.5}` is `InitDeclarator > [Declarator "p", Initializer "{1, 2.5}"]`, and the
    // `Initializer` holds the `InitListExpr`. One hop, not a search: a subtree search would also find a braced list in an
    // argument (`Pair p(make(1))`'s nested calls), which is not this declaration's initialisation.
    let initializer = parent.children().find(|node| {
        cpp_parser::CppSyntaxKind::from(node.kind()) == cpp_parser::CppSyntaxKind::Initializer
    })?;
    initializer.children().find(|node| {
        cpp_parser::CppSyntaxKind::from(node.kind()) == cpp_parser::CppSyntaxKind::InitListExpr
    })
}

/// **A member of the class the cursor is inside** — the second half of C++'s unqualified name lookup.
///
/// Only a bare identifier is considered: `std::make` is qualified, and a qualified name is not looked up among a class's
/// members. The member list is the query that answers (`members_of` walks the bases and substitutes the class's
/// arguments), which is why a member inherited through a template base comes back with a finished type.
pub(crate) fn a_member_of_the_enclosing_class(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    callee: &cpp_parser::CppSyntaxNode,
    // **What the caller does with it.** The card wants the declaration and can show a type the header wrote with the
    // base's parameter in it; the type engine cannot use one, and a wrong type is worse than a refusal.
    a_finished_type_only: bool,
) -> Option<ProjectDefinition> {
    let name = callee.text().to_string();
    let name = name.trim();
    let bare = !name.is_empty()
        && name
            .chars()
            .all(|character| character.is_alphanumeric() || character == '_');
    if !bare {
        return None;
    }
    let class =
        class_of_the_enclosing_definition(scopes, usize::from(callee.text_range().start()))?;
    let Known::Yes(listed) = members_of(index, scopes, root, path, &class) else {
        return None;
    };
    let member = listed
        .members
        .iter()
        .find(|member| member.fact.name == name)?;
    // **A member of a base that is itself a template is not finished here.** `enable_shared_from_this<Node>`'s
    // `shared_from_this` is `_Tp`, and the member list does not carry the base's arguments — printing `_Tp (*)()` (which
    // is what a call of it answered) is worse than saying the type is not known. The refusal is the same one every other
    // unreadable spelling gets.
    let names_a_parameter = |written: &str| {
        written
            .split(|character: char| !character.is_alphanumeric() && character != '_')
            .any(|word| {
                member
                    .fact
                    .parameters
                    .iter()
                    .any(|parameter| !parameter.is_empty() && parameter == word)
            })
    };
    if a_finished_type_only
        && (member
            .fact
            .returns
            .as_deref()
            .is_some_and(names_a_parameter)
            || member
                .fact
                .type_of
                .as_deref()
                .is_some_and(names_a_parameter))
    {
        return None;
    }
    // **No class argument pairing here**: `members_of` has already substituted the class's arguments through its
    // members, so the fact's types are the ones a reader of this class sees.
    Some(ProjectDefinition {
        file: member.file.clone(),
        fact: member.fact.clone(),
    })
}

/// **The values of a braced list, flat** — `{1, 2.5}` and `std::pair{1, 2.5}` are the same values.
///
/// A **construction** writes the type's name as the list's first child and the values as *another* list:
/// `InitListExpr > [IdentifierExpr "std::pair", InitListExpr "{1, 2.5}"]`. A declaration's initialiser is the flat list.
/// The deduction wants the values, so the nested list is opened once.
fn the_elements_of_a_braced_list(
    expression: &cpp_parser::CppSyntaxNode,
) -> Vec<cpp_parser::CppSyntaxNode> {
    let mut elements: Vec<cpp_parser::CppSyntaxNode> = Vec::new();
    for child in expression.children().skip(1) {
        match cpp_parser::CppSyntaxKind::from(child.kind())
            == cpp_parser::CppSyntaxKind::InitListExpr
        {
            true => elements.extend(child.children()),
            false => elements.push(child),
        }
    }
    elements
}

/// **A type a bare expression names** — `std::pair` in `std::pair{1, 2}`, or a written instantiation.
///
/// The question is asked when a braced initialisation's head is not a *name in a scope*: a qualified type written as an
/// expression is an `IdentifierExpr`, which `declaration_of_expression` declines. The index answers whether the spelling
/// is a class, and a spelling that already carries `<…>` is its own type — nothing to look up.
fn a_type_the_expression_names(
    index: &ProjectIndex,
    path: &Path,
    expression: &cpp_parser::CppSyntaxNode,
) -> Option<String> {
    let spelled = expression.text().to_string();
    let spelled = spelled.trim();
    if spelled.is_empty() || spelled.contains(' ') {
        return None;
    }
    if spelled.contains('<') {
        return Some(spelled.to_string());
    }
    let names_a_type = match index.definition(spelled, path) {
        Known::Yes(found) => found.fact.kind == crate::DeclKind::Type,
        // **A name is a type when one of its declarations is one.** `std::string` is an alias (a `Type`) and also has a
        // constructor named `string`, so the name query answers `Ambiguous`; requiring *every* candidate to be a type
        // refused the head of `std::string{"three"}` and, with it, the whole `std::tuple{1, 2.5, std::string{"three"}}`
        // (measured on `basics.cpp`: the tuple deduced to its bare name). A construction needs a class, and a name that
        // any of whose declarations is a type can be one.
        Known::Unknown(UnknownReason::Ambiguous(_)) => index
            .definitions(spelled, path)
            .value()
            .is_some_and(|found| {
                found
                    .found
                    .iter()
                    .any(|declaration| declaration.fact.kind == crate::DeclKind::Type)
            }),
        // **An inline namespace is not part of the name a reader writes.** `std::string` is
        // `using string = basic_string<char>;` inside `std::__cxx11`, so its qualified name is `std::__cxx11::string` and
        // the spelled lookup names nothing — measured on `basics.cpp`, where `std::string{"three"}` answered no type and
        // the `std::tuple{1, 2.5, std::string{"three"}}` around it deduced to its bare name. The retry is the one
        // `members_of` already makes: the last segment, and any candidate that is a type.
        Known::Unknown(_) | Known::No => {
            let bare = spelled.rsplit("::").next().unwrap_or(spelled);
            bare != spelled
                && index.definitions(bare, path).value().is_some_and(|found| {
                    found
                        .found
                        .iter()
                        .any(|declaration| declaration.fact.kind == crate::DeclKind::Type)
                })
        }
    };
    names_a_type.then(|| spelled.to_string())
}

/// **The namespace a namespace alias names** — `views` → `std::ranges::views`.
///
/// A namespace alias's fact is a `Namespace` whose `type_of` is the target's *written* spelling, which may be relative to
/// the scope the alias was declared in (`namespace views = ranges::views;` inside `std`). It is qualified here with that
/// scope when it is unqualified, and `None` is returned for everything that is not an alias — including a real namespace
/// with no members, which is a different answer.
fn a_namespace_aliass_target(index: &ProjectIndex, path: &Path, class: &str) -> Option<String> {
    let found = index.definition(class, path).value()?;
    if found.fact.kind != crate::DeclKind::Namespace {
        return None;
    }
    let written = found.fact.type_of.clone()?;
    if written.contains("::") || written.is_empty() {
        return Some(written);
    }
    match &found.fact.scope {
        Some(scope) => Some(format!("{scope}::{written}")),
        None => Some(written),
    }
}

/// **What a class-template use with no written arguments stands for, from the standard's own guides.**
///
/// `std::tuple{1, 2.5, s}` is `std::tuple<int, double, S>` and `std::pair pair{4, 5}` is `std::pair<int, int>` — the
/// standard fixes both, and neither is readable from libstdc++'s constructors (a constrained variadic template for `tuple`,
/// and a `pair` whose declaring class the walk does not reach). A table is the honest form for a closed set: the names are
/// the standard's, and a class a project calls `pair` is not `std::pair` (the spelling must be `std`-qualified, or the fact
/// must say its scope is `std`).
///
/// The number of elements has to line up with the rule, which is what keeps `std::pair one{1}` from answering a
/// `pair<int>` the language would reject.
fn the_deduction_the_standard_fixes(
    name: &str,
    class_as_written: &str,
    element_types: &[crate::sema::types::Type],
) -> Option<Vec<crate::sema::types::Type>> {
    let plain = class_as_written
        .rsplit("::")
        .next()
        .unwrap_or(class_as_written);
    let in_the_library = class_as_written.contains("std::") || name.starts_with("std::");
    if !in_the_library {
        return None;
    }

    // **Every element, one per parameter** — `pair` takes exactly two, `tuple` as many as are written.
    match plain {
        "pair" if element_types.len() == 2 => {
            return Some(element_types.to_vec());
        }
        "tuple" if !element_types.is_empty() => {
            return Some(element_types.to_vec());
        }
        _ => {}
    }

    // **One argument, from the first element** — the containers whose braced form is
    // `Container(std::initializer_list<T>)`.
    let from_the_first = matches!(
        plain,
        "optional"
            | "vector"
            | "list"
            | "deque"
            | "set"
            | "multiset"
            | "unordered_set"
            | "unordered_multiset"
            | "basic_string"
            | "valarray"
            | "initializer_list"
            | "stack"
            | "queue"
            | "priority_queue"
            | "span"
    );
    if from_the_first && element_types.len() == 1 {
        return Some(element_types.to_vec());
    }
    None
}

/// **The class arguments a braced initialisation deduces** — `std::pair pair{1, 2}` is a `pair<int, int>`.
///
/// C++17's deduction for a class template with no written arguments: the initialiser's elements are the constructor's
/// arguments, and the constructor's parameters say what each template parameter stands for. `deduce_the_parameters` is
/// the pairing (a parameter written as one template parameter, reference qualifiers stripped); this walks the class's
/// constructors, keeps the ones that deduce **every** parameter, and answers only when they agree — the same falsifiable
/// rule the overload arm uses.
///
/// `None` when the spelling already names a type (`pair<int, int>`), when it is not a class template, when an element's
/// type is unknown (a lambda's type is unnamed, and guessing one would print an instantiation nobody wrote), or when the
/// candidates disagree.
#[allow(clippy::too_many_arguments)]
fn the_arguments_a_braced_initialisation_deduces(
    memo: &TypeMemo,
    index: &ProjectIndex,
    declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    elements: &[cpp_parser::CppSyntaxNode],
    spelled: &str,
    depth: usize,
) -> Option<Type> {
    // The written spelling must be a bare class name: a template-id has its arguments already.
    if spelled.contains('<') {
        return None;
    }
    let class = crate::sema::types::parse_type_spelling(spelled);
    let crate::sema::types::Type::Named { name, arguments } = &class else {
        return None;
    };
    if !arguments.is_empty() {
        return None;
    }

    let element_types: Vec<crate::sema::types::Type> = elements
        .iter()
        .filter_map(|element| {
            match type_of_expression_memoed(
                memo,
                index,
                declaring,
                scopes,
                root,
                path,
                element,
                depth + 1,
            ) {
                Known::Yes((type_of, _)) => Some(type_of),
                _ => None,
            }
        })
        .collect();
    // **Every element, or none.** A list with one unknown element cannot say what the class is, and a partial answer
    // would print a `pair<int, _T2>` nobody wrote.
    if element_types.is_empty() || element_types.len() != elements.len() {
        return None;
    }

    // **The class's template parameters, from the declaration or from its own members.**
    //
    // The index's name query is the direct answer, and it declines a spelling written in an expression in a session that
    // has not indexed the project (`std::pair{1, 2}` — the class is declared in the same file). The member list is the
    // query the deduction walks anyway, and every member of a class template carries the class's parameters
    // (`DeclFact::parameters` is what pairs them with a use's arguments), so the fallback is not a second guess: it is the
    // same field, read from a fact that is in hand.
    let declared = index
        .definitions(name, path)
        .value()
        .and_then(|found| {
            found
                .found
                .into_iter()
                .find(|declaration| !declaration.fact.parameters.is_empty())
        })
        .or_else(|| index.definition(name, path).value());
    let class_as_written = match &declared {
        Some(declaration) => declaration.fact.qualified_name(),
        None => name.clone(),
    };
    let constructor_name = class_as_written
        .rsplit("::")
        .next()
        .unwrap_or(&class_as_written);

    let Known::Yes(listed) = members_of(index, scopes, root, path, &class_as_written) else {
        return None;
    };
    let parameters = match declared {
        Some(declaration) if !declaration.fact.parameters.is_empty() => declaration.fact.parameters,
        _ => listed
            .members
            .iter()
            .find(|member| !member.fact.parameters.is_empty())
            .map(|member| member.fact.parameters.clone())?,
    };
    // **The standard's own guides, before the constructors are walked.** The library's constructors are constrained
    // templates (`tuple(_UElements&&...) requires …`), which no pairing of the class's parameters can read; the guide is a
    // fact about the standard rather than about the text. See [`the_deduction_the_standard_fixes`].
    if let Some(deduced) = the_deduction_the_standard_fixes(name, &class_as_written, &element_types)
    {
        return Some(crate::sema::types::Type::Named {
            name: class_as_written,
            arguments: deduced,
        });
    }

    if parameters.is_empty() {
        return None;
    }

    let mut agreed: Option<Vec<crate::sema::types::Type>> = None;
    for constructor in listed
        .members
        .iter()
        .filter(|member| member.fact.kind == crate::DeclKind::Function)
        .filter(|member| member.fact.name == constructor_name)
    {
        let deduced = deduce_the_parameters(
            &parameters,
            constructor.fact.parameter_list.as_deref(),
            &element_types,
        );
        // Every parameter must have been replaced: one left standing is not a deduction.
        let every = deduced.iter().all(|argument| {
            !matches!(argument, crate::sema::types::Type::Named { name, .. }
                if parameters.iter().any(|parameter| parameter == name))
        });
        if !every {
            continue;
        }
        match &agreed {
            Some(previous) if *previous != deduced => return None,
            Some(_) => {}
            None => agreed = Some(deduced),
        }
    }

    agreed.map(|arguments| crate::sema::types::Type::Named {
        name: name.clone(),
        arguments,
    })
}

/// **What a pointer-like class's arrow reaches** — its `element_type`, with the class's parameters substituted.
///
/// The standard's protocol (`std::pointer_traits` is written in terms of it, and `unique_ptr`, `shared_ptr` and `weak_ptr`
/// all take part): `using element_type = _Tp;`. Pairing `_Tp` with the object type's argument is the step that turns
/// `shared_ptr<Node>` into `Node` — without it the member is `_Tp`, which is not a class, and the lookup answered
/// `Unknown` in the handle (`auto twin = node->twin();`).
///
/// `None` for a class that declares no `element_type` (an ordinary pointer, whose pointee the plain reader already
/// strips) and for a substitution that does not land on a class.
pub(crate) fn the_pointee_of_a_handle(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    class: &str,
    arguments: &[crate::sema::types::Type],
) -> Option<(String, Vec<crate::sema::types::Type>)> {
    let written: Vec<String> = arguments
        .iter()
        .map(|argument| argument.to_string())
        .collect();
    let Known::Yes((fact, file)) = member_fact(
        index,
        scopes,
        root,
        path,
        class,
        "element_type",
        Some(&written),
    ) else {
        return None;
    };
    let written_type = fact.type_of.as_deref()?;
    let bindings = member_bindings(index, scopes, root, path, class, arguments);
    let finished = bindings.applied_to(&parse_type_spelling(written_type));
    // **A nested spelling is followed**, which is the ordinary shape in the standard library: `shared_ptr` inherits
    // `__shared_ptr<_Tp>` and `element_type` is written there as `_Tp`, so the fact found through the base walk says
    // `__shared_ptr<_Tp>::element_type`. Substituted, that is `__shared_ptr<Node>::element_type` — a member of the class
    // `__shared_ptr<Node>`, and following it is what answers `Node`.
    let finished = finish_a_nested_name(
        index,
        scopes,
        root,
        path,
        class,
        &bindings,
        finished,
        file,
        vec![fact.name.clone()],
    );
    // **A name that no class declares is not a pointee.** `std::shared_ptr`'s `element_type` is written
    // `typename __shared_ptr<_Tp>::element_type`, and a walk that cannot finish it answers the spelling it started with —
    // a class called `__shared_ptr<Resource>::element_type`, which nothing declares. Handing that back hides the caller's
    // own fallback (following `operator->`'s declared return type), which is the step that does resolve it: measured on
    // `test_cpp`'s `smart_pointers.cpp`, the hover asked for members of that invented name and said
    // "`shared_ptr<Resource>` has no member `identifier`".
    match finished.0 {
        Type::Named { name, arguments } => {
            let declared = index.files_declaring(base_type_name(&name), path);
            declared
                .iter()
                .any(|declaration| declaration.fact.kind == crate::DeclKind::Type)
                .then_some((name, arguments))
        }
        _ => None,
    }
}

fn member_access_class(written: &Type) -> Option<String> {
    if let Some(class) = written.class_name() {
        return Some(class.to_string());
    }

    written.pointee()?.class_name().map(str::to_string)
}

/// **The class a member access is asked of, and the arguments that finish its members' types.**
///
/// The two halves come from one place because they come from one *step*, and there are two callers — the member
/// read as a value (`v.front`) and the member called (`v.back()`) — which had them apart and disagreed for exactly
/// as long as that lasted. Measured: `x.back()` on a `std::string` answered `char&` while `auto y = x.back()`
/// answered `_Elem&`, because the second caller paired the class's parameters with an empty argument list.
///
/// The arguments are the ones the **use** wrote when it wrote any (`std::vector<int>::data`), and otherwise the
/// ones the **alias** carried (`std::string` → `basic_string<char, char_traits<char>, allocator<char>>`): a use
/// that wrote none has not said nothing, it has said "whatever the name it used stands for". See
/// [`resolve_aliases_with_arguments`].
fn member_access_class_and_arguments(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    class: &str,
    written: &Type,
) -> (String, Vec<Type>) {
    let (class, from_the_alias) = resolve_aliases_with_arguments(index, scopes, root, path, class);

    let arguments = if written.arguments().is_empty() {
        from_the_alias
    } else {
        written.arguments().to_vec()
    };

    (class, arguments)
}

/// **What of a member list may be offered at this cursor** — both rules, in one place, and the count of what the
/// second one kept out.
///
/// # The two rules
///
/// 1. **The names the implementation owns are not offered**, the same rule the name completion applies — and this is
///    where a user meets them first: `line.` on a `std::string` listed 202 members of MSVC's `basic_string`, half of
///    them `_Alty`, `_ALLOC_MASK`, `_Apply_annotation`. See [`is_reserved_to_the_implementation`].
/// 2. **A member the reader cannot name is not offered.** `private` and `protected` are the difference between what
///    a class *has* and what may be written at a cursor, and offering one is a mistake the reader only discovers by
///    compiling. The level travels on the fact ([`DeclFact::access`]) and is checked against the cursor's own
///    classes — the one it is written in and what that derives from, which are the two the language lets a
///    non-public member be named from.
///
/// # Why one function, when there are two callers
///
/// Because they had one rule each, and a rule with two readers is how this area's bugs have all started: the
/// completion layer reads the shape itself (it already has one from the context reader) while
/// [`member_completions_at`] reads it again, and both then need the same two filters. The filters live here, and the
/// second is *counted* rather than dropped in silence so that a `.` which offers nothing can say which of the two
/// reasons it was — "the class has no members" and "every member of it is `private` from here" are different facts
/// about the program, and only one of them has a fix the reader can apply.
pub(crate) fn offerable_members(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    offset: usize,
    members: &mut MemberList,
) -> usize {
    members
        .members
        .retain(|member| !is_reserved_to_the_implementation(&member.fact));

    let open_to_the_cursor = classes_the_cursor_is_in(index, scopes, root, path, offset);
    let before = members.members.len();

    members.members.retain(|member| {
        let Some(access) = member.fact.access else {
            return true;
        };
        if access.is_open_to_everyone() {
            return true;
        }

        member
            .fact
            .scope
            .as_deref()
            .is_some_and(|owner| open_to_the_cursor.iter().any(|seen| seen == owner))
    });

    before - members.members.len()
}

/// **The classes a cursor is "inside", for access** — the innermost class its offset is written in, and every class
/// that one derives from.
///
/// # Why those two, and only those two
///
/// C++ lets a class name its own `private` members and its descendants name its `protected` ones. So the "us" of
/// `private:` is the class itself and the "us" of `protected:` is the class and everything below it — and one list
/// answers both, because a member's level only has to be checked against the class it is declared in being *in*
/// this list. A member of a class outside it is invisible, whatever its level: a `protected` member of an unrelated
/// class is as unreachable as a `private` one.
///
/// # What it deliberately does not do
///
/// * **Friends.** `friend class X;` and `friend void f();` make declarations visible to something that is not a
///   descendant, and this model records no friends, so a friend's access is reported as unreachable — a member not
///   offered that the reader could in fact write. That is the direction chosen for the whole feature: a name that
///   is missing is a smaller mistake than a name that cannot be written (see [`crate::completion`]).
/// * **Local classes and lambdas inside a member function.** The cursor's class is found from the *scopes* the
///   offset is in, which a lambda's body shares with the enclosing member — so a lambda in a member function sees
///   what the member function sees, which is what the language says.
///
/// Empty when the cursor is not in a class at all — the ordinary case for a `.cpp` file — and the caller then
/// offers only public members.
pub(crate) fn classes_the_cursor_is_in(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    offset: usize,
) -> Vec<String> {
    // The innermost class, from the scope the offset is in. `qualification_prefix_of` is what turns a `ScopeId`
    // into the spelling a `DeclFact` records, and only a class-like scope has one that names a class.
    let Some(innermost) = scopes.scope_at(offset) else {
        return Vec::new();
    };

    let mut classes: Vec<String> = scopes
        .scope_chain(innermost)
        .into_iter()
        .filter(|scope| {
            scopes.scope(*scope).is_some_and(|data| {
                matches!(data.kind, crate::ScopeKind::Class | crate::ScopeKind::Enum)
            })
        })
        .filter_map(|scope| scopes.qualification_prefix_of(scope))
        .collect();

    // …and outward, one level of bases at a time, the same walk [`members_of`] makes in the other direction. A base
    // that cannot be resolved stops its own branch rather than the whole answer: what is known is still known.
    let mut level: Vec<String> = classes.clone();
    let mut depth = 0usize;

    while !level.is_empty() && depth < MAX_NESTED_TYPE_DEPTH {
        let mut next: Vec<String> = Vec::new();

        for class in &level {
            for base in bases_of(index, scopes, root, path, class)
                .value()
                .unwrap_or_default()
            {
                if !classes.contains(&base) {
                    classes.push(base.clone());
                    next.push(base);
                }
            }
        }

        level = next;
        depth += 1;
    }

    classes
}

/// Every member a type has: its own, and the ones it inherits.
///
/// The query a completion after `.` or `->` is built on, and the second one in this module that needs a **type**.
/// It is the *list* form of [`member_across_files`]: that one is given a member's name and answers where it is
/// declared, this one is given nothing but the type and answers what there is to name at all.
///
/// # The base chain is walked here, and never stored
///
/// The one design decision this query makes, and the reason it is a query rather than a field.
///
/// A summary keeps what each file **says**: `struct D : public B` is stored as the spelling `B`, and `D`'s
/// summary says nothing about `B`'s members. The alternative — resolving the bases when the summary is built and
/// writing `D`'s inherited members onto `D` — is what an index-shaped instinct reaches for, and it is wrong for
/// three reasons that all end in a stale answer with nothing on disk to contradict it:
///
/// ```text
/// 1. B gains and loses members          -> D's text and D's key are unchanged, and D's stored list is now wrong
/// 2. D's base list changes              -> caught, because D's text changed
/// 3. *which* B the name `B` means       -> unchanged in D's text, changed by a macro, an include or an
///                                          `#undef`, so D's stored list is wrong with nothing to catch it
/// ```
///
/// The third is the one that settles it: it leaves `D`'s text identical, so no per-file invalidation can see it.
/// Walking the chain at query time costs one lookup per base per query and cannot go stale, because nothing is
/// kept. `a_member_added_to_a_base_appears_without_reindexing_the_derived_class` is that argument as a test.
///
/// # The three things a list can be, and none of them is "these are all the members"
///
/// * `Yes(list)` — the members this analysis can see. `list.unlisted` names the bases that could not be listed
///   at all, so a consumer can tell a complete answer from a truncated one instead of guessing.
/// * `Unknown(NotDeclaredHere)` — nothing visible declares the type. Not `No`: the index holds a subset of the
///   translation unit, so a type from a header nobody indexed looks exactly like a type that does not exist.
/// * `Unknown(ConditionalCompilation)` — the type is only reachable through a guarded `#include`, so whether it
///   is here at all is not known.
///
/// # What it does with a name two bases declare
///
/// Both entries are listed and both are marked [`ProjectMember::ambiguous`]. Dropping one would be choosing, and
/// choosing is the answer the language refuses to give — the same fact [`member_across_files`] states as
/// `Unknown(Ambiguous)` for a single name, stated here as a property of a listed member, because a list with a
/// hole in it would be a worse answer than a list that says which entries are contested.
///
/// # What it deliberately does not do
///
/// * No `using` declarations and no virtual/override resolution. A `using Base::f;` in a derived class brings a
///   name in without declaring a member of its own, and nothing here models that yet.
/// * No access check. A `private` base's members are listed, because access is not in the facts — see
///   [`DeclFact::bases`] — and filtering on a guess would hide members a consumer can legitimately see.
/// * No instantiation. A template class lists the members it was written with; a base written `Base<int>` is
///   looked up as the class `Base`.
///
/// **The members written in the class itself** — [`members_of`]'s first step, and nothing else.
///
/// [`members_of`] answers the question a *reader* asks ("what can I write after `.`"), and it walks the base chain
/// to do it. Measured on `test_module`'s `import std;` file: `members_of("std::vector")` is **ten bases and 583 ms
/// of walking**, while the class's own list costs 16 ms and comes back empty — so the walk was 97% of the answer
/// for a class it could not name a single member of.
///
/// A *check* that only needs the class's own constructors asked that question and paid for the walk on **every
/// pull** (`assign-type-check`: 1 221 ms of a 1 497 ms diagnostic pass, two classes). This is the same first step,
/// exposed: one `direct_members`, measured at 4–16 ms.
pub fn own_members_of(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    class: &str,
) -> Known<Vec<(PathBuf, DeclFact)>> {
    direct_members(index, scopes, root, path, class)
}

/// * No conditional region. A member of a class in the buffer comes back with [`FactGuard::Unconditional`]
///   whatever `#if` it is really in — see `fact_from_binding`. A class from the index does carry its regions.
pub fn members_of(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    class: &str,
) -> Known<MemberList> {
    // **A class's members do not change because a reader typed a character somewhere else.** Every diagnostics pull
    // asks for the same handful of classes — `std::vector`, `std::basic_string`, the file's own types — and each
    // answer costs 4–16 ms (`direct_members`, measured) because it reads the class's facts and walks its bases.
    // Measured on `LuaSource.cpp`: 17 lists, 82 ms of a 157 ms pull, every keystroke. The cache is invalidated by
    // *which files the list was made of*, so an edit to a file that contributes members drops exactly those lists
    // (see [`CachedMemberList`]).
    let started = std::time::Instant::now();
    let key = (class.to_string(), path.to_path_buf());
    if let Some(known) = index.cached_member_list(&key) {
        if crate::probes::timing() && started.elapsed().as_micros() >= 300 {
            eprintln!(
                "[member] {:>5.1} ms  hit   {class}",
                started.elapsed().as_secs_f64() * 1000.0
            );
        }
        return known;
    }

    let listed = members_of_inner(index, scopes, root, path, class);
    // **A bare spelling the index files qualified.** `shared_ptr<int>` is what a type deduced from a `std::` function is
    // written as, and the class is `std::shared_ptr`; a member list asked for the bare name answered `NotDeclaredHere`
    // while the completion at the same cursor offered the members (reported: "`shared_ptr<int>` has no member `reset`"
    // with `reset` in the list next to it). Qualified once, only when the first answer held no class.
    // **An empty answer is also a reason to try the qualified spelling.** A bare class name that resolved to an
    // *ambiguous* declaration answers `Known::Yes` with no members (`direct_members`' own rule for `Ambiguous`), so the
    // retry below — which only ran when the first answer held no class at all — never happened: measured,
    // `members_of("shared_ptr")` answered 0 members while `members_of("std::shared_ptr")` answered 39.
    let listed = match &listed {
        Known::No | Known::Unknown(_) => match class.contains("::") {
            true => listed,
            false => match qualified_from_the_index(index, path, class) {
                Some(qualified) if qualified != class => {
                    members_of_inner(index, scopes, root, path, &qualified)
                }
                _ => listed,
            },
        },
        Known::Yes(list) if list.members.is_empty() && !class.contains("::") => {
            match qualified_from_the_index(index, path, base_type_name(class)) {
                Some(qualified) if qualified != class => {
                    // The arguments the caller wrote are kept: `shared_ptr<Resource>` qualifies to
                    // `std::shared_ptr<Resource>`, which is the spelling the members are then substituted with.
                    let qualified = match class.find('<') {
                        Some(at) => format!("{qualified}{}", &class[at..]),
                        None => qualified,
                    };
                    members_of_inner(index, scopes, root, path, &qualified)
                }
                _ => listed,
            }
        }
        Known::Yes(_) => listed,
    };
    if let Known::Yes(list) = &listed {
        index.remember_member_list(key, list);
    }
    if crate::probes::timing() && started.elapsed().as_micros() >= 300 {
        let held = index
            .member_lists
            .lock()
            .map(|known| known.len())
            .unwrap_or(0);
        eprintln!(
            "[member] {:>5.1} ms  miss  {class}  ({} member(s), {} unlisted base(s), {held} held)",
            started.elapsed().as_secs_f64() * 1000.0,
            match &listed {
                Known::Yes(list) => list.members.len(),
                _ => 0,
            },
            match &listed {
                Known::Yes(list) => list.unlisted.len(),
                _ => 0,
            }
        );
    }

    // The diagnostic that found why `std::ios::` offered nothing: whether a member is *present* and at what depth,
    // which is the difference between "the base walk worked" and "the list happens to be long". Off unless asked
    // for, like this crate's other traces.
    if crate::probes::members()
        && let Known::Yes(list) = &listed
    {
        eprintln!(
            "members_of({class}) -> {} member(s), unlisted {:?}",
            list.members.len(),
            list.unlisted
                .iter()
                .map(|base| format!("{} ({:?})", base.spelling, base.reason))
                .collect::<Vec<_>>()
        );
    }
    listed
}

impl ProjectIndex {
    /// **A member list already built for this class and this file's tree**, if one is held.
    ///
    /// A list whose facts all came from **other** files is the same answer for every file that merely *uses* the class,
    /// so `remember_member_list` files such a list under the empty path too and this lookup falls back to it. The key
    /// keeps the asking path because a class declared in the file being read is resolved against that file's own tree —
    /// a list made *of* this file's facts must not be served to another file, and such a list always has the asking
    /// path among its contributors.
    ///
    /// A list with an `unlisted` base is only as good as the set of files that had been read when it was built, so such
    /// an entry is treated as absent once that set has grown — see [`CachedMemberList`]. A list without a gap never
    /// goes stale by counting.
    fn cached_member_list(&self, key: &(String, PathBuf)) -> Option<Known<MemberList>> {
        let known = self.member_lists.lock().ok()?;
        let read_now = self.summaries.len();
        let cached = known
            .get(key)
            .or_else(|| known.get(&(key.0.clone(), PathBuf::new())))?;
        if !cached.list.unlisted.is_empty() && cached.read_at != read_now {
            return None;
        }
        if crate::probes::members() {
            eprintln!(
                "members_of({}) -> {} member(s), cached",
                key.0,
                cached.list.members.len()
            );
        }
        Some(Known::Yes(cached.list.clone()))
    }

    /// **Remember one member list**, with the files it was made of.
    ///
    /// An **empty** list is not remembered — `direct_members` answers one for a class whose declaration is not in the
    /// index yet, and the contributor set would be empty, so nothing could invalidate it.
    ///
    /// A list with an `unlisted` base **is** remembered, tagged with [`CachedMemberList::read_at`]: the gap is a
    /// statement about the files that have been read, so the entry is valid only while that set does not grow.
    ///
    /// # And a list made of facts that are not cooked is not remembered at all
    ///
    /// A summary is written from the file's **own text** first and revised when the file is **cooked**, and the two
    /// disagree about scope: `_STD_BEGIN` is a name to a reader and `namespace std {` to a compiler, so a class's
    /// members move — and appear — when its header is cooked. Measured on a real project's `<xstring>`:
    /// `std::string* message; message->` offered **one** member before the cook and **58** after, and the
    /// one-member list was then served from this cache for the rest of the session, because none of its contributors
    /// changed and the class was found. A list of uncooked facts is therefore *not* cached: `cooked_reading` answers
    /// for each contributor, and one miss means the facts may still be revised.
    fn remember_member_list(&self, key: (String, PathBuf), list: &MemberList) {
        if list.members.is_empty() {
            return;
        }

        let mut contributors: Vec<PathBuf> = Vec::new();
        for member in &list.members {
            if !contributors.contains(&member.file) {
                contributors.push(member.file.clone());
            }
        }
        if contributors
            .iter()
            .any(|file| self.cooked_reading(file).is_none())
        {
            return;
        }

        let read_at = self.summaries.len();

        if let Ok(mut known) = self.member_lists.lock() {
            if known.len() >= MAX_CACHED_MEMBER_LISTS {
                known.clear();
            }
            // **And under the empty path when no fact came from the asking file**: that list is the index's alone, so
            // every other file that merely uses the class gets the same answer (see `cached_member_list`).
            if !contributors.iter().any(|file| file == &key.1) {
                known.insert(
                    (key.0.clone(), PathBuf::new()),
                    CachedMemberList {
                        contributors: contributors.clone(),
                        list: list.clone(),
                        read_at,
                    },
                );
            }
            known.insert(
                key,
                CachedMemberList {
                    contributors,
                    list: list.clone(),
                    read_at,
                },
            );
        }
    }

    /// **Is the branch this declaration is written in the one the configuration takes?**
    ///
    /// `Unconditional` is a free yes, and a region is a macro walk (`visibility_at`) — so the verdict is memoized:
    /// the same fact is asked again on every pull that names the declaration, and the uncached filter took a
    /// diagnostic pull from **28 ms to 71 ms** on the real project (`lsp_status`). `Unknown` answers **true** — a
    /// guard this layer cannot decide must not become a lookup that says the name is not declared.
    fn a_guard_is_taken(&self, file: &Path, guard: crate::FactGuard, offset: usize) -> bool {
        let region = match guard {
            crate::FactGuard::Unconditional => return true,
            crate::FactGuard::Region(region) => region,
        };
        let key = (file.to_path_buf(), offset, region);
        if let Ok(known) = self.guard_answers.lock()
            && let Some(answer) = known.get(&key)
        {
            return *answer != crate::Visibility::Inactive;
        }
        let visibility = crate::index::environment::visibility_at(self, file, guard, offset);
        if let Ok(mut known) = self.guard_answers.lock() {
            if known.len() >= MAX_GUARD_ANSWERS {
                known.clear();
            }
            known.insert(key, visibility);
        }
        visibility != crate::Visibility::Inactive
    }

    /// **Drop every memoized guard verdict about `path`** — called wherever the index changes for it.
    fn forget_guard_answers(&self, path: &Path) {
        let wanted = normalize(path);
        if let Ok(mut known) = self.guard_answers.lock() {
            known.retain(|(file, _, _), _| normalize(file) != wanted);
        }
    }

    /// **Drop every macro walk whose closure read `path`** — called wherever the index changes for it.
    ///
    /// `known_to_the_index` is [`ProjectIndex::insert_at`]'s question, and the rule is the one that function states for
    /// the visibility walks: a file the index **already knew** can only change the walks that read it, while a file it
    /// has never seen can change how an `#include "x.h"` resolves for a closure that does not contain it, so that one
    /// clears both maps.
    fn forget_macro_walks(&self, path: &Path, known_to_the_index: bool) {
        let wanted = normalize(path);
        if let Ok(mut walks) = self.macro_environments.lock() {
            if known_to_the_index {
                walks.retain(|_, cached| {
                    !cached
                        .contributors
                        .iter()
                        .any(|file| file.as_str() == wanted.as_str())
                });
            } else {
                walks.clear();
            }
        }
        if let Ok(mut names) = self.macro_names.lock() {
            if known_to_the_index {
                names.retain(|_, cached| {
                    !cached
                        .contributors
                        .iter()
                        .any(|file| file.as_str() == wanted.as_str())
                });
            } else {
                names.clear();
            }
        }
    }
    /// **Drop every member list one of whose contributors is `path`** — called wherever the index changes for it.
    ///
    /// The comparison is by [`normalize`], for the reason every path comparison in this file is: a summary is filed
    /// under the resolver's spelling (`c:/…`) while an edit arrives with the client's (`C:\…`).
    fn forget_member_lists(&self, path: &Path) {
        let wanted = normalize(path);
        if let Ok(mut known) = self.member_lists.lock() {
            known.retain(|_, cached| {
                !cached
                    .contributors
                    .iter()
                    .any(|file| normalize(file) == wanted)
            });
        }
    }
}

fn members_of_inner(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    class: &str,
) -> Known<MemberList> {
    // The spelling as the caller wrote it, kept for the one question the resolved one cannot answer: whether this
    // answer came through an alias at all — see the end of this function.
    let original = base_type_name(class).to_string();
    // The spelling is normalized once, at the entry, for the same reason a base's is: a consumer feeding this from
    // `DeclFact.type_of` hands over what the file wrote — `const Widget&`, `::Widget`, `Base<int>` — and every one
    // of those parts is about the type's shape rather than about which class declares the members. Normalizing
    // here also means `declared_in` is a qualified spelling from the first level on, and levels cannot disagree.
    //
    // **And aliases are followed here as well as one level down**, which the measurement is why for: `direct_members`
    // and `direct_member` resolve the spelling before looking anything up, but the *base walk* below asks `bases_of`
    // about the class as it was written — and an alias has no bases, so `members_of("istream")` walked no bases,
    // recorded no gap, and answered 42 members with `unlisted` **empty**, while the resolved spelling
    // (`std::basic_istream`) answered the same 42 and *named* the gap. Two spellings of one type, one of them
    // claiming a completeness it does not have.
    // **An alias whose target nothing declares is a gap, not a class with no members.** The list comes back with the
    // missing class recorded in `unlisted` — the field that exists to say where an answer stops — so a consumer that
    // must not invent findings (`undefined-field`) stays silent instead of reporting every member of `std::string` as
    // undefined. See [`resolve_aliases_or_unresolved`] for the measurement.
    let (resolved, _arguments, missing) =
        resolve_aliases_or_unresolved(index, scopes, root, path, base_type_name(class));
    if let Some(missing) = missing {
        if crate::probes::members() {
            eprintln!("members_of_inner: {class} names {missing}, which nothing declares");
        }
        return Known::Yes(MemberList {
            members: Vec::new(),
            unlisted: vec![UnlistedBase {
                spelling: missing.clone(),
                reason: UnknownReason::NotDeclaredHere(Box::from(missing)),
            }],
        });
    }
    // **An inline namespace is not part of the name a reader writes.** libstdc++ declares the class in `std::__cxx11`
    // (`_GLIBCXX_BEGIN_NAMESPACE_CXX11`) while `std::string`'s alias target is spelled `basic_string<char>` — so once
    // `bits/basic_string.h` is **cooked** (the macro expanded) the scoped lookup for `std::basic_string` answers "not
    // declared" and every `std::string` loses its members: measured on the real project, `std::string` answered 0 with
    // `unlisted: ["std::basic_string"]`, while the *unqualified* lookup found `std::__cxx11::basic_string` at once.
    //
    // The retry is by the **last segment only** — the name the class is declared under, whatever namespaces wrap it —
    // and it runs only when the scoped spelling missed, so a class that is where the spelling says is unaffected.
    let mut class = (*resolved).to_string();
    let own = match direct_members(index, scopes, root, path, &class) {
        Known::Yes(members) => members,
        Known::Unknown(UnknownReason::NotDeclaredHere(_)) => {
            let last = without_the_namespace(&class);
            if last == class {
                return Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(class)));
            }
            match direct_members(index, scopes, root, path, &last) {
                Known::Yes(members) => {
                    class = last;
                    members
                }
                Known::Unknown(reason) => return Known::Unknown(reason),
                Known::No => {
                    return Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(class)));
                }
            }
        }
        Known::Unknown(reason) => return Known::Unknown(reason),
        // `direct_members` reports a name nothing declares as `Unknown(NotDeclaredHere)` rather than as `No` —
        // the index is a subset of the translation unit — so this arm exists for totality, not for a case.
        Known::No => return Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(class))),
    };
    if crate::probes::members() && own.is_empty() {
        eprintln!("members_of_inner: {class} has no own members (after alias resolution)");
    }

    // **A namespace alias answers with its target's members.** `namespace views = ranges::views;` is how libstdc++ spells
    // `std::views`, and the index records it as a `Namespace` whose `type_of` is the target — not as a type alias, so
    // `resolve_aliases_or_unresolved` above steps over it. Measured: `std::ranges::views` answered **100** members and
    // `std::views` answered **0**, with nothing in `unlisted` to say why.
    let mut own = own;
    if own.is_empty()
        && let Some(target) = a_namespace_aliass_target(index, path, &class)
        && let Known::Yes(found) = direct_members(index, scopes, root, path, &target)
        && !found.is_empty()
    {
        own = found;
        class = target;
    }

    let mut list = MemberList::default();
    let mut hidden: HashSet<String> = HashSet::new();
    let mut visited: HashSet<String> = HashSet::from([class.to_string()]);

    // Level 0 is the type's own body. It is not part of the walk below because its members are the ones that
    // *hide*, and a base is only reached after them.
    let mut own: Vec<ProjectMember> = own
        .into_iter()
        .map(|(file, fact)| ProjectMember {
            file,
            fact,
            declared_in: class.to_string(),
            depth: 0,
            ambiguous: false,
        })
        .collect();
    own.sort_by(|one, other| one.fact.name.cmp(&other.fact.name));
    mark_ambiguity(&mut own);
    hidden.extend(recorded_names(&own));
    list.members.extend(own);

    // Then outward, one level of bases at a time — which is the order C++ hides in: a base's member is hidden by
    // a same-named member of anything nearer, so a level that has already contributed a name removes it from
    // every level below.
    //
    // Each base is carried with **the class whose base-clause wrote it**, because that is what decides which scope
    // an unqualified base name is looked up in: see `resolved_in_the_enclosing_scopes`.
    //
    // The class's **own** base list is the one case the walk below cannot report, and it is reported here instead,
    // exactly as a base's is: a class whose bases cannot be read is a truncated list, not a class with no bases.
    // Measured, and it is why the two look different from outside: MSVC's `<istream>` declares `std::basic_istream`
    // **three** times (the class, then `template class _CRTIMP2_PURE_IMPORT basic_istream<char, …>;` twice under
    // `#if defined(_DLL_CPPLIB)`), an ambiguous name answers no base list, and the members inherited from
    // `basic_ios` — `eof`, `fail`, `clear`, … — vanished from the list while `unlisted` stayed **empty**, so the
    // answer did not say it was incomplete.
    // **A template parameter is not a base class.** A base clause is read into *names a class can be looked up by*,
    // and `_Vector_base<_Tp, _Alloc>` produces three of them — the class and both of its arguments — because a base
    // written as `conditional_t<…>` really is one of the names *inside* it (see [`lookup_names`]). The arguments of an
    // ordinary class template are not, and treating them as bases is expensive: `_Tp` is the name of a parameter in
    // hundreds of declarations in a standard-library closure, so the walk asked "who declares `_Tp`" over the whole
    // index — measured on `LuaSource.cpp`, `members_of("std::vector")` called that question twice for **251 ms and
    // 88 ms**, 96% of a member list whose own members cost 1 ms. The rule that removes them is not a heuristic: C++
    // makes a template parameter shadow any name of its class, so a parameter of *this* class can never be its base.
    let parameters = class_template_parameters(index, scopes, root, path, &class);

    // **The base's written spelling, arguments and all.** `bases_of` answers *names a class can be looked up by* — the
    // arguments are dropped there on purpose (they are not bases, and treating one as a base was measured at 251 ms on
    // `std::vector`) — while a member inherited from a **template** base is written in the base's parameters:
    // `enable_shared_from_this<Node>::shared_from_this` returns `_Tp`, and without the arguments nothing downstream can
    // finish it. `raw_bases` reads the clause itself, and the level keeps the spelling.
    let mut level: Vec<(String, String)> =
        match the_base_clauses_of(index, scopes, root, path, &class) {
            Known::Yes(bases) => bases
                .into_iter()
                .filter(|written| !names_a_template_parameter(base_type_name(written), &parameters))
                .map(|written| (written, class.to_string()))
                .collect(),
            Known::Unknown(reason) => {
                list.unlisted.push(UnlistedBase {
                    spelling: class.to_string(),
                    reason,
                });
                Vec::new()
            }
            Known::No => Vec::new(),
        };
    let mut depth = 1;

    while !level.is_empty() {
        let mut found: Vec<ProjectMember> = Vec::new();
        let mut next: Vec<(String, String)> = Vec::new();

        for (written, owner) in level {
            // **The head is resolved where the base clause was written; the arguments are kept as written.**
            let head = base_type_name(&written).to_string();
            let base = resolved_in_the_enclosing_scopes(index, scopes, path, &owner, &head);
            // The spelling a reader sees and the one the members are substituted by: the resolved head with the
            // arguments the clause wrote.
            let shown = match written.find('<') {
                Some(at) => format!("{base}{}", &written[at..]),
                None => base.clone(),
            };
            if !visited.insert(shown.clone()) {
                continue;
            }

            let members = match direct_members(index, scopes, root, path, &base) {
                Known::Yes(members) => members,
                // A base nothing here can resolve. Its members are **missing from the list** rather than absent
                // from the type, and naming the base is what makes the gap actionable — the fix is an include
                // path or a file that was never indexed, not a different query.
                Known::Unknown(reason) => {
                    list.unlisted.push(UnlistedBase {
                        spelling: shown,
                        reason,
                    });
                    continue;
                }
                Known::No => continue,
            };

            // **The base's arguments, applied to its members** — the same substitution the class's own members go
            // through, aliases included. `shown` is a template-id exactly when the clause wrote arguments, and
            // `substituted_members` does nothing for a plain class.
            let listed = MemberList {
                members: members
                    .into_iter()
                    .map(|(file, fact)| ProjectMember {
                        file,
                        fact,
                        declared_in: shown.clone(),
                        depth,
                        ambiguous: false,
                    })
                    .collect(),
                unlisted: Vec::new(),
            };
            let Known::Yes(listed) = substituted_members(index, path, &shown, Known::Yes(listed))
            else {
                continue;
            };
            found.extend(listed.members);

            // **The next level is substituted too**: a base of a base is written in the base's parameters
            // (`_Vector_base<_Tp, _Alloc>` inside `vector<_Tp>`), and those are this level's arguments.
            let further = the_base_clauses_of(index, scopes, root, path, &base);
            match further {
                Known::Yes(clauses) => next.extend(
                    clauses
                        .into_iter()
                        .map(|clause| substitute_a_base_clause(index, path, &shown, &clause))
                        .filter(|clause| {
                            !names_a_template_parameter(base_type_name(clause), &parameters)
                        })
                        .map(|clause| (clause, base.clone())),
                ),
                Known::Unknown(reason) => list.unlisted.push(UnlistedBase {
                    spelling: base,
                    reason,
                }),
                Known::No => {}
            }
        }

        found.retain(|member| !hidden.contains(&member.fact.name));
        found.sort_by(|one, other| one.fact.name.cmp(&other.fact.name));
        mark_ambiguity(&mut found);
        hidden.extend(recorded_names(&found));
        list.members.extend(found);

        level = next;
        depth += 1;
    }

    // **An alias that resolved to a class with no members at all is a gap, not an empty class.**
    //
    // `std::string` is `typedef basic_string<char> string;` inside libstdc++'s `inline namespace __cxx11`, and the
    // class's facts are keyed `std::__cxx11::basic_string`. The alias walk lands on `std::basic_string` — a name the
    // forward declaration does declare — and `direct_members` finds no members under it, so the list came back
    // **empty and complete** and `undefined-field` reported every member of a `std::string` as undefined (measured:
    // ten findings on `CodeFormatCLib/src/CodeFormat.cpp`). The index cannot see that `__cxx11` is inline, so the
    // honest answer is "the answer stops here" — `unlisted` — which is the field that exists for exactly this.
    if list.members.is_empty() && list.unlisted.is_empty() && class != base_type_name(&original) {
        list.unlisted.push(UnlistedBase {
            spelling: class.to_string(),
            reason: UnknownReason::NotDeclaredHere(Box::from(class.to_string())),
        });
    }

    Known::Yes(list)
}

/// **The base clauses a class was written with** — `std::enable_shared_from_this<Node>`, arguments and all.
///
/// `bases_of` answers the *names* a class can be looked up by, which is the right answer for the walk's lookups and the
/// wrong one for a member's type: a member inherited from a template base is written in that base's parameters, and a
/// name without its arguments cannot say what they are. This reads the clause itself — from the file's own tree when the
/// class is in it, and from the fact the index holds otherwise — and falls back to `bases_of` when neither answers, so the
/// walk is never worse than it was.
fn the_base_clauses_of(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    class: &str,
) -> Known<Vec<String>> {
    if let Some(scope) = scopes.scope_with_qualified_name(class)
        && let Some(data) = scopes.scope(scope)
        && let Some(parent) = data.parent
        && let Some(name) = class.rsplit("::").next()
        && let Some(binding) = scopes.scope(parent).and_then(|scope| {
            scope
                .bindings
                .iter()
                .find(|binding| binding.name.identifier_text() == Some(name))
        })
    {
        return Known::Yes(crate::sema::declarations::declared_bases_of(root, binding));
    }
    let base = base_type_name(class).to_string();
    if let Some(declared) = index
        .files_declaring(&base, path)
        .into_iter()
        .find(|declared| declared.fact.kind == crate::DeclKind::Type)
    {
        return Known::Yes(declared.fact.bases.clone());
    }
    bases_of(index, scopes, root, path, class)
}

/// **A base clause with the current level's arguments substituted into it** — `_Vector_base<_Tp, _Alloc>` asked of
/// `vector<int>` is `_Vector_base<int, allocator<int>>`.
///
/// The parameters come from the declaration of the class the clause was written in, and the arguments from `shown`;
/// when either is missing the clause is returned unchanged, which is the direction that keeps the walk going.
fn substitute_a_base_clause(
    index: &ProjectIndex,
    path: &Path,
    shown: &str,
    clause: &str,
) -> String {
    let Some((head, mut arguments)) = split_template_arguments(shown) else {
        return clause.to_string();
    };
    let Some(declared) = index
        .files_declaring(&head, path)
        .into_iter()
        .find(|declared| declared.fact.kind == crate::DeclKind::Type)
    else {
        return clause.to_string();
    };
    // **The arguments written are the first parameters, in order** — the same positional rule
    // `substituted_members` applies for a defaulted parameter list.
    let mut names = declared.fact.parameters.clone();
    names.truncate(arguments.len());
    arguments.truncate(names.len());
    if names.is_empty() {
        return clause.to_string();
    }
    crate::sema::types::substituted_spelling(clause, &names, &arguments)
}

/// Every declaration written **directly in** the class or namespace `class` names.
///
/// The class's own body first, from the file being edited, and then the index — the same two-layer split
/// [`direct_member`] makes, and for the same reason: a buffer that has never been saved has no summary, and a
/// class the buffer does not mention is only in the index.
///
/// [`Known::Yes`] with an empty list is a real answer — a class with nothing in it — and is deliberately not the
/// same as [`Known::Unknown`], which is what a name nothing declares produces. The two are told apart by asking
/// whether the *name* is declared, which is the one question that distinguishes "nothing written in it" from
/// "nothing here knows what it is".
///
/// A name that is not an identifier — a destructor, an operator, a conversion function — comes back with an empty
/// [`DeclFact::name`], exactly as the index stores it. It is a declaration that exists, so it is not dropped here;
/// a consumer that shows a list filters on the name it can print and reads the spelling from the source, which is
/// where it lives.
fn direct_members(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    class: &str,
) -> Known<Vec<(PathBuf, DeclFact)>> {
    // Followed here as well as in `direct_member`, for the same reason it is there: the members of `std::string`
    // are the members of `std::basic_string`, and the member-list query and the single-member query must not
    // disagree about which class a spelling names.
    //
    // **…but the literal spelling is asked first**, because an alias's target can be a spelling no scope has:
    // `typedef struct { int a; int b; } Object;` files its members under **`Object`** — an untagged struct's only name
    // is the typedef's — while `resolve_aliases` turns that spelling into the struct's own *text*
    // (`struct { int a; int b; }`), which names nothing. Measured with `tests/anon_struct_probe.rs`: the facts existed
    // under `Object` (2 postings, 2 visible) and `members_of("Object")` answered an **empty list**. One lookup here
    // costs nothing and keeps the alias path for the shapes it exists for.
    let class = if scopes.scope_with_qualified_name(class).is_some() {
        class.to_string()
    } else {
        resolve_aliases(index, scopes, root, path, class)
    };
    // **A namespace alias in the spelling's prefix** — `std::views::_Filter` is `std::ranges::views::_Filter`. Type aliases
    // are followed above; a namespace alias is not a type, so it needs this step, and it is *additive*: a spelling that
    // already resolves is unchanged.
    let class = through_a_namespace_alias(index, path, &class);
    let class = &class;

    if let Some(scope) = scopes.scope_with_qualified_name(class)
        && let Some(data) = scopes.scope(scope)
    {
        // **The file's shapes once, not once per member.** See [`fact_from_binding_with`] for the measurement: this
        // list is 151 members of `std::vector` on libstdc++, and the per-member form built the table 151 times.
        let shapes = crate::sema::declarations::DeclarationShapes::of(root);
        return Known::Yes(
            data.bindings
                .iter()
                .map(|binding| {
                    (
                        path.to_path_buf(),
                        fact_from_binding_with(&shapes, root, class, binding),
                    )
                })
                .collect(),
        );
    }

    // **A class nested inside another one, spelled without its outer class.**
    //
    // `class outer { public: class inner { … }; };` declares a class whose qualified name is `outer::inner`, while
    // every use written inside `outer` spells it `inner` — and so does every parameter list there:
    // `bool operator!=(const inner &other) const`. The lookup above asks the table for the bare spelling, which is
    // not a key, so the answer fell through to the index, where `definition("inner")` is **Ambiguous**: the class is
    // `inner` in scope `outer`, and its constructor is a declaration named `inner` in scope `outer::inner`. An
    // ambiguous class answered `Known::Yes(empty)` — "that class has nothing written in it" — and `undefined-field`
    // therefore reported **every member** of the class: measured, `` `other` has no member `at_end_` `` on
    // `coroutine.cpp`, whose `generator<T>::iterator` is exactly this shape, and a completion on such a class
    // offered its constructor and nothing else.
    //
    // The scope is in the table and keyed correctly; only the spelling differs, so one scan for a class scope whose
    // last segment is this name answers it. Two such classes is a real ambiguity and answers nothing.
    if let Some(scope) = a_class_nested_in_another(scopes, class)
        && let Some(data) = scopes.scope(scope)
    {
        let shapes = crate::sema::declarations::DeclarationShapes::of(root);
        let qualified = scopes
            .qualified_name_of(scope)
            .unwrap_or_else(|| class.to_string());
        return Known::Yes(
            data.bindings
                .iter()
                .map(|binding| {
                    (
                        path.to_path_buf(),
                        fact_from_binding_with(&shapes, root, &qualified, binding),
                    )
                })
                .collect(),
        );
    }

    let found = index.declarations_in(class, path);
    if !found.is_empty() {
        return Known::Yes(
            found
                .into_iter()
                .map(|declaration| (declaration.file.clone(), declaration.fact.clone()))
                .collect(),
        );
    }

    // **The class spelling a use writes is not the key its facts are stored under, and asking again with the key is
    // not a guess.**
    //
    // `declarations_in` matches `fact.scope == class` **exactly**, and the two strings come from different places:
    // the spelling is what the *use* wrote — for `_Repptr._Lock_and_load()`, the object's type as the declaration in
    // this file spells it, `_Locked_pointer` — while a fact's `scope` is the class's **fully qualified** name,
    // `std::_Locked_pointer`, because MSVC's headers open their namespace with the `_STD_BEGIN` macro.
    //
    // Measured: ten `auto` declarations in `<memory>` were refused as `NotDeclaredHere`, seven of them for
    // `_Locked_pointer::_Lock_and_load` — and the fact was there all along with `scope=std::_Locked_pointer`,
    // `qualified=std::_Locked_pointer::_Lock_and_load`, and the lookup asking for a name without the `std::`.
    //
    // So the class is **resolved**, the same way go-to-definition resolves it, and the retry uses the qualified name
    // its own declaration gives. That is the difference between this and a bare-name fallback: a bare name would
    // answer with a `_Locked_pointer` from anywhere, while this asks *which class the spelling names* and then uses
    // the answer's own identity. The level walk above is unaffected — it works on facts, which are already keyed
    // correctly.
    //
    // **The template arguments come off first**, and they have to: a use writes the type of its object, so the class
    // arrives as `_Locked_pointer<_Ty>` — and a *declaration* is never keyed by that spelling. Measured on the same
    // name: `_Locked_pointer` resolves to `std::_Locked_pointer` while `_Locked_pointer<_Ty>` answers
    // `NotDeclaredHere`, which is why a retry that skipped this step changed nothing at all. The arguments are what
    // [`super::member_bindings`] pairs with the class's parameters *after* the class is found; they are not part of
    // its name.
    if let Known::Yes(resolved) = index.definition(without_arguments(class), path) {
        let qualified = resolved.fact.qualified_name();
        if qualified != *class {
            let found = index.declarations_in(&qualified, path);
            if !found.is_empty() {
                return Known::Yes(
                    found
                        .into_iter()
                        .map(|declaration| (declaration.file.clone(), declaration.fact.clone()))
                        .collect(),
                );
            }
        }
    }

    // Nothing is written *in* it, so the name is either an empty class or no class at all. Which one is decided by
    // the declaration itself rather than by the absence of members: a fact whose own qualified name is the
    // spelling asked about is the class, and everything else that matched did so on its bare name.
    //
    // **`Ambiguous` is that same answer**, and it is the ordinary case for the standard library: a class
    // template is forward-declared and then defined, and the two declarations are one entity written twice.
    // `std::allocator_traits` is exactly this — `xmemory:554` forward-declares it and `755` defines it — and
    // the class declares **no members of its own at all**, because every one of them is inherited from
    // `_Normal_allocator_traits`. Answering `Ambiguous` here says "I cannot tell which class you mean", when
    // the truthful answer is "that class, and it has nothing written directly in it": the members are one
    // level out, which is what the base walk above is for.
    match index.definition(class, path) {
        Known::Yes(found) if found.fact.qualified_name() == *class => Known::Yes(Vec::new()),
        Known::Unknown(UnknownReason::Ambiguous(_)) => Known::Yes(Vec::new()),
        Known::Unknown(reason) => Known::Unknown(reason),
        Known::Yes(_) | Known::No => {
            Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(class.as_str())))
        }
    }
}

/// **The scope of a class whose last name segment is `class`**, when exactly one scope has that name and a
/// qualification — see the call site, which is where the measurement is.
///
/// A table with two of them is an ambiguity and answers `None`: guessing between two nested classes named `inner`
/// would make a member list about a class the reader did not write, and a wrong member list is worse than no list.
fn a_class_nested_in_another(scopes: &crate::ScopeTree, class: &str) -> Option<crate::ScopeId> {
    let mut found = None;
    for (index, scope) in scopes.scopes().iter().enumerate() {
        if scope.kind != crate::ScopeKind::Class || scope.name.as_deref() != Some(class) {
            continue;
        }
        let id = crate::ScopeId(index);
        match scopes.qualified_name_of(id) {
            // Keyed by the spelling asked about: the caller's own branch handles it.
            Some(qualified) if qualified == class => return None,
            Some(_) => {}
            None => continue,
        }
        if found.is_some() {
            return None;
        }
        found = Some(id);
    }
    found
}

/// The names in a level that take part in **hiding**: every member that has a name at all.
///
/// **A destructor, an operator and a conversion function used to be left out of this rule** because a fact stored a
/// lookup key rather than a spelling — `~D` has no identifier in it — so their `DeclFact::name` was `""` and there was
/// nothing to compare them by. That is no longer what a fact holds: `binding.name.text()` answers the spelling
/// (`~Derived`, `operator[]`, `operator int`), for the reason `fact_for` records — an empty name made every
/// destructor answer for its own class and made an operator invisible to a member list. So the hiding rule applies to
/// them like anything else, and it is *right* that it does: `~Derived` and `~Base` are different spellings, so a
/// derived destructor hides nothing it should not, while a derived `operator[]` does hide a base's.
///
/// What is still left out is a member with **no** name at all, which a fact now has only where the source has no
/// spelling to read.
fn recorded_names(members: &[ProjectMember]) -> impl Iterator<Item = String> + '_ {
    members
        .iter()
        .map(|member| member.fact.name.clone())
        .filter(|name| !name.is_empty())
}

/// Flag the members whose name another class at the same level also declares.
///
/// Level-scoped rather than list-scoped, and the difference is the language's: a base's member that a *derived*
/// class redeclares is hidden, so it never reaches this function, while two bases at the same level genuinely
/// leave the name unresolved — the same finding [`member_across_files`] reports as `Unknown(Ambiguous)`.
///
/// **Overloads are not ambiguity.** `void f(); void f(int);` declares one name once, in one class, and a consumer
/// that flagged it would refuse to complete a name the language resolves perfectly well. So what is counted is
/// the number of distinct declaring classes, not the number of declarations.
///
/// A member with no recorded name is skipped for the same reason it takes no part in hiding — see
/// [`recorded_names`] — and skipping it is the conservative direction: claiming two declarations are one contested
/// name would be a definite statement about a name this layer cannot read.
fn mark_ambiguity(members: &mut [ProjectMember]) {
    let mut declaring: HashMap<String, HashSet<String>> = HashMap::new();

    for member in members.iter().filter(|member| !member.fact.name.is_empty()) {
        declaring
            .entry(member.fact.name.clone())
            .or_default()
            .insert(member.declared_in.clone());
    }

    for member in members.iter_mut() {
        member.ambiguous = !member.fact.name.is_empty()
            && declaring
                .get(&member.fact.name)
                .is_some_and(|classes| classes.len() > 1);
    }
}

/// What a completion at a member access should offer: the type, its members, and where to put the chosen one.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MemberCompletions {
    /// The type of the object, as the **lookup key** the members were found under — `Widget`, `ns::Widget`,
    /// `Base` for `Base<int>`.
    ///
    /// The key rather than the spelling the file wrote, because a consumer showing "members of `…`" has to name
    /// something the user can find, and `Base<int>` is a type no member is declared in. It is also the fastest
    /// thing to look at when the list is wrong.
    pub class: String,
    pub members: MemberList,
    /// The range the member's name occupies, which is what a client **replaces** with the chosen one.
    ///
    /// Empty and just past the operator for `w.`, which is the state this query exists for. One field for both
    /// states on purpose: an insert-at-a-point and a replace-a-prefix are the same edit, and a consumer that had
    /// to branch on which one it is would get it wrong exactly once — on the keystroke right after the dot.
    pub member_range: cpp_parser::SourceRange,
    /// What of the name is already written **before the cursor**: `si` for `w.si|`, and empty for `w.|`.
    ///
    /// Not the whole written member, which is why it is computed here rather than taken from the shape: a cursor
    /// in the *middle* of a name — `w.si|ze` — filters by `si` while [`MemberCompletions::member_range`] covers
    /// all of `size`, because the range is what gets replaced and the prefix is what gets matched. A consumer that
    /// used the whole spelling for both would offer nothing while the user is plainly typing.
    pub prefix: String,
    /// **How many members the access level kept out of the list** — counted rather than dropped in silence, so that
    /// a `.` which offers nothing can say which of the two reasons it was: "the class has no members" and "every
    /// member of it is `private` where the cursor is" are different facts about the program, and only one of them
    /// has a fix the reader can apply. See [`DeclFact::access`].
    pub hidden_by_access: usize,
}

/// The members a completion at `offset` should offer: `w.` and `w.si`, answered with `Widget`'s members.
///
/// The third query that needs a **type**, and the one the other two were building towards: [`members_of`] answers
/// "what does this type have" given a type, and this answers "what should be offered here" given a cursor. The
/// steps are all ones that already existed, which is the whole reason it is short:
///
/// ```text
/// 1. read the shape   — the object expression and what of the member is written (completion::context_at)
/// 2. infer the type   — type_of_expression, the recursive inference the member *lookup* already uses
/// 3. list the members — members_of, including the ones the bases declare
/// ```
///
/// # The state it exists for
///
/// `w.` — the operator typed and nothing after it. That is the keystroke that *asks* the question, and the reader
/// above is the one place that decides it is a member access: the parser usually reads `w.` as an access with an
/// empty member, and where a recovery loses that shape the reader falls back to the **text**, which cannot be
/// ambiguous about an operator sitting at the cursor. The same answer covers `w.si`, where the work is only that
/// [`MemberCompletions::member_range`] is the written prefix instead of a point.
///
/// # The answers, and the one that matters most
///
/// * `Yes(completions)` — the members of the object's type.
/// * `Unknown(UnknownType)` — the object's type could not be worked out. **The common case in real code**, and
///   the honest one: `f().size` needs a return type computed, `(*p).size` needs a dereference followed, and
///   `arr[i].size` needs a subscript — see [`members_of`]'s note. A consumer shows
///   nothing rather than offering the members of some other type.
/// * `Unknown(NotDeclaredHere)` — the object's type is a class nothing visible declares.
/// * `Unknown(ConditionalCompilation)` — that class is only reachable through a guarded `#include`.
/// * `Unknown(UnparsableName)` — the cursor is not on a member access at all.
pub fn member_completions_at(
    index: &ProjectIndex,
    declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    offset: usize,
) -> Known<MemberCompletions> {
    let memo = TypeMemo::default();
    // **The shape comes from the completion context, which is the one reader of it.** This used to call
    // `sema::resolve::member_access_at`, which reads the access out of the tree alone, and the two disagree about
    // one offset a client really sends: with the caret drawn **on** the operator's own column (`full2|.`), the
    // grammar's access node ends before the operator, so the tree answers "not a member access" while the context
    // reader — which asks the text as well, for exactly this reason — answers "a member access with nothing
    // written". Measured on a live server: the member list and the diagnostic for the same keystroke said opposite
    // things, and a client asking at the caret's own column got the names in scope.
    //
    // Two readers of one fact is the shape of every bug in this area; the completion layer owns this question, and
    // every consumer of it — this query, `Session::member_completions`, the log line — goes through it.
    let crate::completion::CompletionContext::Member(access) =
        crate::completion::context_at(root, offset)
    else {
        return Known::Unknown(UnknownReason::UnparsableName);
    };

    let written = match type_of_expression_memoed(
        &memo,
        index,
        declaring,
        scopes,
        root,
        path,
        &access.object,
        0,
    ) {
        Known::Yes((written, _)) => written,
        Known::Unknown(reason) => return Known::Unknown(reason),
        // The only `No` the type layer produces is "nothing says what this is", which is the same answer as an
        // expression it cannot type: there is nothing to list members of.
        Known::No => {
            return Known::Unknown(UnknownReason::UnknownType(Box::from(
                access.object.text().to_string().trim(),
            )));
        }
    };

    let Some(class) = member_access_class(&written) else {
        return Known::Unknown(UnknownReason::UnknownType(Box::from(written.to_string())));
    };

    // **`config->` on a smart pointer lists the pointee's members**, not the handle's: `std::shared_ptr<T>` has
    // `operator->`, `get` and `reset`, and the names a reader is reaching for after an arrow are `T`'s (reported from
    // an editor: "and there is no completion either"). Only for an **arrow**, and only when the handle declares
    // `operator->` — an object whose `->` reaches a class it declares no `operator->` for is a pointer, which
    // [`member_access_class`] has already reached through.
    // **The *written* spelling**, not `class`: `member_access_class` has already stripped `shared_ptr<Config>` to
    // `shared_ptr`, and the template arguments are exactly what the handle's `operator->` return type is substituted
    // with. Measured: with the stripped spelling the step declined for want of arguments and the list was the
    // handle's.
    let spelled = written.to_string();
    // **One answer to "which class does this access reach".** The completion's `the_class_after_the_operator` is the
    // reader of that question — it follows a pointer, a class's own `operator->`, a base's (through the substitution
    // composed along the base chain), and the base's `element_type` typedef — and this query used a second
    // implementation that followed only the first two. The two disagreed exactly where a reader notices: on
    // `std::shared_ptr<std::string>`, the completion listed `std::string`'s sixty-eight members while a hover on one
    // of them answered "`std::shared_ptr<std::string>` has no member `c_str`". Asking the completion's answer first
    // makes the list and the hover one answer; `the_class_an_arrow_points_at` stays as the fallback for the shapes it
    // reaches that this one does not (an alias chain the substitution cannot follow).
    // **The shared answer is used only when it names a class**, and that is not a formality: the completion's reader
    // substitutes what it can and answers with the spelling that is left, so a member template's `_Ty2*` comes back
    // as `_Ty2` — a name nothing declares, which a member lookup would answer "no members" for with confidence. The
    // older reader below is the one that walks `element_type` and the aliases for exactly those shapes, so the two
    // are tried in that order rather than one replacing the other.
    let names_a_class = |name: &str| {
        let bare = base_type_name(name);
        index
            .files_declaring(bare, path)
            .iter()
            .any(|found| found.fact.kind == crate::DeclKind::Type && found.fact.type_of.is_none())
    };
    let class = match access.arrow {
        true => crate::completion::the_class_after_the_operator(
            index, scopes, root, path, &written, true,
        )
        .map(|(class, _)| class)
        .filter(|class| names_a_class(class))
        .or_else(|| the_class_an_arrow_points_at(index, scopes, root, path, &spelled, None))
        .unwrap_or(class),
        false => class,
    };

    match members_of(index, scopes, root, path, &class) {
        Known::Yes(mut members) => {
            let hidden_by_access =
                offerable_members(index, scopes, root, path, offset, &mut members);

            Known::Yes(MemberCompletions {
                class: class.to_string(),
                members,
                hidden_by_access,
                member_range: access.member_range,
                prefix: written_before_the_cursor(&access, offset),
            })
        }
        Known::Unknown(reason) => Known::Unknown(reason),
        // `members_of` reports a name nothing declares as `Unknown(NotDeclaredHere)` rather than `No`, so this arm
        // is for totality and says the same thing it would.
        Known::No => Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(class))),
    }
}

/// The part of the member's spelling that lies **before** the cursor.
///
/// Separate from the range because the two answer different halves of the same edit: the range is what the client
/// **replaces** with the chosen name — all of `size`, so nothing of the old spelling is left behind — while this
/// is what a server **matches** against the candidates, and a cursor inside a name has only typed the part before
/// it. Taking the whole spelling for both is what makes `w.si|ze` offer nothing.
///
/// The slice is by byte offset into the member's own text, so it is exactly the written prefix; a cursor that is
/// not on a character boundary (possible in an identifier with non-ASCII letters) falls back to the whole
/// spelling, which is the safe direction — a filter that matches too much still shows something.
fn written_before_the_cursor(access: &crate::sema::resolve::MemberAccess, offset: usize) -> String {
    let start = access.member_range.start_offset;
    let end = access.member_range.end_offset().min(offset);

    if end <= start {
        return String::new();
    }

    access
        .member
        .get(..end - start)
        .unwrap_or(&access.member)
        .to_string()
}

/// One name a completion can offer: where it is declared, and how far out it was found.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OfferedName {
    pub file: PathBuf,
    pub fact: DeclFact,
    /// How many scopes out from the cursor the declaration was found: `0` is a name declared in the scope the
    /// cursor is in — a local, or the scope the `::` named — and larger numbers are enclosing scopes, which C++
    /// only considers once the inner ones have been searched. The order of [`NameCompletions::names`].
    ///
    /// Recorded rather than left to be recomputed, for the reason [`ProjectMember::depth`] is: a consumer showing
    /// locals above globals, or grouping by where a name came from, would otherwise have to reconstruct the walk it
    /// was just handed the result of.
    pub depth: usize,
    /// **How far from the cursor the declaration is in the program text** — the field a consumer ranks by.
    ///
    /// [`OfferedName::depth`] counts *scopes*, which orders a lookup but does not answer the question a suggestion
    /// list is judged by: a local and a name from `zmmintrin.h` can both be depth 2. This says which of them is
    /// nearer — the buffer's own scope, the buffer, a header beside it, a header it includes, or a header only
    /// that header includes — and it is the same order C++ would find them in from the other end.
    ///
    /// Recorded here rather than re-derived by a consumer because the derivation needs the include *graph*, and
    /// the walk that produced this list already crossed it: see [`NameProvenance`].
    pub from: NameProvenance,
}

/// Where a name a completion offers was found, relative to the file the cursor is in.
///
/// Ordered by nearness, so that the ranking can use the enumeration itself as a tier and two consumers cannot
/// disagree about which of two provenances is closer.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum NameProvenance {
    /// A scope of the file being edited: a local, a parameter, a member of the class the cursor's body is in, or
    /// the names written directly in a `::`-qualified scope.
    Scope,
    /// Written at file scope in the file being edited.
    ThisFile,
    /// A header the file being edited includes directly.
    DirectInclude,
    /// A file reached only through another file — the standard library's own headers, mostly.
    IndirectInclude,
}

/// What a completion **in a name** should offer: the scope that was listed, and its names.
///
/// The sibling of [`MemberCompletions`], and the other half of "what can be typed here": that one answers after a
/// `.` or `->`, where the answer is a type's members; this one answers in a name position, where the answer is
/// what is visible — after a `::` (one scope), or with no qualifier at all (the scopes the cursor is inside, from
/// the innermost outward).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NameCompletions {
    /// The scope the names were listed from, as the **lookup key** rather than as the file spelled it: `ns`,
    /// `ns::Widget`, `::` for the global name space, or empty when the cursor wrote no qualifier — there the names
    /// come from the scopes the cursor is inside rather than from one scope.
    pub scope: String,
    /// The names, innermost first and **deduplicated by name**: a declaration in an inner scope hides the same
    /// name in an outer one, which is what C++ does and what keeps a local `count` from being offered beside the
    /// header's. Two declarations of one name in the *same* scope are both kept — that is an overload, not a
    /// choice.
    pub names: Vec<OfferedName>,
    /// What of the name is already written **before the cursor**: `Wid` for `ns::Wid|`, empty for `ns::|`.
    ///
    /// The counterpart of [`MemberCompletions::prefix`], and separate from the range for the same reason.
    pub prefix: String,
    /// The range a client **replaces** with the chosen name: the written segment, or an empty range at the cursor
    /// when the segment has only just begun.
    pub name_range: cpp_parser::SourceRange,
}

/// The names a completion at `offset` should offer: `ns::`, `Widget::`, `::`, and a bare name.
///
/// # The four positions, and one query for all of them
///
/// ```text
/// ns::            one scope: the names written directly in `ns`
/// Widget::        one scope, and its **bases** — a typedef a base declares is nameable through the derived class
/// ::Widget        the global name space only, which is what the leading `::` asks for
/// loc             no qualifier: every name visible from the cursor, innermost scope first
/// ```
///
/// The first three are one question — list the declarations written in a scope — and the fourth is the same
/// question asked of a *chain* of scopes. What differs is only where the scopes come from, which is why this is one
/// query rather than four.
///
/// # The two layers, and when they are merged rather than chosen between
///
/// The file's own scope tree is asked first, because a buffer that has never been saved has no summary — the split
/// every cross-file query in this crate makes. What happens next depends on what the scope *is*, and the difference
/// is the language's:
///
/// * a **class** is defined once, so its members come from one place: the buffer's scope if it has one, the index
///   otherwise. Merging would list the same member twice;
/// * a **namespace** can be reopened, and a file that writes `namespace ns { … }` and includes a header that does
///   the same has both sets of names. So those are merged, the buffer winning a name they both declare;
/// * the **global name space** is a namespace, and is the namespace every included header writes into — the same
///   merge, with the file scope of the buffer as the first contributor.
///
/// # What it will not offer
///
/// A **local** declaration of another file is never in the list. The index cannot place a local in the function it
/// belongs to, so a name lookup there could only guess — and the guess would be wrong in the common case rather
/// than the rare one: the standard library's headers alone declare thousands of locals called `__first` and `n`.
/// See [`DeclFact::local`]. Locals of the file being edited *are* offered, from its own scope tree, which is the
/// only thing that knows which body they are in.
///
/// # The answers
///
/// * `Yes(completions)` — the names, which may be an empty list for a scope that is declared and empty.
/// * `Unknown(UnparsableName)` — the cursor is not in a name or a qualifier: on punctuation, on a keyword, or past
///   the end of what could be one.
/// * `Unknown(NotDeclaredHere)` — the `::` named a scope nothing here declares, so there is nothing to list and no
///   way to say it is empty.
/// * `Unknown(ConditionalCompilation)` — the scope is declared, but only in a file reached through a guarded
///   `#include`, so whether these names are visible depends on macros this layer does not have.
pub fn name_completions_at(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    offset: usize,
) -> Known<NameCompletions> {
    let Some(position) = crate::sema::resolve::name_position_at(root, offset) else {
        return Known::Unknown(UnknownReason::UnparsableName);
    };
    let phase = std::time::Instant::now();
    if crate::probes::completion() {
        eprintln!(
            "[completion] the position: scope {:?}, written {:?}",
            position.scope, position.written
        );
    }

    // **What is typed decides how much is read**, and the difference is not small. The index half of this query
    // collects every declaration of every file the cursor can see — measured on a real file that includes
    // `<string>`, **1103** names at one cursor — and collecting them to then drop all but the ones beginning with
    // `w` is work with no answer in it. A client asks on every keystroke, so the prefix is passed down and applied
    // where the names are still borrowed: see [`ProjectIndex::visible_declarations`].
    //
    // An **empty prefix must not filter**: that is the state the whole feature exists for (`return |`, a blank
    // line), and a filter that treated "nothing written" as "nothing matches" would empty the list exactly when it
    // is most wanted.
    let names = if position.scope.is_empty() {
        match visible_names(index, scopes, root, path, offset, &position.written) {
            Known::Yes(names) => names,
            Known::Unknown(reason) => return Known::Unknown(reason),
            Known::No => return Known::Unknown(UnknownReason::UnparsableName),
        }
    } else {
        match names_in_a_scope(
            index,
            scopes,
            root,
            path,
            &position.scope,
            &position.written,
        ) {
            Known::Yes(names) => names,
            Known::Unknown(reason) => return Known::Unknown(reason),
            Known::No => return Known::Unknown(UnknownReason::UnparsableName),
        }
    };
    if crate::probes::completion() {
        eprintln!(
            "[completion] the listing took {:?} for {} name(s)",
            phase.elapsed(),
            names.len()
        );
    }

    // **The file's own macros**, which the index half cannot see. A `#define` is a preprocessing fact of *this* file, not a
    // declaration in any scope — measured at four cursors in one file: `MA` offered only `main`, `MAX` offered nothing, and
    // `WIDTH` offered 89 names without itself. A macro is offered with `MacroLike`, which the ranking already places after
    // variables and before keywords, and it is a `ThisFile` provenance because that is where a `#define` lives.
    let mut names = names;
    // **The macro tail belongs to an ordinary name position, not to a `::`-qualified one.** A macro
    // is not a member of anything: `std::NOATOM` is legal only because the preprocessor replaced
    // the name before the compiler saw it, and a reader who typed `std::` is asking about `std`.
    // Appending the macros there was not merely noise — it **crowded the list out**: with an empty
    // prefix the ranking falls through to the label, and every macro of the headers the file
    // includes sorts before every lowercase name, so `ITEM_BUDGET` was spent on `NOATOM`,
    // `_WINDOWS_`, `_GLIBCXX_…` and `string`, `format`, `expected` were cut.
    if position.scope.is_empty()
        && let Some(summary) = index.summary(path)
    {
        // **The file's own macros and those of the headers it includes directly.** A `#define` is a preprocessing fact of one
        // file, so the index half of this query cannot see either — and a header's macros are the common case: a project's
        // `config.h` defines the names its sources use. The direct includes are the boundary: a macro two headers away is
        // reachable only through the macro environment, which is the hover's query, not this one's.
        // **The position is carried, not just the name.**
        //
        // The item's identity — the `(file, offset)` a client echoes back to
        // `completionItem/resolve` — is the declaration's **name range**, and a macro has no
        // declaration fact: the item is built from a clone of the file's first declaration (see the
        // loop below). Without the macro's own range in hand the clone kept the template's, so
        // resolve looked up `int main()` and the popup showed `FULL_NAME_FORMAT` with the detail
        // **`int ()`**. Measured twice: once before the clone's fields were cleared, and again
        // after they were, because the range was the field nobody had replaced.
        let mut offered_macros: Vec<(&str, bool, cpp_parser::SourceRange)> = Vec::new();
        for fact in &summary.macros {
            offered_macros.push((fact.name.as_str(), fact.function_like, fact.range));
        }
        for include in &summary.includes {
            let Some(resolved) = &include.resolved else {
                continue;
            };
            let Some(included) = index.summary(resolved) else {
                continue;
            };
            for fact in &included.macros {
                offered_macros.push((fact.name.as_str(), fact.function_like, fact.range));
            }
        }
        offered_macros.sort_by(|left, right| left.0.cmp(right.0));
        offered_macros.dedup_by(|left, right| left.0 == right.0);

        for (name, function_like, range) in offered_macros {
            if !position.written.is_empty() && !name.starts_with(&position.written) {
                continue;
            }
            // A fact cloned from one of the file's own declarations rather than built from nothing: `DeclFact` has no
            // `Default` (its `DeclKind`, `SourceRange` and `FactGuard` do not), and adding one for this would put a
            // meaningless declaration shape in the type.
            //
            // **What the clone keeps is the shape and nothing else**, and that is a correction
            // rather than a tidy-up: everything the template said about *itself* — the return type,
            // the parameter list, the template parameters, the bases — belongs to a different
            // declaration, and this fact speaks for a macro.
            let Some(template) = summary.declarations.first() else {
                continue;
            };
            let mut declaration = template.clone();
            declaration.name = name.to_string();
            declaration.kind = crate::DeclKind::MacroLike;
            // Nothing of the template's *declaration* survives: a macro has no type, no return type, no
            // parameters of its own and no bases, and a `#define` is never local.
            declaration.type_of = None;
            declaration.returns = None;
            declaration.bases.clear();
            declaration.parameters.clear();
            declaration.local = false;
            // **The clone's position is the macro's own.** This is the field that decided what the popup *said*
            // about the macro: the identity a client echoes back to `completionItem/resolve` is a `(file, offset)`
            // pair, and with the template's range it named `int main()` — so resolving the item read `main`'s
            // declaration and the detail line under `FULL_NAME_FORMAT` was **`int ()`**. Clearing the clone's other
            // fields did not help, because the offset was never the macro's.
            //
            // A `#define` is at file scope and in no namespace of its own, whatever the template happened to be.
            declaration.name_range = range;
            declaration.range = range;
            declaration.scope = None;
            declaration.in_namespace = None;
            // **A function-like macro is offered with its parenthesis**, which is the only hint a completion item can carry
            // about how it is used: `MAX(` tells the reader the name takes arguments, and `MAX` alone does not.
            declaration.parameter_list = function_like.then(|| "(".to_string());
            names.push(OfferedName {
                file: path.to_path_buf(),
                fact: declaration,
                depth: 0,
                from: NameProvenance::ThisFile,
            });
        }
    }

    Known::Yes(NameCompletions {
        scope: position.scope,
        names,
        prefix: position.written,
        name_range: position.range,
    })
}

/// **One completion query, with its own measurement reported to the log** — see [`query_trace`].
///
/// The server's log line splits a completion into `prepare`/`catch up`/`modules` and then `view`/`completions`;
/// this is what goes inside `completions`, which is the half no lock can explain. A wrapper rather than a call to
/// asks and the query has several ways to return early.
pub fn name_completions_traced(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    offset: usize,
) -> Known<NameCompletions> {
    name_completions_at(index, scopes, root, path, offset)
}

/// Every name visible from a cursor with no qualifier written: the scope chain, then the index.
///
/// The order is C++'s: the scope the cursor is in, then each enclosing scope outward, and only then the names other
/// files contribute. Each step's own answer is already a list — the tree's bindings, a class's members including
/// its bases, a namespace's declarations across the project — so this walks the chain and hands each depth to the
/// function that knows how to list it.
fn visible_names(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    offset: usize,
    written: &str,
) -> Known<Vec<OfferedName>> {
    let Some(innermost) = scopes.scope_at(offset) else {
        return Known::Unknown(UnknownReason::UnparsableName);
    };

    let chain = scopes.scope_chain(innermost);
    let mut names: Vec<OfferedName> = Vec::new();
    let phase = std::time::Instant::now();

    // **The class a separated definition belongs to.** `int Source::GetLine(int) { … }` in a `.cpp` declares no scope for
    // `Source` here — the class is in a header — so the scope chain below has no class to offer members from, and a
    // completion in that body named none of `Source`. The declaration node still says which class it is, and this reads it
    // from the parser's own nodes: the declarator's qualified name lives in the declaration's specifier sequence. Nothing is
    // synthesized in the scope tree, which is what keeps `resolve`'s rule intact (a qualifier names nothing until something
    // declares it).
    if let Some(class) = the_class_a_definition_belongs_to(root, offset)
        && let Known::Yes(members) = names_of_a_class(index, scopes, root, path, &class)
    {
        names.extend(offered(members, 0));
    }

    // The file the cursor is in, as the store spells paths, so that the declaration-order filter can tell this
    // file's offsets from another file's.
    let in_this_file = normalize(path);
    if crate::probes::completion() {
        eprintln!("[completion]   the class tier: {:?}", phase.elapsed());
    }
    let chain_phase = std::time::Instant::now();

    for (depth, scope) in chain.iter().copied().enumerate() {
        let Some(data) = scopes.scope(scope) else {
            continue;
        };

        // The file scope is the global name space, and it is the one scope whose names other files contribute to
        // as well — every included header is written there. It is listed below, once, rather than here.
        if data.kind == crate::ScopeKind::TranslationUnit {
            continue;
        }

        // A **class** in the chain — the cursor is inside a member function of it — brings its members, bases
        // included: `size` is nameable inside `Widget::g` without a qualifier, and so is anything a base declares.
        if matches!(data.kind, crate::ScopeKind::Class | crate::ScopeKind::Enum)
            && let Some(class) = scopes.qualification_prefix_of(scope)
        {
            let members = match names_of_a_class(index, scopes, root, path, &class) {
                Known::Yes(members) => members,
                Known::Unknown(reason) => return Known::Unknown(reason),
                Known::No => Vec::new(),
            };
            names.extend(offered(members, depth));
            continue;
        }

        // Anything else in the chain is a body, a block or a lambda: its own bindings, which the tree has — and a
        // **namespace**, whose bindings are neither: the kind is what decides, and it is also what decides whether
        // a name beginning with an underscore belongs to the user (a body) or to the global name space (a `_name`
        // at file scope is the implementation's, one inside a function is not).
        let body = matches!(
            data.kind,
            crate::ScopeKind::Block | crate::ScopeKind::Function | crate::ScopeKind::Lambda
        );
        names.extend(offered(
            // **In a body, only what is declared above the cursor is in scope.** A *scope* holds every binding
            // written in its braces, so a list built from the scope contains `int c = a + b;` at a cursor three
            // lines above it — a name that cannot be written there, because the language has not declared it yet.
            // It is the same rule a reader applies without thinking, and the one a user reported: "在我下面声明的
            // 变量不应该补全出来".
            //
            // Only bodies: a class's members and a namespace's names are visible in **declaration order
            // independent** fashion (`class C { void f() { x = 1; } int x; };` is legal), so the filter would be
            // wrong there. Nothing is lost by the narrower rule — a body is exactly where the *textual* order is
            // the language's rule.
            bindings_of(root, path, &data.bindings, None, body)
                .into_iter()
                .filter(|candidate| !body || declared_above(candidate, offset, &in_this_file))
                .collect(),
            depth,
        ));

        // …and for a **namespace**, the names other files write into it. A namespace is reopened by every file
        // that mentions it, so the buffer's list is never the whole answer.
        if let Some(prefix) = scopes.qualification_prefix_of(scope) {
            names.extend(offered(
                declarations_in(&prefix, index, path, written),
                depth,
            ));
        }
    }

    // The global name space: the buffer's own file scope, and every file it includes. One step past the chain, so
    // that the depth stays an ordinary count of how far the lookup walked — the file scope is a scope like any
    // other, it is just not one the chain walked through.
    if crate::probes::completion() {
        eprintln!("[completion]   the chain: {:?}", chain_phase.elapsed());
    }
    let global_phase = std::time::Instant::now();
    names.extend(global_offers(
        index,
        scopes,
        root,
        path,
        chain.len(),
        written,
    ));
    if crate::probes::completion() {
        eprintln!(
            "[completion]   the global tier: {:?}",
            global_phase.elapsed()
        );
    }

    let sort_phase = std::time::Instant::now();
    sort_and_hide(&mut names);
    if crate::probes::completion() {
        eprintln!("[completion]   the sort: {:?}", sort_phase.elapsed());
    }
    Known::Yes(names)
}

/// The names at **file scope**, ready to offer: the buffer's own and every included file's, deduplicated.
///
/// A helper rather than two lines at each call site because the deduplication is the part that is easy to forget
/// and impossible to notice: the buffer's file-scope names and the index's are the *same* declarations whenever
/// the file being edited has been saved, so a list that skipped this step offers every global name twice.
fn global_offers(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    depth: usize,
    written: &str,
) -> Vec<OfferedName> {
    let mut names = offered(global_names(index, scopes, root, path, written), depth);
    sort_and_hide(&mut names);
    names
}

/// **Does this spelling name a type?** — the question that decides whether a qualifier is completed as a class
/// (its members, `members_of`) or as a namespace (the guard-evaluating visibility walk, which the index's own note
/// measures at **1.2 s**).
///
/// # Why "every candidate is a `Type`" was wrong
///
/// It is the rule that let `std::vector<int>::` work (a class template has a forward declaration in `<iosfwd>` and a
/// definition in `<vector>`, so two `Type`s), and it is false for **every class that writes its own constructor**:
/// `class LSPHandle { public: LSPHandle(LanguageServer *); … };` puts a `Function` named `LSPHandle` (scope
/// `LSPHandle`) beside the class, so "all candidates are types" says no — and the completion after `LSPHandle::` fell
/// to the namespace route. Measured on `E:\EmmyLuaCodeStyle`, `CodeFormatServer/src/LSP/LSPHandle.cpp`:
/// **`name_completions` 1.14 s** against `members_of`'s **16 µs** for the same class.
///
/// # The rule this uses instead
///
/// A spelling names a type when **some** candidate is a `Type` and **every other candidate is a member of it** — its
/// `scope` is the spelling itself, which is exactly where a constructor, a destructor and a same-named nested name
/// are filed. A *namespace* of that name has no such candidate (its facts' scope is the namespace's parent), so it
/// keeps the namespace route; and the alias case (`std::string`) is untouched, because `definition` answers it
/// singularly today.
fn a_spelling_names_a_type(index: &ProjectIndex, spelling: &str, path: &Path) -> bool {
    let Some(found) = index.definitions(spelling, path).value() else {
        return false;
    };
    let mut any_type = false;
    for declaration in &found.found {
        if declaration.fact.kind == crate::DeclKind::Type {
            any_type = true;
            continue;
        }
        // Everything else has to be *inside* the type: a constructor, a destructor, or a nested name of the same
        // spelling. A namespace's own facts fail this, which is what keeps `ns::` on the namespace route.
        if declaration.fact.scope.as_deref() != Some(spelling) {
            return false;
        }
    }
    any_type
}

/// The names written directly in one `::`-qualified scope.
fn names_in_a_scope(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    scope: &str,
    written: &str,
) -> Known<Vec<OfferedName>> {
    names_in_a_scope_at(index, scopes, root, path, scope, written, 0)
}

/// The same query, with how many aliases have been followed — the guard is what makes a cycle in
/// `namespace a = b; namespace b = a;` terminate rather than recurse for ever.
#[allow(clippy::too_many_arguments)]
fn names_in_a_scope_at(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    scope: &str,
    written: &str,
    depth: usize,
) -> Known<Vec<OfferedName>> {
    // The global name space has no spelling of its own: `::` is what the file writes, and `None` is what a
    // declaration at file scope records.
    if scope == "::" {
        return Known::Yes(global_offers(index, scopes, root, path, 0, written));
    }

    // A leading `::` on a longer path — `::ns::Widget` — asks for the *global* one, and the spelling to look up is
    // the rest: a fact records `ns::Widget` and never `::ns::Widget`, for the same reason.
    let spelling = scope.trim_start_matches("::");

    let in_the_tree = scopes.scope_with_qualified_name(spelling);
    let kind = in_the_tree
        .and_then(|id| scopes.scope(id))
        .map(|scope| scope.kind);

    let mut names: Vec<OfferedName> = Vec::new();

    match kind {
        // A class is defined once, so its members come from one place — and the walk over its bases is
        // `members_of`'s job rather than this query's.
        Some(crate::ScopeKind::Class | crate::ScopeKind::Enum) => {
            let members = match names_of_a_class(index, scopes, root, path, spelling) {
                Known::Yes(members) => members,
                Known::Unknown(reason) => return Known::Unknown(reason),
                Known::No => Vec::new(),
            };
            names.extend(offered(members, 0));
        }
        // A namespace can be reopened, so the buffer's names and the project's are both part of the answer.
        Some(_) => {
            if let Some(data) = in_the_tree.and_then(|id| scopes.scope(id)) {
                // `false`: a namespace is not a body, so a `_name` in it is not a local — the reservation that
                // applies to a name beginning with an underscore is the *global* name space's, and the spelling
                // here is the namespace's own.
                names.extend(offered(
                    bindings_of(root, path, &data.bindings, Some(spelling), false),
                    0,
                ));
            }
            names.extend(offered(declarations_in(spelling, index, path, written), 0));

            // **A namespace alias is a scope with no members of its own**, and its target is where the names are.
            // `namespace views = ranges::views;` gives `std::views` an empty namespace scope — the walker needs one
            // for the name to resolve — and every adapter a reader types after `std::views::` is declared in
            // `std::ranges::views`. Measured on the corpus's `ranges.cpp`: completion after `std::views::` answered
            // **0** names, while `filter`, `transform`, `reverse`, `drop` and `take` are all there.
            //
            // Only on the empty answer, so an ordinary `std::` never pays for the tree walk this needs.
            if names.is_empty()
                && depth < 4
                && let Some(id) = in_the_tree
                && let Some(target) = the_target_of_a_namespace_alias(root, scopes, id)
            {
                let target = the_target_in_its_own_scope(scopes, spelling, &target);
                if target != spelling {
                    return names_in_a_scope_at(index, scopes, root, path, &target, written, 0);
                }
            }
        }
        // Not in the buffer at all: the project's answer, or nothing.
        None => {
            // **A qualifier that names a *type* rather than a scope in this file.** The scope tree is the buffer's
            // own, so `std::string` — an alias of a class template, declared in `<xstring>` — is not a scope it can
            // name, and `Some(Class)` above never sees it. A class is defined once, so its members are the answer,
            // and `members_of` is the query that resolves an alias, a template spelling and the bases: measured on
            // a file that includes `<string>`, completion after `std::string::` offered **0** names before this and
            // every member of `basic_string` after it.
            //
            // **Asked only of a name the index says is a type**, and that test is the whole reason this is not
            // simply tried first: `members_of` answers for a spelling that no class declares — it lists the
            // declarations whose *scope* is that name — so a namespace qualifier sent down this path (`ns::`,
            // `std::`) silently took the member route, which has no budget and no dedup by hiding. A namespace is
            // [`DeclKind::Namespace`] and is answered below, where the collection budget applies.
            // **Is the spelling a type?** — asked three ways, because one way is not enough for the standard library:
            //
            // ```text
            //   `definition` says Yes(Type)          an ordinary class, declared once and visible
            //   `definition` says Unknown(Ambiguous)  **the ordinary case for a class template**: `std::vector` is
            //                                        forward-declared in `<iosfwd>` and defined in `<vector>`, so the
            //                                        singular query declines. Every candidate being a Type is the
            //                                        answer, and it is what `std::vector<int>::` needed — it offered
            //                                        nothing while the definition query was the only test.
            //   an alias in this index                 `std::string` is `using string = basic_string<char, …>;`, so
            //                                        the name is an *alias* fact whose `scope` is `std` and whose
            //                                        target is the class that has the members. Measured: without this
            //                                        arm `std::string::` offered **0** items.
            // ```
            let names_a_type = a_spelling_names_a_type(index, spelling, path);
            if crate::probes::members() {
                let bare = spelling.rsplit("::").next().unwrap_or(spelling);
                let facts: Vec<String> = index
                    .every_fact_named(bare)
                    .into_iter()
                    .map(|(file, fact)| {
                        format!(
                            "{:?} scope {:?} kind {:?} @ {}",
                            fact.name,
                            fact.scope,
                            fact.kind,
                            file.file_name().unwrap_or_default().to_string_lossy()
                        )
                    })
                    .collect();
                eprintln!(
                    "    names_in_a_scope({spelling}): in the tree {}, names_a_type {names_a_type}, \
                     definition {:?} | facts named {bare:?}: {facts:?}",
                    in_the_tree.is_some(),
                    match index.definition(spelling, path) {
                        Known::Yes(found) =>
                            format!("Yes({} {:?})", found.fact.qualified_name(), found.fact.kind),
                        Known::Unknown(reason) => format!("Unknown({reason:?})"),
                        Known::No => "No".to_string(),
                    }
                );
                if spelling == "std::string" {
                    let xstring = index.summaries_named_like("xstring");
                    let string = index.summaries_named_like("string");
                    eprintln!(
                        "      index: {} summaries, {} distinct names | by_name: string {} basic_string {} \
                         vector {} | by_scope: std::basic_string {} | files: xstring {} string-ish {}",
                        index.len(),
                        index.distinct_names(),
                        index.name_postings("string"),
                        index.name_postings("basic_string"),
                        index.name_postings("vector"),
                        index.scope_postings("std::basic_string"),
                        xstring.len(),
                        string.len(),
                    );
                    for path in string.iter().take(6) {
                        eprintln!("        {}", path.display());
                    }

                    // **What the summary of `<xstring>` actually says**, which is the question that separates
                    // "the class was never recorded" from "it was recorded under a name nothing asks for".
                    // `basic_string` is written at `xstring:2344` as
                    // `template <class _Elem, class _Traits, class _Alloc> class basic_string`, so a reading that
                    // dropped it lost it in the *fact builder* rather than in any lookup.
                    for (path, summary) in index.all_summaries() {
                        let name = path.to_string_lossy();
                        if !name.ends_with("xstring") && !name.ends_with("include/string") {
                            continue;
                        }
                        let mut named: Vec<String> = summary
                            .declarations
                            .iter()
                            .filter(|fact| fact.name.contains("basic"))
                            .map(|fact| {
                                format!(
                                    "{:?} kind {:?} scope {:?} local {}",
                                    fact.name, fact.kind, fact.scope, fact.local
                                )
                            })
                            .collect();
                        named.sort();
                        named.dedup();
                        eprintln!(
                            "      {} has {} declaration(s); the {} named *basic*: {:?}",
                            name,
                            summary.declarations.len(),
                            named.len(),
                            named.iter().take(14).collect::<Vec<_>>()
                        );
                    }
                }
            }

            if names_a_type {
                // **An alias is followed to the class that has the members.** `std::string` is
                // `using string = basic_string<char, char_traits<char>, allocator<char>>;` — a fact whose `scope`
                // is `std`, not `std::string` — so `members_of("std::string")` looks for a class by that name and
                // finds nothing. Measured: `std::string::` offered **0** items, and it is the most-used class in
                // the library. `resolve_aliases` is the same resolution `members_of` does for a member's own type,
                // so the two cannot disagree about what the spelling names.
                let named = resolve_aliases(index, scopes, root, path, spelling);
                let named = named.as_ref();
                if crate::probes::members() {
                    eprintln!("    names_a_type({spelling}) -> alias resolved to {named:?}");
                }
                match names_of_a_class(index, scopes, root, path, named) {
                    Known::Yes(members) => names.extend(offered(members, 0)),
                    Known::Unknown(reason) => return Known::Unknown(reason),
                    Known::No => {}
                }
            } else {
                let found = declarations_in(spelling, index, path, written);
                if found.is_empty() {
                    // **A namespace alias, declared in a header the buffer does not hold.** The scope tree is the
                    // buffer's own, so `std::views` — `namespace views = ranges::views;` in `<ranges>` — is not a
                    // scope it can name, and the index records the target on the alias's own fact. Measured on the
                    // corpus's `ranges.cpp`: completion after `std::views::` answered **0** names, while every
                    // adapter is declared in `std::ranges::views`.
                    //
                    // The target is looked up where the alias sits (`std::ranges::views` for `ranges::views` in
                    // `std`) and then as written, because which of the two is right depends on the alias's scope.
                    if depth < 4
                        && let Known::Yes(alias) = index.definition(spelling, path)
                        && alias.fact.kind == crate::DeclKind::Namespace
                        && let Some(target) = alias.fact.type_of.as_deref()
                    {
                        let mut candidates: Vec<String> = Vec::new();
                        if let Some(scope) = alias.fact.scope.as_deref() {
                            candidates.push(format!("{scope}::{target}"));
                        }
                        candidates.push(target.trim_start_matches("::").to_string());
                        for candidate in candidates {
                            if candidate != spelling
                                && !declarations_in(&candidate, index, path, written).is_empty()
                            {
                                return names_in_a_scope_at(
                                    index, scopes, root, path, &candidate, written, 0,
                                );
                            }
                        }
                    }
                    // Empty is either "declared and empty" or "no such scope", and the difference is the *name* —
                    // the same distinction `direct_members` makes, for the same reason.
                    return match index.definition(spelling, path) {
                        Known::Yes(found) if found.fact.qualified_name() == spelling => {
                            Known::Yes(Vec::new())
                        }
                        Known::Unknown(reason) => Known::Unknown(reason),
                        _ => Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(spelling))),
                    };
                }
                names.extend(offered(found, 0));
            }
        }
    }

    sort_and_hide(&mut names);
    Known::Yes(names)
}

/// **What a namespace alias names**, or `None` when this scope is a namespace with a body of its own.
///
/// `namespace views = ranges::views;` parses as a `NamespaceDecl` with **no compound statement** and a `NameExpr`
/// after the `=`; the scope walker creates a scope for it so that the name resolves, and that scope is empty by
/// construction. The tree is asked rather than the text because the two are already in hand and the shape says it
/// without spelling rules: a namespace declaration with a body is an ordinary one, with a target and no body is an
/// alias.
fn the_target_of_a_namespace_alias(
    root: &cpp_parser::CppSyntaxNode,
    scopes: &crate::ScopeTree,
    id: crate::sema::symbol::ScopeId,
) -> Option<String> {
    let scope = scopes.scope(id)?;
    if scope.kind != crate::ScopeKind::Namespace {
        return None;
    }
    let range = scope.range?;
    let node = root.descendants().find(|node| {
        cpp_parser::CppSyntaxKind::from(node.kind()) == cpp_parser::CppSyntaxKind::NamespaceDecl
            && cpp_parser::source_range(node.text_range()) == range
    })?;
    if node.children().any(|child| {
        cpp_parser::CppSyntaxKind::from(child.kind()) == cpp_parser::CppSyntaxKind::CompoundStat
    }) {
        return None;
    }
    node.children()
        .find(|child| {
            cpp_parser::CppSyntaxKind::from(child.kind()) == cpp_parser::CppSyntaxKind::NameExpr
        })
        .map(|child| child.text().to_string())
}

/// **Where an alias's target is looked up from.** The language looks a target up in the scope the alias is declared
/// in, so `namespace views = ranges::views;` inside `std` names `std::ranges::views`; a target that already resolves
/// on its own — `namespace fs = std::filesystem;` at file scope — is used as written.
fn the_target_in_its_own_scope(scopes: &crate::ScopeTree, alias: &str, target: &str) -> String {
    let target = target.trim().trim_start_matches("::");
    if let Some(at) = alias.rfind("::") {
        let nearby = format!("{}::{target}", &alias[..at]);
        if scopes.scope_with_qualified_name(&nearby).is_some() {
            return nearby;
        }
    }
    if scopes.scope_with_qualified_name(target).is_some() {
        return target.to_string();
    }
    target.to_string()
}

/// **Is this declaration above the cursor**, so that the language has reached it?
///
/// The rule a reader applies without thinking, and the one a user reported as missing ("在我下面声明的变量不应该补全
/// 出来"): `int sum = a + b;` three lines *below* the cursor is not a name that can be written at the cursor, and a
/// list built from a scope's bindings contains it anyway — a scope holds every binding written inside its braces.
///
/// # Where it applies, and where it must not
///
/// Only in a **body** (a function, a block, a lambda), because that is the one place where textual order *is* the
/// language's rule. A class's members and a namespace's names are reachable regardless of where they are written —
/// `class C { void f() { x = 1; } int x; };` is perfectly legal — so filtering those by position would remove names
/// a reader can legitimately write.
///
/// # The one thing it will not judge
///
/// A binding from **another file**: its range is an offset into that file, so comparing it with this file's cursor
/// compares two different rulers. Those are kept — the conservative direction, and the same one the rest of this
/// module takes: a name that is in scope and not offered is a missing answer, while a name that is not in scope yet
/// and *is* offered is one the reader sees as a mistake.
///
/// In practice every binding here is the buffer's own — `build_scopes` walks one file's tree, and a name reached
/// through an include is a [`NameProvenance::DirectInclude`] fact from the index rather than a binding — so this is
/// the guard that keeps the rule from being wrong if that ever changes.
fn declared_above(candidate: &Candidate, offset: usize, in_this_file: &str) -> bool {
    if candidate.file != Path::new(in_this_file) {
        return true;
    }

    let at = candidate.fact.name_range.start_offset;

    // A zero-length range at the start of the file is what a recovery produces, and it is not a position.
    at == 0 || at < offset
}

/// One name on its way to being offered: where it was declared, how far inside one answer it was, and how near the
/// cursor that is.
///
/// Named rather than a tuple because there are four of them now and two of the four are `usize`; a call site that
/// had to remember which was which is how a ranking ends up ordered by the wrong number.
struct Candidate {
    file: PathBuf,
    fact: DeclFact,
    /// How far *inside* one answer the name was found — a base class's member is one step further than the class's
    /// own — which is added to the depth of the scope the answer came from.
    steps: usize,
    from: NameProvenance,
}

impl Candidate {
    fn new(file: PathBuf, fact: DeclFact, from: NameProvenance) -> Candidate {
        Candidate {
            file,
            fact,
            steps: 0,
            from,
        }
    }
}

/// How many declarations from **every visible file at once** one name query will collect.
///
/// A backstop on work rather than a statement about the answer, and the number is derived from what the answer can
/// be: `crate::completion` shows at most two hundred items, and every one of them is scored by *how near the cursor
/// its declaration is*. A query that has already collected this many names — all of them from files the cursor
/// reaches through includes, which is the tier that ranks last — cannot have its answer changed by the next one,
/// and on a file that includes `<string>` and the C++ standard library there are **26 728** declarations in the
/// files one cursor can see.
///
/// The file's **own** declarations are not capped: they come from the scope tree rather than from here, they are
/// the tier that ranks first, and there are as many of them as the reader wrote.
///
/// This is the budget for the **global** name space (`::`, and a cursor at file scope). For one named scope see
/// [`MAX_COLLECTED_IN_A_SCOPE`], which is a different question with a different answer.
const MAX_COLLECTED_NAMES: usize = 400;

/// How many declarations one **named scope** may contribute to a list — `std::`, `ns::`, `Widget::`.
///
/// # Why this is not [`MAX_COLLECTED_NAMES`]
///
/// Because that budget is spent in **file order**, and a scope's names are spread over the files that declare them.
/// Measured on a file that includes `<cstdio>`, `<iostream>`, `<optional>`, `<string>` and `<format>`: completion
/// after `std::` offered **175** names, and the ones it offered were whatever the first 400 declarations of the
/// visibility walk happened to be — `cin`, `cout`, `getline`, `make_optional`, `nullopt` — while `string` (declared
/// in `<xstring>`, reached through `<string>`) and everything in `<format>` were past the cut. The list a reader
/// saw therefore depended on the order of their own `#include` lines, which is not a property of the program.
///
/// The honest number is the size of the scope, because a namespace holds what it holds: `std` is **2 008**
/// declarations on this project, and every namespace in the C++ standard library is inside that. The display budget
/// ([`crate::completion`]'s `ITEM_BUDGET`, two hundred items) is what keeps the *message* small, and it reports
/// itself as `truncated` so the client re-asks as the reader types — where the prefix filter, which is applied
/// before anything is cloned, makes the list exact.
///
/// The cost of the larger budget is one `DeclFact` clone per surviving name, and only for a cursor whose prefix is
/// short enough to keep them: the walk itself is one pass over the closure.
const MAX_COLLECTED_IN_A_SCOPE: usize = 4096;

/// How many declarations one name may have before a workspace search stops ordering them — see
/// `ProjectIndex::open_group`.
const POPULAR_NAME: usize = 4096;

/// The bindings one of the file's own scopes holds, as names to offer. — `ns` for `namespace ns { … }`, a class's name for
/// its body — and `None` for a scope that has none: a function body, a block, a lambda. The distinction is the one
/// [`DeclFact::scope`] documents, and it is passed rather than derived because the caller is the one that knows
/// *why* it is listing these bindings.
///
/// `local` is the other half of that and it is **not** derivable from `scope`, which is why it is a parameter:
/// `None` is passed by two callers with different meanings — the **file scope** (whose names are the global name
/// space's) and a **body** (whose names are the user's locals) — and the difference decides what may be offered.
/// A `_name` at file scope is reserved to the implementation; the same spelling inside a function is the user's own
/// and is offered. Filling this in wrong is not visible anywhere else: the fact's `local` field is only read by
/// [`is_reserved_to_the_implementation`] on this path, and a local marked global silently disappears from the list.
fn bindings_of(
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    bindings: &[crate::Binding],
    scope: Option<&str>,
    local: bool,
) -> Vec<Candidate> {
    let spelling = scope.unwrap_or_default();

    bindings
        .iter()
        .map(|binding| {
            let mut fact = fact_from_binding(root, spelling, binding);
            fact.local = local;
            Candidate::new(path.to_path_buf(), fact, NameProvenance::Scope)
        })
        .collect()
}

/// The names written at **file scope**: this buffer's, and every included file's.
fn global_names(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    written: &str,
) -> Vec<Candidate> {
    let mut names: Vec<Candidate> = scopes
        .root()
        .and_then(|root_scope| scopes.scope(root_scope))
        // `false`: this **is** the global name space — the one scope where a name beginning with an underscore is
        // reserved to the implementation, which is why `Session::name_completions` does not offer `_Arg` or `_cprintf`.
        .map(|data| bindings_of(root, path, &data.bindings, None, false))
        .unwrap_or_default();

    // **The buffer's own file-scope names are the file's**, even though they live in the global name space: the
    // distinction the ranking needs is "did the reader write this here", not "which scope is it in".
    for name in &mut names {
        name.from = NameProvenance::ThisFile;
    }

    names.extend(declarations_in_scope(index, path, None, written));
    names
}

/// The facts the index holds for a scope spelling, or for the global name space when it is `None`.
///
/// The global case is the *absence* of a spelling rather than an empty one, which is why it cannot go through
/// [`ProjectIndex::declarations_in`]: that one compares a spelling, and a declaration at file scope records
/// `None`. It is the same distinction `matches` makes for a leading `::`. A **local** is left out here for the
/// reason [`DeclFact::local`] gives — a local also records `None`, and offering another file's would be the wrong
/// answer rather than a missing one.
fn declarations_in_scope(
    index: &ProjectIndex,
    visible_from: &Path,
    scope: Option<&str>,
    written: &str,
) -> Vec<Candidate> {
    // **The prefix is applied here, where the names are still borrowed.** Everything below this point is work per
    // declaration — a `DeclFact` clone, a provenance lookup, a `Vec` push — and on a file that includes `<string>`
    // there are over a thousand of them at one cursor position. Collecting them to drop all but those beginning
    // with `w` is the difference between a keystroke and a stutter, and it is a filter rather than a query: the
    // names it drops could not have been offered anyway. See [`crate::sema::resolve::name_position_at`].
    let accepts = |fact: &DeclFact| name_starts_with(fact, written);

    let found = match scope {
        Some(spelling) => index.declarations_in_where(spelling, visible_from, accepts),
        // **The full walk, and it has to be.** A cheap version of this arm (the `#include` graph plus a prefix over the
        // raw summaries) was measured and reverted: it cost 1.18 s either way — the time is in `bindings_of`'s type
        // inference, not here — and it changed what completion offers, because the walk's answer includes the **cooked**
        // reading's declarations (a name a macro writes) and excludes the branches a condition does not take. Two
        // handshake tests say so: `a_name_only_the_cooked_reading_declares_is_offered_over_the_wire` and
        // `a_c_reader_gets_completion_and_signature_help_for_what_the_file_defines`.
        None => index.visible_declarations_where(visible_from, |fact| {
            accepts(fact) && fact.scope.is_none() && !fact.local
        }),
    };

    // **Each of the two queries applied its own budget**, and this function must not apply a third: the global
    // name space is unbounded in size and the tier it produces ranks last ([`MAX_COLLECTED_NAMES`]), while one named
    // scope holds what it holds ([`MAX_COLLECTED_IN_A_SCOPE`]). A second cut here is what made `std::` offer 175 of
    // its 2 008 names.
    found
        .into_iter()
        .map(|declaration| {
            Candidate::new(
                declaration.file.clone(),
                declaration.fact.clone(),
                provenance_of(
                    index,
                    visible_from,
                    declaration.visibility,
                    &declaration.file,
                ),
            )
        })
        .collect()
}

/// Does this declaration's name begin with what is being typed?
///
/// Case-insensitive, and **`true` for an empty prefix** — the state the whole feature is for. The rule is a
/// *filter* and not a ranking: the offer list drops a name this rejects, because a name the reader has not started
/// typing cannot be what they meant and the client would filter it out anyway. What it must not do is decide
/// between two names that both match; that is `crate::completion`'s job.
fn name_starts_with(fact: &DeclFact, written: &str) -> bool {
    if written.is_empty() {
        return true;
    }

    let name = fact.name.as_str();
    name.len() >= written.len()
        && name
            .chars()
            .zip(written.chars())
            .all(|(have, wanted)| have.eq_ignore_ascii_case(&wanted))
}

/// [`declarations_in_scope`] for a named scope, spelled the way this module spells lookups.
fn declarations_in(
    spelling: &str,
    index: &ProjectIndex,
    visible_from: &Path,
    written: &str,
) -> Vec<Candidate> {
    declarations_in_scope(index, visible_from, Some(spelling), written)
}

/// **How near the cursor a file is**, for the ranking: the buffer, a project header beside it, a header the buffer
/// includes, or one only those headers include.
///
/// The three cross-file answers are exactly the three the visibility walk produced — the file was reached by
/// crossing includes — so this only has to tell *which* of them a fact is, and the question it asks the graph is
/// the cheap one: does the file that declares this name appear among the cursor file's **own** `#include`s.
///
/// A file that is reachable only through a guarded `#include` ([`IncludeVisibility::Conditional`]) is ranked as an
/// indirect one, which is the honest place for it: it is in the list — the reader may be writing for exactly that
/// configuration — but it is not one of the headers this file certainly includes.
fn provenance_of(
    index: &ProjectIndex,
    visible_from: &Path,
    visibility: IncludeVisibility,
    declaring: &Path,
) -> NameProvenance {
    if visibility == IncludeVisibility::Conditional {
        return NameProvenance::IndirectInclude;
    }

    let declaring = normalize(declaring);
    let mut direct = false;

    if let Some(summary) = index.summary(visible_from) {
        for include in &summary.includes {
            let Some(resolved) = &include.resolved else {
                continue;
            };
            if normalize(resolved) == declaring {
                direct = true;
                break;
            }
        }
    }

    if direct {
        return NameProvenance::DirectInclude;
    }

    NameProvenance::IndirectInclude
}

/// The members of a class, bases included, as names to offer.
fn names_of_a_class(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    class: &str,
) -> Known<Vec<Candidate>> {
    match members_of(index, scopes, root, path, class) {
        Known::Yes(members) => Known::Yes(
            members
                .members
                .into_iter()
                .map(|member| {
                    // A class's own members are reachable from a cursor inside the class without a qualifier, and
                    // they are ranked as what they are — the nearest thing there is, beside a local. Which is why
                    // the provenance is `Scope` and the *depth* carries the inheritance: see `Score::LOCAL`.
                    let mut candidate =
                        Candidate::new(member.file, member.fact, NameProvenance::Scope);
                    candidate.steps = member.depth;
                    candidate
                })
                .collect(),
        ),
        Known::Unknown(reason) => Known::Unknown(reason),
        Known::No => Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(class))),
    }
}

/// Wrap candidates as offers, adding the depth of the scope they were found in and dropping the declarations that
/// have no name to type — and the names the implementation owns.
///
/// [`Candidate::steps`] is how far *inside* one answer the name was — a base class's members are one step further
/// than the class's own — and the two are added because they mean the same thing to a consumer: how far the lookup
/// had to walk before it found this name, which is the order C++ walks in too.
fn offered(found: Vec<Candidate>, depth: usize) -> Vec<OfferedName> {
    found
        .into_iter()
        .filter(|candidate| !candidate.fact.name.is_empty())
        .filter(|candidate| !is_reserved_to_the_implementation(&candidate.fact))
        .map(|candidate| OfferedName {
            file: candidate.file,
            fact: candidate.fact,
            depth: depth.saturating_add(candidate.steps),
            from: candidate.from,
        })
        .collect()
}

/// Is this name **reserved to the implementation**, and therefore not something a completion should offer?
///
/// The standard's own three rules, and nothing else:
///
/// ```text
/// __name    reserved everywhere                `__crt_…`, `__imp_…`
/// _Name     reserved everywhere                `_ALLOC_MASK`, `_Alty`, `FILE`? no — `FILE` is not reserved
/// _name     reserved **in the global namespace**   `_Arg`, `_Address`, `_cprintf`
/// ```
///
/// The third is why this is asked of a **fact** rather than of a spelling: `_Address` at file scope is the
/// implementation's, while `Widget::_count` is the user's own member and a local `_i` is theirs too — and a
/// `DeclFact` says which it is (`local`, and `scope: None` for the global name space).
///
/// # What it is worth, measured
///
/// A completion is a suggestion list, and these are names the user may not use. On one real file, of the **1903**
/// names visible at a blank line inside a function body, **601** were reserved this way (`_Arg`, `_Arg1`,
/// `__crt_…`) — and the same rule takes `_ALLOC_MASK`, `_Alty` and `_Apply_annotation` off `basic_string`'s
/// member list, which is where a user completing `line.` meets them first.
///
/// # What it is *not*
///
/// Not a rule about what the analysis will answer: hover, a jump and a rename still find a reserved name — a reader
/// who points at `_Arg` in a header wants to know what it is — this only decides what to **offer**.
pub(crate) fn is_reserved_to_the_implementation(fact: &DeclFact) -> bool {
    let name = fact.name.as_str();
    let mut characters = name.chars();

    if characters.next() != Some('_') {
        return false;
    }

    match characters.next() {
        // `__name`, and a lone `_`.
        Some('_') | None => true,
        // `_Name`.
        Some(second) if second.is_uppercase() => true,
        // `_name`: the implementation's only in the global name space — and not for a local, whose scope is `None`
        // for the reason `DeclFact::scope` documents (a body contributes no segment to a qualified name).
        Some(_) => fact.scope.is_none() && !fact.local,
    }
}

/// Put the offers in the order a completion shows them: nearest scope first, then by name; and drop every name an
/// inner scope has already offered.
///
/// The hiding is what makes a *list* an answer rather than a pile: a local `count` and a header's `count` are two
/// declarations of one name, and C++ reaches only the first. Both would be wrong to show — one of them is not what
/// the user gets if they pick it — and the inner one is the one they get.
fn sort_and_hide(names: &mut Vec<OfferedName>) {
    // Stable, so that two declarations of one name at one depth keep the order they were found in: that is an
    // overload, and reordering it would be inventing a preference.
    names.sort_by(|one, other| {
        one.depth
            .cmp(&other.depth)
            .then_with(|| one.fact.name.cmp(&other.fact.name))
    });

    let mut seen: HashSet<String> = HashSet::new();
    names.retain(|name| seen.insert(name.fact.name.clone()));
}

/// How deep the type question may ask itself before it gives up.
///
/// See the guard in [`type_of_expression`]: this is a bound on an ill-formed file's recursion, not a statement
/// about how complex a type may be.
/// How many members deep a member's type is followed before the walk gives up.
///
/// A member declared with another member's name is the ordinary way a class writes its own types —
/// `typedef _Ty& reference; reference front;`, `typedef size_t size_type; size_type size();` — so one step is not
/// enough. The step is a **member lookup** rather than a substitution, which is why it needs a bound of its own:
/// a lookup can be answered by a declaration that names the member it was asked from, and `a b; b a;` is writable
/// text even though it is not a valid program. Eight is far past any real chain — the standard library's deepest
/// are two or three.
const MAX_NESTED_TYPE_DEPTH: usize = 8;

const MAX_TYPE_DEPTH: usize = 8;

/// **How many inference answers the index keeps** — see `ProjectIndex::type_answers`.
const MAX_TYPE_ANSWERS: usize = 8192;

/// **What an inference answer is a function of**, as one number: the file, the expression's range, its kind and its text.
///
/// The range is part of it on purpose: the same spelling at two places is two questions (`Widget` inside a class and
/// outside one), and a `T` in a template is a parameter where a `T` at file scope is a class.
fn the_type_key(path: &Path, expression: &cpp_parser::CppSyntaxNode) -> u64 {
    let range = expression.text_range();
    let mut bytes: Vec<u8> = Vec::with_capacity(96);
    bytes.extend_from_slice(normalize_path(path, cfg!(windows)).as_bytes());
    bytes.push(0x1f);
    bytes.extend_from_slice(&u64::from(u32::from(range.start())).to_le_bytes());
    bytes.extend_from_slice(&u64::from(u32::from(range.end())).to_le_bytes());
    let kind = cpp_parser::CppSyntaxKind::from(expression.kind());
    bytes.extend_from_slice(&u64::from(kind as u16).to_le_bytes());
    bytes.push(0x1e);
    bytes.extend_from_slice(expression.text().to_string().as_bytes());
    crate::cache::fnv1a64(&bytes)
}
/// **What a `new` expression allocates** — the spelling of its type, which is the whole of the answer.
///
/// The type is the `TypeId` child the grammar built: `new` is the one expression whose operand is a **type**, and
/// `parse_new_type_and_initializer` reads it with the type grammar rather than the expression one. So this is a
/// lookup in a tree that is already there, not an inference.
///
/// A placement list comes first and parses as an `ArgumentList` rather than a `TypeId`, so taking the first
/// `TypeId` child skips it without a rule about parentheses. `None` for a `new` with no type, which is a parse
/// error rather than an allocation.
fn new_expression_allocates(expression: &cpp_parser::CppSyntaxNode) -> Option<String> {
    let allocated = expression.children().find(|child| {
        cpp_parser::CppSyntaxKind::from(child.kind()) == cpp_parser::CppSyntaxKind::TypeId
    })?;

    let written = allocated.text().to_string();
    let written = written.trim();

    // `new int[10]` parses its type as `int[10]`, and the suffix belongs to the declarator rather than to the
    // allocated type: the expression type is `int*`, not `int[10]*`.
    let name = match written.find('[') {
        Some(at) => written[..at].trim(),
        None => written,
    };

    (!name.is_empty()).then(|| name.to_string())
}

/// The type of an expression, as far as this layer can tell, and the file that declared it.
///
/// The core of the `infer` layer, and it is **recursive** because that is what an expression is: `a.b.size` is a
/// member access whose object is a member access, and the type of the inner one is the type recorded on the
/// declaration the outer one starts from.
///
/// # The three shapes it can type, and the boundary
///
/// ```text
/// a name          `widget`      — its declaration's `type_of`, from this file or through the index
/// `this`          `this->size`  — the class whose scope encloses the expression, which needs no inference
/// a member access `a.b`         — recursively: find `b` in the type of `a`, then read `b`'s own `type_of`
/// ```
///
/// Everything else is [`UnknownReason::UnknownType`] carrying the expression's spelling: a call (`f().size`), a
/// dereference (`(*p).size`), a subscript, an arithmetic expression. Each of those needs a type *computed* rather
/// than read off a declaration, which is a different and much larger problem — and answering `Unknown` is what
/// keeps this layer from being wrong in a way a consumer cannot see.
///
/// # One entry point, one memo — and the recursion shares it
///
/// The engine used to be **stateless** below its caller: this function called itself for every sub-expression, so a
/// question already answered was answered again — a `2 800`-line file asked 382 top-level questions and spent
/// **5 923 ms**, because one `e.U.Start.Kind` re-deduced the `auto` declaration behind `e` eleven times. The memo is
/// now a parameter ([`type_of_expression_memoed`]), so every recursive question hits it; a caller with many questions
/// to ask — [`crate::sema::model::SemanticModel`] — passes one map for the whole request.
pub(crate) fn type_of_expression(
    index: &ProjectIndex,
    declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    expression: &cpp_parser::CppSyntaxNode,
    depth: usize,
) -> Known<(Type, PathBuf)> {
    // **One memo per entry point**, which is the smallest scope that already removes the duplication: the questions
    // asked *inside* one expression are the ones that repeat. A caller that asks about many expressions shares a
    // larger memo by calling [`type_of_expression_memoed`] itself — see `SemanticModel`.
    let memo = TypeMemo::default();
    type_of_expression_memoed(
        &memo, index, declaring, scopes, root, path, expression, depth,
    )
}

/// **What an expression's type was, and what a member lookup answered** — the memo one request shares.
///
/// The engine was recursive over the tree and **stateless**, so every sub-expression it had already answered was
/// answered again: on a 2 800-line file, one `e.U.Start.Kind` re-deduced the `auto` declaration behind `e` eleven
/// times, and the whole file was 382 top-level questions but **5 923 ms**. A memo keyed by the node's range is sound
/// for the same reason [`crate::sema::model::SemanticModel`]'s is: a range is unique within one tree, and a tree is
/// not mutated while a query runs.
///
/// The second map answers the other repeated question. A member lookup is keyed by the **class spelling and the
/// member's name**, which is the whole of its input, and one file asks the same pair many times — `size()` on one
/// string is three lines in one file, and every rule that reads a member access asks the same question. It is a
/// memo of the *lookup*, not of the answer's use: each caller still gets its own `DeclFact` clone.
#[derive(Default)]
pub(crate) struct TypeMemo {
    types: std::cell::RefCell<std::collections::HashMap<(u32, u32), Known<(Type, PathBuf)>>>,
    /// **The questions being answered right now** — see [`TypeMemo::enter`]. Keyed like `types`, because a node is
    /// unique within one tree and a tree is not mutated while a query runs.
    in_flight: std::cell::RefCell<std::collections::HashSet<(u32, u32)>>,
    members:
        std::cell::RefCell<std::collections::HashMap<(String, String), Known<(DeclFact, PathBuf)>>>,
}

impl TypeMemo {
    /// **The type of a node already asked about, if it was.**
    fn remembered_type(&self, key: &(u32, u32)) -> Option<Known<(Type, PathBuf)>> {
        self.types.borrow().get(key).cloned()
    }

    /// **Claim a question, or be told that it is already being answered.**
    ///
    /// # Why this is a set and not the depth counter
    ///
    /// `depth` bounds a *chain of sub-expressions*, and several call sites deliberately start a **new** question at
    /// zero, because a type read out of another declaration is not part of the chain that asked for it. That is right
    /// for `auto x = f(); x.size()` and fatal for a **cycle**: measured on a real C++23 project, one member question
    /// recursed
    ///
    /// ```text
    /// text_of(site.file).content  →  text_of(site.file)          (a call: its return type is its body's)
    ///                             →  macro_definitions.lookup(token.text(…))
    ///                             →  token.text(text_of(site.file).content)   ← the same node again
    /// ```
    ///
    /// with every lap resetting `depth` to 0, until the stack was gone (32 MB did not help). The memo below could not
    /// stop it either: an answer is remembered **after** it is computed, so a question that re-enters itself finds an
    /// empty memo, forever.
    ///
    /// `false` means "this node is already on the stack above you", and the honest answer there is that the type is
    /// not knowable from these questions — which is what `Unknown` is for.
    fn enter(&self, key: (u32, u32)) -> bool {
        self.in_flight.borrow_mut().insert(key)
    }

    fn leave(&self, key: &(u32, u32)) {
        self.in_flight.borrow_mut().remove(key);
    }

    /// **One member lookup, remembered by what it was asked.**
    ///
    /// The lookup is taken as a closure so that the memo owns both the key and the miss path in one place; a caller
    /// that wanted to skip the closure on a hit would have to write the map's shape at every call site.
    fn member(
        &self,
        class: &str,
        member: &str,
        look: impl FnOnce() -> Known<(DeclFact, PathBuf)>,
    ) -> Known<(DeclFact, PathBuf)> {
        let key = (class.to_string(), member.to_string());
        // Taken out of the borrow before the miss path runs: a `match` on `borrow()` holds the `Ref` for the whole
        // match, and the `borrow_mut()` inside it panics with `RefCell already borrowed` — the same shape that bit
        // the members-free memo this one replaces.
        if let Some(known) = self.members.borrow().get(&key).cloned() {
            return known;
        }
        let answer = look();
        self.members.borrow_mut().insert(key, answer.clone());
        answer
    }
}

/// [`type_of_expression`] with the caller's memo — no new map, and every question asked below shares it.
pub(crate) fn type_of_expression_memoed(
    memo: &TypeMemo,
    index: &ProjectIndex,
    declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    expression: &cpp_parser::CppSyntaxNode,
    depth: usize,
) -> Known<(Type, PathBuf)> {
    let range = expression.text_range();
    let key = (
        u32::try_from(usize::from(range.start())).unwrap_or(u32::MAX),
        u32::try_from(usize::from(range.end())).unwrap_or(u32::MAX),
    );
    if let Some(known) = memo.remembered_type(&key) {
        return known;
    }
    // **An answer a previous request already computed**, for a *top-level* question: the answer is a function of this
    // file's expression and of the index, and every insert or forget in the index clears the memo — so a hit cannot be
    // about a world the index has left. A recursive question is a step toward an answer rather than one, and `depth`
    // bounds what it was allowed to see, so nothing below the top is filed.
    if depth == 0
        && let Some(known) = index.a_remembered_type(path, expression)
    {
        memo.types.borrow_mut().insert(key, known.clone());
        return known;
    }
    // **A node already on the stack above this call is a cycle, and no amount of depth bounds it** — see
    // [`TypeMemo::enter`] for the chain that was measured. The answer names the spelling rather than inventing a type.
    if !memo.enter(key) {
        let written = expression
            .text()
            .to_string()
            .lines()
            .next()
            .unwrap_or_default()
            .to_string();
        return Known::Unknown(UnknownReason::UnknownType(Box::from(written)));
    }

    let started = std::time::Instant::now();
    // **The recursion, when it is asked to show itself.** `depth` is bounded (`MAX_TYPE_DEPTH`) *per question*, and
    // several call sites deliberately start a **new** question at 0 — so a cycle that goes through one of them is not
    // bounded by anything. Measured on a real C++23 project: `module_graph.cpp` overflowed the stack with 32 MB on
    // `text_of(site.file).content.substr(…).starts_with(name)`, and no log said which questions repeated. One line per
    // question answers that, and it is the only instrument that can.
    if crate::probes::types() {
        eprintln!(
            "[type_of] depth {depth:>2}  {:?}",
            expression
                .text()
                .to_string()
                .lines()
                .next()
                .unwrap_or_default()
                .chars()
                .take(60)
                .collect::<String>()
        );
    }
    let answer = type_of_expression_inner(
        memo, index, declaring, scopes, root, path, expression, depth,
    );

    if crate::probes::timing() && started.elapsed().as_millis() > 5 {
        eprintln!(
            "[type_of] {:>5} ms  depth {depth}  {:?}",
            started.elapsed().as_millis(),
            expression
                .text()
                .to_string()
                .lines()
                .next()
                .unwrap_or_default()
        );
    }
    // **The claim is released before the answer is filed**, and both happen whatever the arm answered: a question
    // left in flight would make every later ask about the same node answer `Unknown`.
    memo.leave(&key);
    if depth == 0 {
        index.remember_a_type(path, expression, &answer);
    }
    memo.types.borrow_mut().insert(key, answer.clone());
    answer
}

/// The body of the inference — one arm per expression shape, and **every recursive question goes back through
/// [`type_of_expression_memoed`]** so that an answer already computed is never computed again.
fn type_of_expression_inner(
    memo: &TypeMemo,
    index: &ProjectIndex,
    declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    expression: &cpp_parser::CppSyntaxNode,
    depth: usize,
) -> Known<(Type, PathBuf)> {
    let text = expression.text().to_string();
    let written = text.trim();

    // **A bound on the recursion, not a policy about types.** Every arm below can ask the same question about a
    // *smaller* expression, and one of them asks it about a *different declaration* — which is what makes a file
    // like `auto a = *b; auto b = *a;` a loop rather than a walk. Nobody writes that, and a language server meets
    // whatever is written: past this depth the answer carries the spelling and no type, which is the same answer
    // this layer gives everything it cannot read.
    if depth > MAX_TYPE_DEPTH {
        return Known::Unknown(UnknownReason::UnknownType(Box::from(written)));
    }

    // **`co_await e` has the type of `e`'s awaiter's `await_resume()`.**
    //
    // ```cpp
    // task<std::string> greet(std::string name);
    // task<std::string> f() { auto s = co_await greet("x"); s. }   // `s` is a std::string
    // ```
    //
    // Without this the awaited expression was read as a `UnaryExpr` and fell through to the name case, so `s` was a
    // type nobody knew: measured on `test_cpp/coroutine.cpp`, completion after `s.` on
    // `auto s = co_await greet("x");` answered **nothing**, while the coroutine itself parsed and hovered. The
    // awaiter is the operand's own type — `task<T>` is its own awaiter — and the value is what
    // `await_resume()` returns, which [`operator_returns_of`] already reads for any member *with the class's
    // template arguments substituted* (`task<std::string>`'s `T` becomes `std::string`), so the two questions are
    // one call and no second substitution rule.
    //
    // A type that declares no `await_resume` is not an error this layer can name — the compiler's diagnosis is
    // better — so it answers `Unknown`, which is what keeps the completion after an unknown awaited value empty
    // rather than wrong.
    if let Some(operand) = a_co_awaits_operand(expression) {
        let awaited = type_of_expression_memoed(
            memo,
            index,
            declaring,
            scopes,
            root,
            path,
            &operand,
            depth + 1,
        );
        if let Known::Yes((awaiter, _)) = awaited
            && let Some(returns) = operator_returns_of(
                index,
                declaring,
                scopes,
                root,
                path,
                &awaiter,
                "await_resume",
            )
            && !returns.trim().is_empty()
        {
            let settled = crate::sema::types::parse_type_spelling(&returns);
            return Known::Yes((settled, path.to_path_buf()));
        }
        return Known::Unknown(UnknownReason::UnknownType(Box::from(written)));
    }

    // **A literal's type is the one thing about it nobody has to look up.**
    //
    // `auto x = 1;` is a declaration whose type the file spells in a form no name can carry, and the reader had
    // no arm for it: the literal fell through to the name case, was found not to be one, and came back
    // `UnparsableName` — which says the *spelling* could not be read when what is true is that it is not a name at
    // all. Measured, this is 8 of the `auto` declarations in MSVC's `<vector>` alone, and the shape a reader meets
    // before any other.
    //
    // Read from the **token**, not the text: `1` and `1.0f` and `"abc"` differ by their kind, and a suffix
    // (`10u`, `1.0L`) is part of the literal rather than a separate thing to interpret. A user-defined literal
    // (`10_km`) is a **lookup**: its type is the return type of `operator""_km`, and that is the arm below.
    if let Some((kind, written_as)) = expression
        .children_with_tokens()
        .filter_map(|element| element.into_token())
        .map(|token| {
            (
                cpp_parser::CppTokenKind::from(token.kind()),
                token.text().to_string(),
            )
        })
        .find(|(kind, _)| {
            !matches!(
                kind,
                cpp_parser::CppTokenKind::Whitespace | cpp_parser::CppTokenKind::Newline
            )
        })
    {
        let literal = match kind {
            cpp_parser::CppTokenKind::IntegerLiteral | cpp_parser::CppTokenKind::CharLiteral => {
                Some("int")
            }
            cpp_parser::CppTokenKind::FloatingLiteral => Some("double"),
            cpp_parser::CppTokenKind::BoolLiteral
            | cpp_parser::CppTokenKind::TrueKeyword
            | cpp_parser::CppTokenKind::FalseKeyword => Some("bool"),
            // **A string literal's element type is its encoding prefix**, which is the one part of a literal's type
            // the text carries: `L"…"` is `const wchar_t*`, `u8"…"` is `const char*`, and the plain form is too.
            // Answering `const char*` for every literal made `std::format(L"x {}", 1)` deduce `string` — the width
            // rule that picks between `format_string` and `wformat_string` was reading the wrong half.
            cpp_parser::CppTokenKind::StringLiteral => Some(a_string_literals_type(&written_as)),
            cpp_parser::CppTokenKind::NullptrLiteral | cpp_parser::CppTokenKind::NullptrKeyword => {
                Some("nullptr_t")
            }
            // **A user-defined literal's type is its operator's return type.** `"numbers"sv` is
            // `operator""sv("numbers", 1)`, whose declaration is where the type is written — a lookup, and one the index
            // answers by name. Measured on `test_cpp`'s `strings.cpp`: `"numbers"sv.size()` had no type at all, so the
            // hover on `size` said the type of `"numbers"sv` was not known and go-to-definition reached nothing.
            cpp_parser::CppTokenKind::UserDefinedLiteral => None,
            _ => None,
        };
        // **The one literal kind whose spelling is not its type.** Handled before the arm above so that the
        // `Some("int")`-style answers stay one match, and because this is the only case that needs the index.
        if kind == cpp_parser::CppTokenKind::UserDefinedLiteral {
            // **An unknown answer says what is unknown**: the literal, with its suffix, rather than the whole
            // expression, because the suffix is the part that did not resolve.
            let a_user_defined_literal_is = |returns: String| {
                Known::Yes((
                    crate::sema::types::parse_type_spelling(&returns),
                    path.to_path_buf(),
                ))
            };
            if let Some(suffix) = a_user_defined_literals_suffix(&written_as)
                && let Some(declared) = index
                    .files_declaring(&format!("operator\"\"{suffix}"), path)
                    .into_iter()
                    .find(|declared| declared.fact.kind == crate::DeclKind::Function)
                && let Some(returns) = declared.fact.returns.as_deref()
                && !returns.trim().is_empty()
            {
                return a_user_defined_literal_is(returns.to_string());
            }
            return Known::Unknown(UnknownReason::UnknownType(Box::from(written)));
        }
        if let Some(spelled) = literal {
            // **Parsed, not named.** `Type::named("int")` is a type whose *name* is `int` — a class as far as every
            // later question is concerned — and the same for `const char*`. Measured: a string literal came back as
            // `Named { name: "const char*" }`, so `has an arithmetic type` was false for `int` and the conversion
            // relation answered `Unknown` for `int count = "three";`, which is the one pair it is certain about.
            //
            // `parse_type_spelling` is the crate's own reader for a written type: it knows the builtins, the
            // qualifiers and the declarators, and it is the same function a declaration's own spelling goes through
            // — so a literal's type and a declared type are built by one implementation.
            return Known::Yes((
                crate::sema::types::parse_type_spelling(spelled),
                path.to_path_buf(),
            ));
        }
    }

    /// **The suffix of a user-defined literal** — `_kb` for `4_kb`, `sv` for `"numbers"sv`, `_f` for `1.0e5_f`.
    ///
    /// The token is one piece of text, so the boundary has to be found in it. The **last** run of identifier characters
    /// is the suffix's neighbourhood; inside it, a suffix begins at its last `_` (a numeric literal's suffix must start
    /// there, and `0x1F_kb`'s `F` is a hexadecimal digit, not a letter of the suffix) and otherwise at its first letter
    /// (`"x"sv`, `1.5s` — the reserved suffixes the standard library declares without an underscore).
    fn a_user_defined_literals_suffix(written: &str) -> Option<&str> {
        let written = written.trim_end();
        let run_start = written
            .rfind(|character: char| !(character.is_ascii_alphanumeric() || character == '_'))
            .map(|boundary| boundary + 1)
            .unwrap_or(0);
        let run = &written[run_start..];
        if run.is_empty() {
            return None;
        }
        if let Some(underscore) = run.rfind('_') {
            let suffix = &run[underscore..];
            return (suffix.len() > 1).then_some(suffix);
        }
        run.find(|character: char| character.is_ascii_alphabetic())
            .map(|at| &run[at..])
    }

    /// **The type of a string literal, from its encoding prefix** — see the literal arm of [`type_of_expression_inner`].
    ///
    /// `L` is `wchar_t`, `u8` is `char` (the C++20 `char8_t` is deliberately not introduced: a file that is not compiled as
    /// C++20 spells neither, and `const char*` is what every reader means by it), `u` is `char16_t` and `U` is `char32_t`.
    /// A raw string (`LR"(…)"`) carries the same prefix, which is why the test is a prefix rather than a quote.
    fn a_string_literals_type(written: &str) -> &'static str {
        let written = written.trim_start();
        if written.starts_with("u8") {
            return "const char*";
        }
        if written.starts_with('L') {
            return "const wchar_t*";
        }
        if written.starts_with('u') {
            return "const char16_t*";
        }
        if written.starts_with('U') {
            return "const char32_t*";
        }
        "const char*"
    }

    // **A functional cast of a template-id is that type.** `std::vector<int>()` — the initialiser behind every
    // `auto z = std::vector<int>();` — is a **call expression** whose callee is a *type with arguments in it*, so the
    // function lookup below cannot answer it: there is no function called `std::vector<int>`. The type is the
    // spelling, read off the expression, and the arguments are kept rather than resolved because `std::vector<int>`
    // is what a reader wants to see and substituting `int` into a template's parameters would be a second answer
    // free to disagree with the one the file wrote.
    //
    // Measured on a real editor session: `auto z = std::vector<int>();` had **no** type, so `z.append(…)` fell back
    // to "every `append` in the project" and hover answered with nine `basic_string::append` declarations.
    if cpp_parser::CppSyntaxKind::from(expression.kind()) == cpp_parser::CppSyntaxKind::CallExpr
        && let Some(callee) = written.strip_suffix("()")
        && callee.contains('<')
        // **A type spelling has no space in it.** `_STD h<int>()` is a macro followed by a name — two identifiers the
        // parse keeps as one name, because that is what the standard library writes — and it is not a type; a type-id
        // is one spelling. This is the shape that made the arm claim `_STD _Convert_size<int>` as a type.
        && !callee.chars().any(char::is_whitespace)
        // **…and the name before the arguments is a class.** `h<int>()` is a **function template** call, whose type is
        // `h`'s return type — the call path answers that, and answering `h<int>` here would shadow it. So the arm asks
        // the index one question: is the bare name a class? Only then is this a construction rather than a call.
        && index
            .files_declaring(callee.split('<').next().unwrap_or(callee).trim(), path)
            .iter()
            .any(|declared| declared.fact.kind == crate::DeclKind::Type)
        // **Not a macro.** `MAKE_T<int>()` is a macro invocation whose expansion the parse does not have here, and
        // `auto x = MAKE_T<int>();` is deduced from the macro's own body elsewhere — claiming the spelling as a type
        // would answer `MAKE_T<int>`, which is not a type. An all-uppercase first segment is the convention every C++
        // codebase follows for a macro, and it is the one piece of evidence this arm has.
        && !callee
            .split("::")
            .next()
            .unwrap_or(callee)
            .split('<')
            .next()
            .unwrap_or(callee)
            .chars()
            .all(|character| !character.is_ascii_lowercase())
    {
        return Known::Yes((Type::named(callee.trim()), path.to_path_buf()));
    }

    // `this` is the enclosing class, and no inference is involved: the scope chain already knows which class this
    // is, and it is the same answer inside every member function of it — and when the chain does not, the
    // definition's own qualified name does. See [`class_of_the_enclosing_definition`].
    if written == "this" {
        let offset = usize::from(expression.text_range().start());
        return match class_of_the_enclosing_definition(scopes, offset) {
            Some(class) => Known::Yes((Type::named(class), path.to_path_buf())),
            None => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
        };
    }

    // **A `new` expression is a pointer to what it allocates**, and that is C++'s rule rather than an inference:
    // `new T`, `new T(args)`, `new T[n]` and `new T{args}` all have the type `T*`. Nothing about `T`'s own type has
    // to be known, which is what makes this arm worth having where the callee's return type is not — and the shapes
    // it covers are exactly the ones a factory writes.
    //
    // Measured on MSVC's `<memory>`: **5** `auto` declarations refused with `UnknownType("new _Ref_count_obj2<_Ty>
    // (…)")` and its `_Ref_count_bounded_array` siblings — every one of them answerable from the spelling alone,
    // with the type already in the tree and nothing asking it. The template arguments are kept rather than resolved:
    // `_Ref_count_obj2<_Ty>*` is what a reader wants to see, and an attempt to resolve `_Ty` would turn a certain
    // answer into an uncertain one.
    if cpp_parser::CppSyntaxKind::from(expression.kind()) == cpp_parser::CppSyntaxKind::NewExpr {
        return match new_expression_allocates(expression) {
            Some(allocated) => Known::Yes((
                crate::sema::types::parse_type_spelling(&format!("{allocated}*")),
                path.to_path_buf(),
            )),
            None => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
        };
    }

    // A name: its declaration says what type it has. The file being edited is asked first, because a buffer that
    // has never been saved has no summary — the two-layer split the name query uses, for the same reason.
    //
    // **Qualified or bare is the same case**, and that is C++'s rule rather than a convenience: `lib::global` is one
    // entity, and the chain is part of its *spelling* — a scope to descend through, not an expression around a name.
    // Read the other way (a bare name only) every qualified name in every file was `UnknownType`: `lib::global`,
    // `std::cin`, `ns::make()` — measured, `a_qualified_name_in_this_file_has_the_type_its_declaration_wrote`.
    // **A name a structured binding introduced** — `for (auto [key, value] : map)`, `auto [a, b] = pair;`.
    //
    // The name is a variable with no written type, so the name rule below has nothing to read: the declaration says
    // `auto`, and the element’s type is whatever the *range* (or the initializer) produces. The answer is that
    // type's position-th component, which is the language's rule rather than an inference: `[a, b]` over a
    // `pair<A, B>` binds `a` to `A` and `b` to `B`, and a `map<K, V>`'s elements are `pair<const K, V>`.
    if let Some(answer) = structured_binding_type(
        memo, index, declaring, scopes, root, path, expression, depth,
    ) {
        return answer;
    }

    if writes_a_name(written) {
        return match declaration_of_expression(index, scopes, root, path, expression) {
            Known::Yes(named) => {
                let dt = declared_type(memo, index, declaring, scopes, root, path, &named, depth);
                match dt {
                    Known::Yes(type_of) => {
                        // **A declaration whose type is an alias template applied to arguments is
                        // finished here**, the same way the member arm finishes one.
                        // `enable_if_t<__is_same(int, int), double>` is a *spelling* the fact
                        // records, and the alias's target is `typename enable_if<…, double>::type`
                        // — a member of a class template applied to arguments, which
                        // `member_fact`'s pattern rule resolves once it is asked with those
                        // arguments.
                        let type_of =
                            a_trait_alias_resolved(index, scopes, root, path, &named, &type_of)
                                .unwrap_or(type_of);
                        Known::Yes((
                            substituted_at_the_use(
                                index, scopes, root, path, expression, &named, type_of,
                            ),
                            named.file(path),
                        ))
                    }
                    Known::Unknown(reason) => Known::Unknown(reason),
                    // The declaration is a function, a class or an alias: none of them has a type *as a name*, which
                    // is the distinction `DeclFact::returns` exists for.
                    Known::No => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
                }
            }
            Known::Unknown(reason) => Known::Unknown(reason),
            Known::No => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
        };
    }

    // A **braced initializer**: `Widget{…}` is a temporary of the class it names, which is what makes
    // `auto w = Widget{}` a declaration of a `Widget`. Only the first child is read, and only when it *names* a
    // type: `{1, 2}` names nothing, and a braced list of values is a different thing that this layer does not
    // deduce (C++ deduces it as `std::initializer_list`, which is a library type, not a language one).
    if cpp_parser::CppSyntaxKind::from(expression.kind()) == cpp_parser::CppSyntaxKind::InitListExpr
    {
        let Some(first) = expression.children().next() else {
            return Known::Unknown(UnknownReason::UnknownType(Box::from(written)));
        };

        // **A construction has a head, a bare braced list does not.** `{1, 2}` has values only; `Builder<int>{}` is the
        // type's name and a nested list of values. The first branch below refuses *anything* whose first child has a
        // type, which is right for a value and wrong for a type: `Builder<int>{}.with(2)` answered "the type of
        // `Builder<int>{}` is not known" while the head was a class this file declares.
        let has_a_head = cpp_parser::CppSyntaxKind::from(first.kind())
            != cpp_parser::CppSyntaxKind::InitListExpr
            && expression.children().nth(1).is_some_and(|child| {
                cpp_parser::CppSyntaxKind::from(child.kind())
                    == cpp_parser::CppSyntaxKind::InitListExpr
            });

        return match type_of_expression_memoed(
            memo,
            index,
            declaring,
            scopes,
            root,
            path,
            &first,
            depth + 1,
        ) {
            // **Not the first element's type.** `{1, 2}` is a braced list of values and C++ makes it a
            // `std::initializer_list<int>` — a library type, which this layer deliberately does not invent. Answering
            // `int` here claimed that the list *is* an `int`, and the hover that read the type at the object's last byte
            // then looked for members of `int` on a `Pair<int, int>`.
            Known::Yes(_) if !has_a_head => {
                Known::Unknown(UnknownReason::UnknownType(Box::from(written)))
            }
            _ => match declaration_of_expression(index, scopes, root, path, &first) {
                // **The spelling is read, not named.** `Type::named("Pair<int, int>")` is a class whose *name* is
                // `Pair<int, int>` and whose argument list is empty — so nothing downstream substitutes: the member
                // lookup is handed that spelling, `TypeBindings` gets no arguments, and `sum`'s written `T` comes back as
                // `T`. `parse_type_spelling` is the crate's reader for a written type and answers
                // `Named { name: "Pair", arguments: [int, int] }` for the same text.
                //
                // **And a class template with no written arguments deduces them** — `std::pair pair{1, 2}` is a
                // `pair<int, int>`; see [`the_arguments_a_braced_initialisation_deduces`].
                Known::Yes(named) if named.type_of(root, scopes).is_none() => {
                    let spelled = first.text().to_string();
                    let spelled = spelled.trim();
                    let elements = the_elements_of_a_braced_list(expression);
                    let settled = the_arguments_a_braced_initialisation_deduces(
                        memo, index, declaring, scopes, root, path, &elements, spelled, depth,
                    )
                    .unwrap_or_else(|| crate::sema::types::parse_type_spelling(spelled));
                    Known::Yes((settled, named.file(path)))
                }
                // **A qualified type name is a type even when the name query declines it.** `std::pair{1, 2}` is an
                // `InitListExpr` whose first child is an `IdentifierExpr "std::pair"` — an expression node, not a name in
                // a scope, so `declaration_of_expression` answers nothing and the list fell back to the bare spelling:
                // `auto t = std::tuple{1, 2, 3}` was a `std::tuple` with no arguments (measured with `inspect inlay`).
                // The spelling is asked of the index instead, and the deduction is the same one the arm above runs.
                _ => match a_type_the_expression_names(index, path, &first) {
                    Some(spelled) => {
                        let elements = the_elements_of_a_braced_list(expression);
                        let settled = the_arguments_a_braced_initialisation_deduces(
                            memo, index, declaring, scopes, root, path, &elements, &spelled, depth,
                        )
                        .unwrap_or_else(|| crate::sema::types::parse_type_spelling(&spelled));
                        Known::Yes((settled, path.to_path_buf()))
                    }
                    None => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
                },
            },
        };
    }

    // A **call**: what the callee returns, or a temporary of the class it names.
    if cpp_parser::CppSyntaxKind::from(expression.kind()) == cpp_parser::CppSyntaxKind::CallExpr {
        return type_of_a_call(memo, index, declaring, scopes, root, path, expression);
    }

    // **A named cast has the type it names**, and that is C++'s own rule rather than an inference: `static_cast<T>`,
    // `dynamic_cast<T>`, `const_cast<T>` and `reinterpret_cast<T>` all have the type `T`, whatever the operand is —
    // the operand's type is what the *programmer* had to know, and the cast is the statement of the answer. So
    // nothing is walked and nothing can be wrong: the `TypeId` the grammar read is the type.
    //
    // Measured before this arm existed: 39 `auto` declarations across `<vector>` and `<xutility>` refused, every one
    // of them a cast — `UnknownType("static_cast<size_t>")`, `UnknownType("const_cast<char*>")` — with the cast
    // expression already in the tree and nothing asking it.
    if cpp_parser::CppSyntaxKind::from(expression.kind()) == cpp_parser::CppSyntaxKind::CastExpr {
        let target = expression
            .children()
            .find(|child| CppSyntaxKind::from(child.kind()) == CppSyntaxKind::TypeId);
        return match target {
            Some(target) => {
                let written = target.text().to_string();
                let written = written.trim();
                Known::Yes((
                    crate::sema::types::parse_type_spelling(written),
                    path.to_path_buf(),
                ))
            }
            // A `CastExpr` with no type in it is one the recovery built around a keyword with nothing after it,
            // which is a file being typed at rather than a cast.
            None => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
        };
    }

    // **A conditional expression** has the type the two branches agree on: `cond ? 1 : 2.0` is a `double` — [expr.cond]
    // usual arithmetic conversions, the same rule a fold uses. Measured: `auto widened = true ? 1 : 2.0;` answered
    // *"the type of `true ? 1 : 2.0` is not known here"*.
    if cpp_parser::CppSyntaxKind::from(expression.kind()) == cpp_parser::CppSyntaxKind::TernaryExpr
    {
        let branches: Vec<cpp_parser::CppSyntaxNode> = expression.children().collect();
        if let (Some(one), Some(other)) = (branches.get(1), branches.get(2)) {
            let one_type = type_of_expression_memoed(
                memo,
                index,
                declaring,
                scopes,
                root,
                path,
                one,
                depth + 1,
            );
            let other_type = type_of_expression_memoed(
                memo,
                index,
                declaring,
                scopes,
                root,
                path,
                other,
                depth + 1,
            );
            if let (Known::Yes((one_type, file)), Known::Yes((other_type, _))) =
                (one_type, other_type)
            {
                let agreed = if one_type == other_type {
                    Some(one_type.clone())
                } else {
                    crate::sema::declarations::the_widest_of(&[one_type, other_type])
                        .map(|widest| crate::sema::types::parse_type_spelling(&widest))
                };
                if let Some(agreed) = agreed {
                    return Known::Yes((agreed, file));
                }
            }
        }
    }

    // **`sizeof` and `alignof` are a `size_t`**, whatever they are applied to — an expression or a type, complete or not.
    // Measured: `auto bytes = sizeof(int);` answered nothing at all, and the initialiser's tree is
    // `Initializer > UnaryExpr "sizeof(int)"`, so the arm is on the *shape* rather than on a kind this grammar does not
    // produce for it.
    {
        let spelled = expression.text().to_string();
        let spelled = spelled.trim_start();
        if spelled.starts_with("sizeof") || spelled.starts_with("alignof") {
            return Known::Yes((
                crate::sema::types::parse_type_spelling("size_t"),
                path.to_path_buf(),
            ));
        }
    }

    // A **parenthesised** expression has the type of what it wraps, and the parentheses are a node of their own:
    // `(*p).size` makes the object of the `.` a `ParenExpr`, so a recursion that did not step through it would
    // stop one level above the answer — which is exactly where it used to stop.
    if cpp_parser::CppSyntaxKind::from(expression.kind()) == cpp_parser::CppSyntaxKind::ParenExpr {
        return match expression.children().next() {
            Some(inner) => type_of_expression_memoed(
                memo,
                index,
                declaring,
                scopes,
                root,
                path,
                &inner,
                depth + 1,
            ),
            None => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
        };
    }

    // **A binary operator**, which is where most of the `auto` declarations in a standard-library header get their
    // type: `auto x = a & b;`, `auto y = p << n;`. Measured, 466 of the 488 `auto`s this could not answer were
    // expressions of this shape — `(*_VbFirst & _FirstSourceMask) << _SourceShift` and the like.
    //
    // # Three rules, and only one of them is exact for free
    //
    // * **A comparison or a logical operator yields `bool`.** `==`, `<`, `&&` … That is C++'s own answer for every
    //   operand type there is, so nothing is inferred and nothing can be wrong.
    // * **An assignment yields its left operand's type**, which is also C++'s answer rather than an inference.
    // * **Everything else is the usual arithmetic conversion**, and that is where this stops.** `a + b` is `int`
    //   for two `int`s and `unsigned` for an `int` and an `unsigned`, so the answer is **exact when the two
    //   operands already agree** — the common case in the code that survives — and is refused otherwise. Ranking
    //   the conversions (`long long` beats `unsigned`, `double` beats everything) would be a table this analysis
    //   would then have to keep right for every platform's widths; a wrong type shown for an `auto` is worse than
    //   `auto`, because the second says the file did not spell it and the first says it did.
    if let Some((operator, left, right)) = binary_operands_of(expression) {
        // **A class's own operator** — `a + b` on a type that declares `operator+`, `a == b` on one that declares
        // `operator==`. It is tried **before** the builtin rules below, because those are answers about arithmetic
        // and a class that overloads an operator has said what it means: `Money + Money` is `Money`, not "the two
        // operands agree"; `Matrix == Matrix` is whatever `operator==` returns, not necessarily `bool`.
        //
        // Assignments are left out: `a = b` is the left operand's type, which the rule below already answers, and a
        // user `operator=` that returns something else is a spelling nobody relies on for `auto`.
        if !matches!(
            operator.as_str(),
            "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "&=" | "|=" | "^=" | "<<=" | ">>="
        ) && let Known::Yes((left_class, file)) =
            type_of_expression_memoed(memo, index, declaring, scopes, root, path, &left, depth + 1)
            && matches!(left_class, Type::Named { .. })
            && let Some(returns) = operator_returns_of(
                index,
                declaring,
                scopes,
                root,
                path,
                &left_class,
                &format!("operator{operator}"),
            )
        {
            return Known::Yes((crate::sema::types::parse_type_spelling(&returns), file));
        }

        if matches!(
            operator.as_str(),
            "==" | "!=" | "<" | ">" | "<=" | ">=" | "&&" | "||"
        ) {
            return Known::Yes((Type::named("bool"), path.to_path_buf()));
        }

        let left_type =
            type_of_expression_memoed(memo, index, declaring, scopes, root, path, &left, depth + 1);
        if matches!(
            operator.as_str(),
            "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "&=" | "|=" | "^=" | "<<=" | ">>="
        ) {
            return left_type;
        }

        let Known::Yes((left_type, file)) = left_type else {
            return match left_type {
                Known::Unknown(reason) => Known::Unknown(reason),
                _ => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
            };
        };

        return match type_of_expression_memoed(
            memo,
            index,
            declaring,
            scopes,
            root,
            path,
            &right,
            depth + 1,
        ) {
            Known::Yes((right_type, _)) if right_type == left_type => {
                // **Two pointers subtracted are not a pointer.** `p - q` is a *count of elements*, and C++ spells
                // it `ptrdiff_t` — so "the operands agree, therefore the answer is their type" holds for
                // arithmetic and is wrong for exactly this pair. Measured on a fixture: `auto d = q - raw();` with
                // both operands `int*` answered **`int*`**, which is not a missing answer but a wrong one, and a
                // wrong type shown for an `auto` is worse than a refusal — the refusal says the file did not spell
                // it, the wrong answer says it did.
                //
                // Refused rather than answered `ptrdiff_t`: a file that spells its own difference type — MSVC's
                // `difference_type`, a `_Distance` — would be shown a name from another library, and this layer has
                // no way to know which of them the code is written against.
                if operator == "-" && left_type.pointee().is_some() {
                    return Known::Unknown(UnknownReason::UnknownType(Box::from(written)));
                }
                Known::Yes((left_type, file))
            }
            // **A pointer plus an integer literal is the pointer** — C++'s own rule, [expr.add] — and it is
            // written here rather than left out because the case it is for is the one this layer cannot reach yet.
            //
            // `_Get_unwrapped` returns `_It + 0` in every branch: 54 `auto` declarations over eight MSVC headers,
            // each a template parameter plus a literal. The rule needs `left_type.pointee()` — and `_It`'s type is
            // the **name** `_Iter`, not a `T*` spelling, so the analysis cannot see that it is a pointer at all
            // until the call site's argument is substituted for it. It was written, measured (306 deduced before
            // and after — it never fired) and taken back out for that reason. Instantiation is what makes it fire.
            // **The two operands disagree, so the conversion decides and this does not rank conversions.** The
            // answer is the spelling, which is what every other refusal in this layer carries.
            Known::Yes(_) => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
            Known::Unknown(reason) => Known::Unknown(reason),
            Known::No => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
        };
    }

    // A **dereference**: `*p` has the type `p` points at. Nothing is looked up — the pointer's own declaration
    // already spells the pointee, and the `*` is arithmetic on that spelling.
    if let Some(operand) = unary_operand_with(expression, "*") {
        let operand_type = type_of_expression_memoed(
            memo,
            index,
            declaring,
            scopes,
            root,
            path,
            &operand,
            depth + 1,
        );
        return match operand_type {
            // **A `*` is the type model's own operation.** `Widget**` gives `Widget*`, an array gives its
            // element, and a class with an `operator*` gives nothing — that one needs the class's members and
            Known::Yes((type_of, file)) => match type_of.pointee() {
                // **Only a pointer's or an array's `*` is the model's own operation.** A class goes to the arms
                // below even though `pointee()` answers for it too: what `*` means for a class is what the class
                // declared, and a class that declared nothing is the iterator model's case.
                Some(pointee)
                    if !matches!(type_of, Type::Named { .. } | Type::TemplateParameter { .. }) =>
                {
                    Known::Yes(((*pointee).clone(), file))
                }
                // **A class's own `operator*`** — `*it` on a user iterator, whose return type is the element the
                // operator promises. Tried first: a class that defines it has said what `*` means for itself.
                Some(_) | None => {
                    if let Some(returns) = operator_returns_of(
                        index,
                        declaring,
                        scopes,
                        root,
                        path,
                        &type_of,
                        "operator*",
                    ) {
                        return Known::Yes((
                            crate::sema::types::parse_type_spelling(&returns),
                            file,
                        ));
                    }
                    // **The iterator model**, for a class with no `operator*` that came from `begin()`: it is a
                    // view of its container's element, so `*it` is the element the type already is.
                    match &type_of {
                        Type::Named { .. } | Type::TemplateParameter { .. } => {
                            Known::Yes((type_of, file))
                        }
                        // An operand whose type has no `*` on it: the program is ill-formed, and a type invented
                        // here would be a wrong answer rather than a missing one.
                        _ => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
                    }
                }
            },
            Known::Unknown(reason) => Known::Unknown(reason),
            Known::No => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
        };
    }

    // An **address-of**: `&x` is a pointer to `x`, which is the same arithmetic the other way round. It is here
    // so that the two operators are one rule rather than one rule and one hole: `(&r)->size` is a member access
    // whose object is this, and the `->` already knows what to do with a pointer.
    if let Some(operand) = unary_operand_with(expression, "&") {
        let operand_type = type_of_expression_memoed(
            memo,
            index,
            declaring,
            scopes,
            root,
            path,
            &operand,
            depth + 1,
        );
        return match operand_type {
            Known::Yes((type_of, file)) => {
                // `&x` is a pointer to `x`, and the decay first is what makes `&arr` a pointer to the array's
                // *element* — C++'s own rule, and the reason this is not simply "wrap it in a pointer".
                let pointed_at = type_of.decay();
                Known::Yes((
                    Type::Pointer {
                        to: Arc::new(pointed_at),
                    },
                    file,
                ))
            }
            Known::Unknown(reason) => Known::Unknown(reason),
            Known::No => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
        };
    }

    // **A unary operator that a class may overload**: `-a`, `+a`, `~a`, `!a`.
    //
    // There was no arm for these at all, so `Money neg = -a;` on a class declaring `Money operator-() const` answered
    // "not a type I know" — and it was not the class case alone: `-count` on an `int` had no answer either, because
    // the binary arm's arithmetic rule never runs for a one-operand expression. The rules are the language's two:
    //
    // * a class operand goes to its own `operator-` (and `!` to `operator!`), which has said what the operator means
    //   for it — a member list names them now (`DeclFact::name` is the spelling);
    // * a builtin operand keeps its own type, except `!`, which is `bool`. C++ promotes `-`/`+`/`~` on an integer
    //   narrower than `int` to `int`, and the widths are the table the binary arm refuses to keep, so the operand's
    //   own type is the honest answer here too.
    for symbol in ["-", "+", "~", "!"] {
        let Some(operand) = unary_operand_with(expression, symbol) else {
            continue;
        };
        let operand_type = type_of_expression_memoed(
            memo,
            index,
            declaring,
            scopes,
            root,
            path,
            &operand,
            depth + 1,
        );
        return match operand_type {
            Known::Yes((type_of, file)) => {
                if matches!(type_of, Type::Named { .. } | Type::TemplateParameter { .. })
                    && let Some(returns) = operator_returns_of(
                        index,
                        declaring,
                        scopes,
                        root,
                        path,
                        &type_of,
                        &format!("operator{symbol}"),
                    )
                {
                    return Known::Yes((crate::sema::types::parse_type_spelling(&returns), file));
                }
                if symbol == "!" {
                    Known::Yes((Type::named("bool"), path.to_path_buf()))
                } else {
                    Known::Yes((type_of, file))
                }
            }
            Known::Unknown(reason) => Known::Unknown(reason),
            Known::No => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
        };
    }

    // A **conditional**: `c ? a : b` has the type the two arms agree on, and nothing else about it matters — the
    // condition is a `bool` and never part of the answer.
    //
    // That is C++'s rule for the case this layer can decide: when the arms have the same type, that is the type,
    // whichever arm runs. When they differ the *conversion* decides — `c ? 1 : 2.0` is a `double` — and this layer
    // does not rank conversions, which is the same refusal the binary arm makes and for the same reason.
    //
    // Measured: this is `_Val ? *_VbFirst : ~*_VbFirst`, seven `auto` declarations in MSVC's `<vector>`. Both arms
    // are the `_Vb_reference` the bit iterator's operators return, so they agree, and the answer is that type.
    if CppSyntaxKind::from(expression.kind()) == CppSyntaxKind::TernaryExpr {
        let arms: Vec<cpp_parser::CppSyntaxNode> = expression.children().collect();
        // Three nodes — the condition, the `?` arm and the `:` arm — with the two punctuation tokens between them.
        let (Some(then_arm), Some(else_arm)) = (arms.get(1), arms.get(2)) else {
            return Known::Unknown(UnknownReason::UnknownType(Box::from(written)));
        };
        let then_type = type_of_expression_memoed(
            memo,
            index,
            declaring,
            scopes,
            root,
            path,
            then_arm,
            depth + 1,
        );
        let else_type = type_of_expression_memoed(
            memo,
            index,
            declaring,
            scopes,
            root,
            path,
            else_arm,
            depth + 1,
        );

        return match (then_type, else_type) {
            (Known::Yes((then_type, file)), Known::Yes((else_type, _)))
                if then_type == else_type =>
            {
                Known::Yes((then_type, file))
            }
            (Known::Yes(_), Known::Yes(_)) => {
                Known::Unknown(UnknownReason::UnknownType(Box::from(written)))
            }
            // One arm unknown is the whole answer unknown, and the reason is the arm's: a caller reading
            // "`x` is not a type I know" should be told about `x`, not about the conditional around it.
            (Known::Unknown(reason), _) | (_, Known::Unknown(reason)) => Known::Unknown(reason),
            _ => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
        };
    }

    // A **subscript**: `arr[0]` has the array's element type. That is the whole of it for an array; a *class*
    // with an `operator[]` — `v[0]` on a `std::vector` — needs the template instantiated, and this answers
    // `Unknown` for the same reason it does everywhere else: see [`element_type_name`].
    if let Some(base) = subscript_base(expression) {
        let base_type =
            type_of_expression_memoed(memo, index, declaring, scopes, root, path, &base, depth + 1);
        return match base_type {
            // **An array's element is the model's own operation**, and a *class* with an `operator[]` is the case
            // this arm deliberately leaves alone: `v[0]` on a `std::vector` gives the template's `reference`, which
            // needs the class looking up — taking the first template argument instead would be right for a
            // `vector` and wrong for a `map`, and nothing here can tell them apart.
            Known::Yes((type_of, file)) => match type_of.pointee() {
                // **A pointer's subscript is the pointee.** `int* a; a[0]` is `*(a + 0)`, and C++ fixes its type as `int`
                // — no class, no instance, nothing this layer cannot read. Reported: `auto x = a[0];` answered "the type
                // of `a[0]` is not known here".
                Some(element) if matches!(type_of, Type::Pointer { .. }) => {
                    Known::Yes(((*element).clone(), file))
                }
                Some(element) if matches!(type_of, Type::Array { .. }) => {
                    Known::Yes(((*element).clone(), file))
                }
                // **The class case**: a `std::vector<int>`'s `operator[]` returns `T&`, and `members_of` has already
                // substituted the argument — so the answer is the member's own return type rather than a guess from
                // the first template argument (which would be right for a `vector` and wrong for a `map`).
                _ => match operator_returns_of(
                    index,
                    declaring,
                    scopes,
                    root,
                    path,
                    &type_of,
                    "operator[]",
                ) {
                    Some(returns) => {
                        // **The answer is a *type*, not the spelling the member wrote.** `reference` is the class's own
                        // alias for `T&`, and both halves — the alias and the parameter — are what this reads; see
                        // [`a_members_answer_as_a_type`] for the measurement.
                        let written = a_members_answer_as_a_type(
                            index, scopes, root, path, &type_of, &returns,
                        );
                        if crate::probes::inference() {
                            eprintln!(
                                "[inference] subscript on {:?}: the member wrote {:?}, the type is {:?}",
                                type_of.to_string(),
                                returns,
                                written
                            );
                        }
                        Known::Yes((crate::sema::types::parse_type_spelling(&written), file))
                    }
                    // A class with no `operator[]`: nothing this layer can say, and saying nothing is the rule.
                    None => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
                },
            },
            Known::Unknown(reason) => Known::Unknown(reason),
            Known::No => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
        };
    }

    // A member access: the type of the member, which is a fact on its declaration.
    if let Some(inner) = crate::sema::resolve::member_access_of(expression) {
        // **One question, one answer, and the shared memo.** This arm used to call the *entry point* twice — once
        // for the `Yes` and once again to get the `Unknown`'s reason — which both bypassed the memo (a fresh map per
        // call) and paid for the inference twice. On `LuaSource.cpp` this is the arm every `x.y` and `x.y()` goes
        // through, so it is the one that has to be a single memoised question.
        let (inner_type, declared_in) = match type_of_expression_memoed(
            memo,
            index,
            declaring,
            scopes,
            root,
            path,
            &inner.object,
            depth + 1,
        ) {
            Known::Yes((inner_type, declared_in)) => (inner_type, declared_in),
            Known::Unknown(reason) => return Known::Unknown(reason),
            // Not "no": a `Known::No` is this layer's answer for a name it cannot place at all, and the caller is
            // told which spelling it was — the same answer the `unreachable!` this replaces would have panicked on.
            Known::No => {
                return Known::Unknown(UnknownReason::UnknownType(Box::from(
                    inner.object.text().to_string().trim(),
                )));
            }
        };

        // **An arrow is followed as far as the type answers.** `p->` on a `Widget*` reaches `Widget`, on a
        // `std::shared_ptr<Node>` reaches `Node` — the pointer-like class says so with `element_type` (`operator->`'s
        // declared return type is a dependent `typename …::type`, which is a trait this layer cannot read). The
        // completion has resolved this for a while in [`crate::completion::the_class_after_the_operator`], including the
        // bound on a proxy whose `operator->` returns itself; this arm used to look the member up in the **handle** and
        // answered `Unknown(NotDeclaredHere("shared_ptr::twin"))` for `auto twin = node->twin();`.
        let reached_by_an_arrow = inner.arrow.then(|| {
            crate::completion::the_class_after_the_operator(
                index,
                scopes,
                root,
                path,
                &inner_type,
                true,
            )
        });
        let reached_by_an_arrow = reached_by_an_arrow.flatten();
        let Some(class) = reached_by_an_arrow
            .clone()
            .map(|(reached, _)| reached)
            .or_else(|| member_access_class(&inner_type))
        else {
            return Known::Unknown(UnknownReason::UnknownType(Box::from(
                inner_type.to_string(),
            )));
        };

        // **The class as the declaration spelled it, and then as the name that spelling resolves to.** A type
        // written inside a namespace is spelled there *without* its qualifier — MSVC's `<iostream>` writes
        // `extern istream cin;` inside `std` — so a member lookup for `std::cin.read` is handed `istream` while the
        // class it needs is `std::istream`. C++ resolves that spelling in the scope the declaration is in; this
        // asks the index for the **name** from the file the declaration is in, which is the same lookup whenever
        // that file sees exactly one such name — and no answer at all (with the first reason kept) when it sees
        // several, which is the direction this layer fails in.
        //
        // **The arguments the use wrote**, which is what turns a member's own _Ty& into int&: the parameter names
        // are the declaring class's ([DeclFact::parameters]) and the arguments are the object type's, and the pairing
        // is positional — see [crate::TypeBindings].
        //
        // **And when the use wrote none, the alias it named may have carried them.** `std::string` has no
        // arguments of its own — it is one name — and the class it resolves to was written with three:
        // `basic_string<char, char_traits<char>, allocator<char>>`. Without them the pairing is empty, `_Elem` has
        // nothing to be replaced by, and `x.back()` on a `std::string` answers `_Elem&`: measured, and it is the
        // last step between that and `char&`. See [`member_access_class_and_arguments`].
        let (class, arguments) =
            member_access_class_and_arguments(index, scopes, root, path, &class, &inner_type);
        // **The pointee, by the handle's own `element_type` — substituted.** `std::shared_ptr` declares
        // `using element_type = _Tp;`, so the member is `_Tp` until the object type's argument is paired with it
        // (`shared_ptr<Node>` → `Node`). Asked first, because it is the protocol and it knows the arguments; the
        // completion's resolver is the fallback for the shapes it covers (`p->` on a real pointer, an `operator->`
        // whose return type is a class).
        let (class, arguments) = match inner.arrow {
            true => the_pointee_of_a_handle(index, scopes, root, path, &class, &arguments)
                .or_else(|| {
                    reached_by_an_arrow
                        .clone()
                        .map(|(reached, _)| (reached, Vec::new()))
                })
                .unwrap_or((class, arguments)),
            false => (class, arguments),
        };
        // The arguments as **spellings**, which is what a pattern comparison is: a pattern is what the other
        // declaration wrote, and two spellings of one type would not compare equal. The direction this rule fails in
        // is "no match", which keeps an answer rather than removing one.
        let written_arguments: Vec<String> = arguments
            .iter()
            .map(|argument| argument.to_string())
            .collect();
        let found = memo.member(&class, &inner.member, || {
            member_fact(
                index,
                scopes,
                root,
                path,
                &class,
                &inner.member,
                Some(&written_arguments),
            )
        });
        let found = match found {
            Known::Yes(found) => Known::Yes(found),
            Known::Unknown(reason) => match declared_class(index, &declared_in, &class) {
                Some(qualified) => {
                    match memo.member(&qualified, &inner.member, || {
                        member_fact(
                            index,
                            scopes,
                            root,
                            path,
                            &qualified,
                            &inner.member,
                            Some(&written_arguments),
                        )
                    }) {
                        Known::Yes(found) => Known::Yes(found),
                        Known::Unknown(_) | Known::No => Known::Unknown(reason),
                    }
                }
                None => Known::Unknown(reason),
            },
            Known::No => Known::No,
        };
        let Known::Yes((fact, file)) = found else {
            let Known::Unknown(reason) = found else {
                unreachable!("the first match established that this is an `Unknown`")
            };
            return Known::Unknown(reason);
        };

        // **Which question is being asked depends on where the cursor is, and both are real.**
        //
        // ```text
        // `v.data`    a member function named on its own   a function has no type *as a name*   nothing to give
        // `v.data()`  the callee of a call                 what a call of it has                the return type
        // `v.front`   a data member                        what its declaration says           `_Ty&`, substituted
        // ```
        //
        // A cursor inside `data` in `v.data()` is on the **callee**, and every consumer asking about it — a hover,
        // an inlay hint — wants the type of `v.data()`. Measured before this existed: the four offsets of `data`
        // answered `UnknownType("v.data")` while the `(` one byte later answered `int*`, so the answer depended on
        // which byte of one name the user was pointing at.
        let arguments = arguments.to_vec();
        let bindings = member_bindings(index, scopes, root, path, &class, &arguments);

        let being_called = expression.parent().is_some_and(|parent| {
            cpp_parser::CppSyntaxKind::from(parent.kind()) == cpp_parser::CppSyntaxKind::CallExpr
        });

        // **A member of a class template is finished here**, and this is the one place it can be: the argument list
        // is the object type's, which is what this arm just computed, and the parameter names are the declaring
        // class's. `v.front` on a `std::vector<int>` is `_Ty&` in the header and `int&` here — without this the
        // answer is a type called `_Ty`, which is not a class, so nothing can follow it.
        //
        // **A member whose type is another member of the same class**: `_Ty& reference; reference front;`. The
        // substitution has nothing to replace in `reference` — that spelling does not mention `_Ty` — so the name
        // is resolved as a member of the *same* class with the same argument pairing, and the walk repeats while
        // the type is still a bare name.
        //
        // A chain of two is real and common: `size_type` → `size_t` is how every standard container declares
        // `size()`, `capacity()`, `max_size()`. The walk is bounded by [`MAX_NESTED_TYPE_DEPTH`] rather than by an
        // argument about termination, because the argument is nearly — not exactly — true: each step asks about a
        // *different* name and a class has finitely many members, but two members can name each other (`a b; b a;`
        // is not valid C++ and *is* writable text), and a walk that trusted validity would not terminate on the
        // file a language server has to survive.
        //
        // **A call's return type is finished the same way**, which is what the closure is for: `x.back()` answers
        // `reference` in MSVC's `<xstring>` (`typedef _Ty& reference;`), and that is one more bare name standing for
        // a member of the same class. Without the second use of this walk, `auto y = x.back()` recorded the *name*
        // `reference` as `y`'s type — measured, and it is what a reader saw when hovering an `auto` variable: a type
        // that is not a type, on a declaration the compiler types as `char&`.
        if let Some(type_of) = fact.type_of.as_deref() {
            // **An alias template at the head of the spelling is followed here, and this is the exit that needed it.**
            //
            // A member whose type is `enable_if_t<__is_same(int, int), double>` answered with exactly that spelling:
            // the reader parsed the declaration's own text and returned it, and no step in between knew that the
            // head of it is an alias. Following it turns the type into `typename enable_if<__is_same(int, int),
            // double>::type` — a member of a **class template applied to arguments** — and the walk below is the one
            // that resolves such a member, by the pattern comparison that folds a decidable builtin to the `true`
            // the library wrote its `enable_if` for.

            if let Some((named, member)) = the_alias_behind(index, &file, type_of) {
                // **The chain is what has already been *resolved*, not what is about to be asked.** Pushing the member
                // here made the walk refuse its first question — `asked.contains("type")` — and the answer came back as
                // the member's own name (measured: `Some("type")` where the file means `double`).
                let chain = vec![fact.name.clone()];
                // **The bindings of the class the member was found in**, not of the class the *use* names: the walk is
                // about to read `enable_if<…, double>::type`, whose declaration says `_Ty`, and `_Ty` is `double` here
                // because that class was applied to `double`. Passing the object's bindings (`Widget`'s, which pair
                // nothing with nothing) left the parameter's own name standing — measured: `Some("_Ty")`.
                // **The arguments split where the *language* splits them.** `Type::arguments` (from
                // `parse_type_spelling`) read `__is_same(int, int)` as two arguments — it does not count parentheses —
                // so the substitution paired `_Ty` with `int)` and the answer was `Some("int)")`. `split_arguments`
                // counts brackets and parentheses, which is the rule the pattern comparison already uses; the class
                // name is the bare one, because a class's parameters are filed under it.
                let inner = named
                    .split_once('<')
                    .map(|(_, rest)| rest.trim_end().strip_suffix('>').unwrap_or(rest))
                    .unwrap_or_default();
                let argument_types: Vec<crate::sema::types::Type> =
                    crate::sema::builtins::split_arguments(inner)
                        .iter()
                        .map(|one| crate::sema::types::parse_type_spelling(one))
                        .collect();
                let bare_named = named
                    .split_once('<')
                    .map(|(head, _)| head.trim())
                    .unwrap_or(named.as_str());
                let trait_bindings =
                    member_bindings(index, scopes, root, path, bare_named, &argument_types);
                let finished = finish_a_nested_name(
                    index,
                    scopes,
                    root,
                    path,
                    &named,
                    &trait_bindings,
                    parse_type_spelling(&member),
                    file,
                    chain,
                );

                return Known::Yes(finished);
            }

            let finished = bindings.applied_to(&parse_type_spelling(type_of));
            return Known::Yes(finish_a_nested_name(
                index,
                scopes,
                root,
                path,
                &class,
                &bindings,
                finished,
                file,
                vec![fact.name.clone()],
            ));
        }

        // No `type_of`: the declaration is a function (or a class). For a function being **called**, the answer is
        // what the call has; for one merely named, there is no type and saying so is the honest answer.
        if being_called && let Some(returns) = what_a_call_has_in(&fact) {
            return Known::Yes(finish_a_nested_name(
                index,
                scopes,
                root,
                path,
                &class,
                &bindings,
                bindings.applied_to(&returns),
                file,
                vec![fact.name.clone()],
            ));
        }

        return Known::Unknown(UnknownReason::UnknownType(Box::from(written)));
    }

    Known::Unknown(UnknownReason::UnknownType(Box::from(written)))
}

/// The type **every** visible declaration of `name` agrees on — the declaration to read it from, and its file.
///
/// The one question a type query can still answer when a *name* query cannot: `Ambiguous` means several
/// declarations are visible, and "which one is it" has no answer, while "what type does it have" does whenever
/// they all say the same thing — which redeclarations do by construction
/// (`extern istream cin;` written twice in MSVC's `<iostream>`, once of them under `extern "C++"`).
///
/// `None` when there is nothing visible, when any candidate is a function or a class (neither has a type *as a
/// name* — see [`DeclFact::returns`]), or when two candidates spell the type differently. A disagreement is
/// exactly what `Ambiguous` was about, so it is not resolved here.
fn agreeing_type(index: &ProjectIndex, path: &Path, name: &str) -> Option<(DeclFact, PathBuf)> {
    let candidates = index.files_declaring(name, path);
    let mut agreeing: Option<(DeclFact, PathBuf)> = None;

    for found in &candidates {
        // **A class's type is the class**, and reading `type_of` alone said otherwise.
        //
        // `DeclFact::type_of` is what a declaration wrote *as a type of something else* — a variable's type, an
        // alias's target — and a class has none, so the `?` below returned `None` for the whole list the moment one
        // candidate was a class. Measured on the report that started this: `std::vector` is declared thirteen times
        // (the primary template, `vector<bool>`, the deduction guides), every one of them a class, and
        // `auto x = std::vector<int>();` was refused as `UnknownType("std::vector<int>")` while `ns::Box<int>()` —
        // **one** declaration, in a fixture — deduced. The candidates were never disagreeing; they were being read
        // with a field that is not the answer for a class.
        //
        // A class candidate therefore agrees with every other class candidate **of the same qualified name**, which
        // is what makes `std::vector` and its partial specialisations one answer rather than thirteen.
        let type_of = match found.fact.kind {
            crate::DeclKind::Type => found.fact.qualified_name(),
            _ => found.fact.type_of.clone()?,
        };

        match &agreeing {
            None => agreeing = Some((found.fact.clone(), found.file.clone())),
            Some((first, _)) if first.type_of.as_deref() == Some(type_of.as_str()) => {}
            Some((first, _))
                if first.kind == crate::DeclKind::Type && first.qualified_name() == type_of => {}
            Some(_) => return None,
        }
    }

    agreeing
}

/// The longer spelling a bare type name resolves to **where it was declared** — `Widget` → `lib::Widget`.
///
/// `None` in the three cases where the spelling as written is all this layer has: it is already qualified (a claim
/// about where the name lives, so there is nothing to look up), nothing declares it, or **more than one**
/// declaration is visible from the declaring file — where the honest answer is the caller's first reason rather
/// than one of the candidates.
///
/// The same one step of the same rule [`resolved_in_the_enclosing_scopes`] applies to a base clause, and the same
/// reason it exists: a name written inside a namespace is spelled without that namespace, and a lookup that stopped
/// at the spelling found `std::_Tree` neither as a base of `std::map` nor as the class of `std::cin`.
fn declared_class(index: &ProjectIndex, declaring: &Path, class: &str) -> Option<String> {
    if class.contains("::") {
        return None;
    }

    // **An alias template's name is not the class it stands for, and this is where that matters.**
    //
    // `enable_if_t<__is_same(int, int), double>` is a member's *type*, and the walk below asks this function which
    // class that spelling names. The index files an alias template under its bare name — `enable_if_t` — so the
    // lookup with the whole spelling answered nothing, the alias was never followed, and a member whose type is a
    // constrained alias came back as the spelling it was written with. That is the whole of what blocked
    // `enable_if`: the class on the other side of the alias is `enable_if<__is_same(int, int), double>`, and only
    // once *that* is the name being asked about does the specialization get chosen — by the pattern comparison,
    // which folds a decidable builtin to the `true` the library wrote its `enable_if` for.
    //
    // The arguments are substituted into the alias's own target here rather than in the sharing function below
    // (`alias_target_of`), because this path has no tree: the alias is a fact, its parameters are a field, and the
    // target is a spelling. Nothing else about the lookup changes.
    if let Some((head, rest)) = class.split_once('<')
        && let Some(inside) = rest.trim_end().strip_suffix('>')
        && let Known::Yes(found) = index.definition(head.trim(), declaring)
        && found.fact.kind == crate::DeclKind::Type
        && let Some(target) = found.fact.type_of.as_deref()
    {
        let written = crate::sema::builtins::split_arguments(inside);
        let target =
            crate::sema::types::substituted_spelling(target, &found.fact.parameters, &written);
        if let Some(named) = crate::sema::types::parse_type_spelling(&target).class_name() {
            return Some(named.to_string());
        }
    }

    match index.definition(class, declaring) {
        Known::Yes(found) => {
            let qualified = found.fact.qualified_name();
            (qualified != class).then_some(qualified)
        }
        Known::Unknown(_) | Known::No => None,
    }
}

/// The operand of the unary expression this node is, when its operator is `operator`.
///
/// `*p` and `&x` are `UnaryExpr` — the node every unary operator gets — so what makes one a dereference is the
/// **operator**, exactly as it is for a member access (`w.size` and `arr[0]` share a node kind too). The operator
/// is matched by text rather than by token kind for the same reason: a shape reader that had to know the token's
/// name would be a second place to update if the name changed.
///
/// `-x` and `!x` are `UnaryExpr`s as well and are deliberately not this: what they have is not a pointer.
/// **A binary expression's operator and its two operands**, or None when this is not one.
///
/// The node is left op right, so the operator is the one token between the two expression children — found by
/// position rather than by spelling, because >> is one token here and > > would be two other readings.
fn binary_operands_of(
    node: &cpp_parser::CppSyntaxNode,
) -> Option<(String, cpp_parser::CppSyntaxNode, cpp_parser::CppSyntaxNode)> {
    if cpp_parser::CppSyntaxKind::from(node.kind()) != cpp_parser::CppSyntaxKind::BinaryExpr {
        return None;
    }

    let mut operands = Vec::new();
    let mut operator: Option<String> = None;
    for element in node.children_with_tokens() {
        // A child that is not a token is an operand; the first token that is not trivia is the operator. The two
        // are told apart by `into_token`, which is this crate's idiom for the question — see `sema::semantic`.
        if let Some(token) = element.as_token() {
            if operator.is_none()
                && !matches!(
                    cpp_parser::CppTokenKind::from(token.kind()),
                    cpp_parser::CppTokenKind::Whitespace | cpp_parser::CppTokenKind::Newline
                )
            {
                operator = Some(token.text().to_string());
            }
        } else if let Some(child) = element.into_node() {
            operands.push(child);
        }
    }

    match (operator, operands.as_slice()) {
        (Some(operator), [left, right]) => Some((operator, left.clone(), right.clone())),
        _ => None,
    }
}

/// **What a class's `operator<name>` returns** — the member's own return type, read from the file that declares the
/// class, which is the only place its member list can be read from.
///
/// `None` for a class that declares no such operator, for one nobody declared (a template parameter, a name from a
/// header the project never read), and for an operator whose declaration did not spell a return type. Every `None`
/// means "this layer has no answer", never "the program has no answer".
pub(crate) fn operator_returns_of(
    index: &ProjectIndex,
    declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    class_type: &Type,
    operator: &str,
) -> Option<String> {
    let class = class_type.class_name()?.to_string();

    // **A name that is an alias is not a class, and asking for its operator parses a file.**
    //
    // `files_declaring` answers with the declarations of the *name*, and the next step asks the session for the view
    // of the file the first one is in — a parse of that file. For `std::size_t` that declaration is a typedef in a
    // system header, so every binary expression with a `std::size_t` operand paid for that header's tree before the
    // answer ("a typedef has no `operator>`") was known.
    //
    // [`DeclFact::type_of`] is what tells the two apart: a class definition declares no type of its own, an alias
    // does. An alias's operators are its target's, which this cannot answer without resolving the target first — and
    // the callers answer a comparison `bool` and an arithmetic its operand's type, which is right for every
    // arithmetic alias.
    //
    // Measured on EmmyLuaCodeStyle's `LuaParser/src/File/LuaSource.cpp`: `implicit-bool-conversion`
    // **265 → 93 ms**.
    let declared = index.files_declaring(&class, path);
    let first = declared.first()?;
    if first.fact.type_of.is_some() {
        return None;
    }
    let class_file = Some(first.file.clone());

    // **The single member first, and the whole list only as a fallback.** What this question wants is one
    // declaration's `returns`, and a member list is a far more expensive way to find it: building one reads every
    // member of the class and walks its bases, while `member_fact` asks the index's own scope postings. Measured on
    // `LuaSource.cpp`, where fourteen subscript expressions ask about `std::vector<…>::operator[]`: the member list
    // was **24 ms** each and the listing repeated fourteen times, for **340 ms of a 376 ms** `assign-type-check`
    // pull. The list stays as the fallback because it also answers for a member whose name the postings spell
    // differently (a base's, an operator's without its `operator` prefix).
    //
    // The two spellings are the two a fact can carry for an operator: the declarator's own (`operator[]`) and the
    // bare symbol a reader that recorded only the operator token answered with (`[]`).
    //
    // **A `Yes` ends the question, `None` or not.** The list below is built in the same order this query walks —
    // the class's own declarations first, then each level of bases — so the declaration this found is the one the
    // list's own `find` would return first, and asking the list again can only produce the same `returns`. That is
    // what makes the whole list unnecessary whenever the narrow query hits, which is every operator on every class
    // the index has read.
    let wanted: String = operator
        .chars()
        .filter(|character| !character.is_whitespace())
        .collect();
    let symbol = wanted.strip_prefix("operator").unwrap_or(&wanted);
    // **The class's own parameter names, and the arguments written at the use** — what a return spelling like `T&`
    // has to be read through before it is a type. `member_fact` answers the *fact*, which carries the declaration's
    // own words (`T& operator[]`); the list fallback below substitutes them, so this path has to as well or the same
    // question answers `T&` here and `int&` there.
    // **The parameters of the declaration that has any.** `first` is the class's first declaration in insertion
    // order, and for a class template that is as often a forward declaration as the definition — measured on MSVC's
    // `std::shared_ptr`, whose first fact carries no parameter list at all, so `_Ty2 *` came back unsubstituted and a
    // member lookup was asked about a class called `_Ty2`. `template_parameters_of` already answers this question the
    // right way for the rest of the analysis (it skips empty lists), so the two cannot disagree.
    let written_arguments: Vec<String> = class_type
        .arguments()
        .iter()
        .map(|argument| argument.to_string())
        .collect();
    // **The declarations that match this use**, not just "the first one with parameters" — see
    // [`ProjectIndex::template_parameters_for`].
    let parameters = index.template_parameters_for(&class, path, &written_arguments);
    let parameter_names = &parameters;
    if crate::probes::inference() {
        eprintln!(
            "[inference] operator_returns_of({class}, {operator}): parameters {parameters:?}, arguments {written_arguments:?}"
        );
    }
    for spelling in [wanted.as_str(), symbol] {
        if let Known::Yes((fact, _)) = member_fact(
            index,
            scopes,
            root,
            path,
            &class_type.to_string(),
            spelling,
            None,
        ) {
            let returns = fact.returns?;
            return Some(crate::sema::types::substituted_spelling(
                &returns,
                parameter_names,
                &written_arguments,
            ));
        }
    }

    let class_view = class_file.as_deref().and_then(declaring);
    let (class_scopes, class_root, class_path) = match &class_view {
        Some(view) => (view.scopes.as_ref(), &view.root, view.path.as_path()),
        None => (scopes, root, path),
    };

    let Known::Yes(list) = members_of(
        index,
        class_scopes,
        class_root,
        class_path,
        &class_type.to_string(),
    ) else {
        return None;
    };

    // **The spelling is normalised**: the name a declaration records is whatever the declarator's tokens said, and
    // `operator *` and `operator*` are the same operator with a space in it. Comparing without whitespace makes the
    // two spellings one question, and the bare symbol is accepted as well because a reader that recorded only the
    // operator's own token answered `*`.
    let found = list.members.iter().find(|member| {
        let name: String = member
            .fact
            .name
            .chars()
            .filter(|character| !character.is_whitespace())
            .collect();
        name == wanted || name == symbol
    })?;
    let returns = found.fact.returns.clone()?;

    // **An operator inherited from a base answers in the base's spelling.** `template <class T> struct Base { T*
    // operator->(); }; template <class T> struct Ptr : Base<T> {};` — `Ptr<S>`'s arrow is `Base<S>::operator->`,
    // whose return type is written `T*`: read literally that is a class called `T`, which has no members, so the
    // completion after `ptr->` offered **nothing**. It has to be read through the base clause's arguments (and those
    // through the derived class's own), which is what this asks before the class's own parameters are tried.
    // Measured on that fixture: 0 items before, the pointee's members after; the same shape is libstdc++'s
    // `shared_ptr`, whose `operator->` is declared in `__shared_ptr<_Tp, _Lp>`.
    if found.declared_in != class
        && let Some(substituted) = a_base_operators_return(
            index,
            scopes,
            root,
            path,
            &class,
            &found.declared_in,
            &returns,
            parameter_names,
            &written_arguments,
        )
    {
        return Some(substituted);
    }

    Some(crate::sema::types::substituted_spelling(
        &returns,
        parameter_names,
        &written_arguments,
    ))
}

/// **The operand of a `co_await`, when this node is one.**
///
/// `co_await e` is parsed as a `UnaryExpr` whose first token is the keyword — see `exprs.rs`, where the arm exists
/// because the keyword was in `is_expression_keyword` and no rule consumed it. The operand is the node after the
/// keyword; a tree with none (a malformed `co_await` being typed at) answers `None`, and the caller falls through
/// to the shapes that do not need one.
fn a_co_awaits_operand(
    expression: &cpp_parser::CppSyntaxNode,
) -> Option<cpp_parser::CppSyntaxNode> {
    if cpp_parser::CppSyntaxKind::from(expression.kind()) != cpp_parser::CppSyntaxKind::UnaryExpr {
        return None;
    }
    let mut children = expression.children_with_tokens();
    let keyword = children
        .find_map(|element| element.into_token())
        .filter(|token| {
            cpp_parser::CppTokenKind::from(token.kind()) == cpp_parser::CppTokenKind::CoAwaitKeyword
        })?;
    let _ = keyword;
    children.find_map(|element| element.into_node())
}

/// **A return type that is one bare name plus its operators** — `element_type*` gives `("element_type", "*")`, and
/// `None` for anything else (a qualified name, a template-id, a reference). Only the bare shape can name a member
/// typedef of the class whose operator wrote it; anything richer is a type the substitution already handles.
fn a_bare_type_and_its_operators(written: &str) -> Option<(&str, String)> {
    let trimmed = written.trim();
    let name_len = trimmed
        .chars()
        .take_while(|character| character.is_alphanumeric() || *character == '_')
        .count();
    if name_len == 0 {
        return None;
    }
    let (name, rest) = trimmed.split_at(name_len);
    let suffix: String = rest
        .chars()
        .filter(|character| !character.is_whitespace())
        .collect();
    if !suffix
        .chars()
        .all(|character| matches!(character, '*' | '&'))
    {
        return None;
    }
    Some((name, suffix))
}

/// **A base's operator return, read through the base clause's arguments.** `None` when the clause that names this
/// base cannot be found or its arguments cannot be read — the caller then answers with the spelling as written, which
/// is what this function refines.
fn a_base_operators_return(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    class: &str,
    declared_in: &str,
    returns: &str,
    parameter_names: &[String],
    written_arguments: &[String],
) -> Option<String> {
    // The base list is asked for as a **precondition**: this returns before any substitution when the class's clause
    // cannot be read. The value is dropped on purpose — [`the_arguments_of_a_base`] below reads what is in it.
    let Known::Yes(_) = bases_of(index, scopes, root, path, class) else {
        return None;
    };
    // **The base list carries the clause's arguments as their own entries.** `bases_of(Ptr)` answers
    // `["Base", "T"]` for `struct Ptr : Base<T> {}` — the class and the names *inside* its clause, which is what the
    // lookup does with them (`_Tp` and `_Lp` really can be a base's name). So the arguments of the base we found are
    // the entries right after it, and how many there are is the base template's arity.
    // **The operator may be inherited through more than one level.** libstdc++'s `shared_ptr<_Tp> : __shared_ptr<_Tp,
    // _S_single> : __shared_ptr_access<_Tp, _Lp, false, false>` declares `operator->` two bases down, so looking only
    // at the direct base clause finds nothing and the return type stays the unsubstituted `element_type *`. The
    // substitution is therefore composed along the chain: each base clause's arguments are read through the previous
    // level's parameters.
    let (parameters, arguments) = the_arguments_of_a_base(
        index,
        scopes,
        root,
        path,
        class,
        declared_in,
        parameter_names,
        written_arguments,
        0,
    )?;
    // **The base's return type may name one of its own typedefs.** `__shared_ptr_access` writes
    // `element_type* operator->()` and `element_type` is `using element_type = _Tp;` *inside* it — so substituting
    // `_Tp` alone never reaches it: the pointee comes out as a class called `element_type`, which has no members, and
    // the completion after `shared_ptr<std::string>::operator->` is empty. A bare name is read as a member of the
    // class that declared the operator, substituted, and the operators around it put back on.
    if let Some((name, suffix)) = a_bare_type_and_its_operators(returns)
        && let Known::Yes((alias, _)) =
            member_fact(index, scopes, root, path, declared_in, name, None)
        && let Some(target) = alias.type_of.clone()
    {
        let substituted =
            crate::sema::types::substituted_spelling(&target, &parameters, &arguments);
        return Some(format!("{substituted}{suffix}"));
    }

    Some(crate::sema::types::substituted_spelling(
        returns,
        &parameters,
        &arguments,
    ))
}

/// **The substitution that reaches `wanted` from `class` along the base clauses** — its template parameters and their
/// arguments, composed one level at a time.
fn the_arguments_of_a_base(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    class: &str,
    wanted: &str,
    parameters: &[String],
    arguments: &[String],
    depth: usize,
) -> Option<(Vec<String>, Vec<String>)> {
    if depth > 6 {
        return None;
    }
    let leaf = |spelling: &str| spelling.rsplit("::").next().unwrap_or(spelling).to_string();
    let Known::Yes(bases) = bases_of(index, scopes, root, path, class) else {
        return None;
    };
    let mut at = 0usize;
    while at < bases.len() {
        let written = &bases[at];
        let resolved = resolved_in_the_enclosing_scopes(index, scopes, path, class, written);
        let arity = index.template_parameters_for(&resolved, path, &[]).len();
        let of_the_base: Vec<String> = bases
            .iter()
            .skip(at + 1)
            .take(arity)
            .map(|argument| {
                crate::sema::types::substituted_spelling(argument, parameters, arguments)
            })
            .collect();
        let of_the_base_parameters = index.template_parameters_for(&resolved, path, &of_the_base);
        if leaf(&resolved) == leaf(wanted) {
            return Some((of_the_base_parameters, of_the_base));
        }
        if let Some(found) = the_arguments_of_a_base(
            index,
            scopes,
            root,
            path,
            &resolved,
            wanted,
            &of_the_base_parameters,
            &of_the_base,
            depth + 1,
        ) {
            return Some(found);
        }
        at += 1 + arity;
    }
    None
}

fn unary_operand_with(
    node: &cpp_parser::CppSyntaxNode,
    operator: &str,
) -> Option<cpp_parser::CppSyntaxNode> {
    if cpp_parser::CppSyntaxKind::from(node.kind()) != cpp_parser::CppSyntaxKind::UnaryExpr {
        return None;
    }

    let first = node.children_with_tokens().next()?;
    if first
        .as_token()
        .is_none_or(|token| token.text() != operator)
    {
        return None;
    }

    // The operand is the node after it, which is what a type is inferred *from*.
    node.children().next()
}

/// The base of a `[…]` expression, when that is what this node is.
///
/// `arr[0]` and `w.size` are both `IndexExpr` — the parser reads `w.size` as an index expression with a `.`
/// where the brackets would be — so the operator is
/// what tells them apart. A member access is not a subscript and never reaches the inference for one.
fn subscript_base(node: &cpp_parser::CppSyntaxNode) -> Option<cpp_parser::CppSyntaxNode> {
    if cpp_parser::CppSyntaxKind::from(node.kind()) != cpp_parser::CppSyntaxKind::IndexExpr {
        return None;
    }

    let has_brackets = node
        .children_with_tokens()
        .any(|element| element.as_token().is_some_and(|token| token.text() == "["));
    if !has_brackets {
        return None;
    }

    node.children().next()
}

/// What a `*` on this spelling gives: `Widget*` → `Widget`, `Widget&` → `Widget`, `Widget**` → `Widget*`.
///
/// The operators written after the type are removed, and so is a cv-qualifier written after *them* — `Widget *
/// const` is a const pointer to a `Widget`, so what the `*` gives is the `Widget` and not `Widget * const`.
/// Everything else is kept as written, template arguments included: how much of a spelling names the *class* is
/// the member lookup's question, and it answers that one itself with [`base_type_name`].
///
/// `None` when there is no operator to remove, which is the honest answer for `*x` where the declaration says
/// `x` is an `int`: nothing in a declaration of `x` says otherwise, and a type invented here would be a wrong
/// answer rather than a missing one.
fn pointee_type_name(written: &str) -> Option<String> {
    let mut name = written.trim().to_string();

    // The qualifiers of the *pointer* come first because they are written last: `Widget* const`.
    loop {
        let trimmed = name.trim_end();
        let Some(rest) = trimmed
            .strip_suffix("const")
            .or_else(|| trimmed.strip_suffix("volatile"))
        else {
            break;
        };
        name = rest.trim_end().to_string();
    }

    let trimmed = name.trim_end();
    let stripped = trimmed
        .strip_suffix("&&")
        .or_else(|| trimmed.strip_suffix('*'))
        .or_else(|| trimmed.strip_suffix('&'))?;

    let pointee = stripped.trim().to_string();
    (!pointee.is_empty()).then_some(pointee)
}

/// The declaration an expression **names**, from the file being edited or from the index.
///
/// The reconciliation the two-layer split needs, in one place: the buffer answers with a [`crate::Binding`] whose
/// spellings are read out of the tree, while an indexed file answers with a [`DeclFact`] that carries them as
/// fields. Both are needed for the same two questions — what type does this name have, what does a call of it
/// give — and a second reconciliation would be a second rule book for the same question.
///
/// The answers are the ones the name query gives, and for the same reason: a name this file cannot place is asked
/// of the index, and a name *nothing* declares is [`UnknownType`] carrying the spelling rather than
/// [`UnknownReason::NotDeclaredHere`] — what is missing here is the type of an expression, which is a different
/// thing for a consumer to be told.
///
/// [`UnknownType`]: UnknownReason::UnknownType
// **A big variant, kept inline on purpose.** `Known` answers for every expression the engine types, and boxing the
// found case would put an allocation on the hot path of every member lookup to save the difference between 392 and
// 48 bytes in an enum that lives for the length of one question. The variants are also matched on by value in a
// dozen places, where the box would be a deref at each site.
#[allow(clippy::large_enum_variant)]
enum NamedDeclaration {
    /// A binding of the file being edited. Its spellings come from the tree the caller has.
    Here(crate::Binding),
    /// A declaration in an indexed file, with the file it is in — and, when it was found **through a class**
    /// that had template arguments, the pairing that finishes its type.
    ///
    /// The arguments belong to the *lookup* rather than to the declaration: `std::vector<int>::data` and
    /// `std::vector<float>::data` are one declaration whose type is `_Ty*`, and which of the two a use means is
    /// decided by the object expression. Carrying them here is what lets both questions a consumer asks — "what
    /// type does this have" and "what does a call of it give" — finish the same way, instead of only the first.
    Indexed(DeclFact, PathBuf, TypeBindings),
}

impl NamedDeclaration {
    /// Where the declaration is — the answer's own file, for a consumer that has to jump or to look further.
    fn file(&self, here: &Path) -> PathBuf {
        match self {
            NamedDeclaration::Here(_) => here.to_path_buf(),
            NamedDeclaration::Indexed(_, file, _) => file.clone(),
        }
    }

    /// **The kind of the thing this names**, which a caller needs to tell a member function from an object with an
    /// `operator()`. See [`type_of_a_call`]: it asked "does this callee have an `operator()`?" of a member call whose
    /// type was its *return* type, and answered the container's operator instead of the declared return.
    fn fact_kind(&self) -> crate::DeclKind {
        match self {
            // The two vocabularies are different enums (`BindingKind` is the symbol layer's), and the only
            // distinction this caller makes is "function or not": everything callable answers `Function` so that a
            // call of a *member function* is never mistaken for a call of an object with an `operator()`.
            NamedDeclaration::Here(binding) => match binding.kind {
                crate::sema::symbol::BindingKind::Function
                | crate::sema::symbol::BindingKind::Constructor
                | crate::sema::symbol::BindingKind::Destructor
                | crate::sema::symbol::BindingKind::ConversionFunction
                | crate::sema::symbol::BindingKind::OperatorFunction
                | crate::sema::symbol::BindingKind::LiteralOperator => crate::DeclKind::Function,
                _ => crate::DeclKind::Variable,
            },
            NamedDeclaration::Indexed(fact, _, _) => fact.kind,
        }
    }

    /// The type this declaration was written with.
    ///
    /// `None` for a function — `make` is not a `Widget` and has no members — which is the distinction
    /// [`DeclFact::type_of`] documents.
    fn type_of(&self, root: &cpp_parser::CppSyntaxNode, scopes: &crate::ScopeTree) -> Option<Type> {
        match self {
            // **Read from the syntax**, which is where a type is written: the specifier sequence and the
            // declarator, handed to the one reader that knows how to assemble them. For a declaration in this
            // file that is the better source by a wide margin — `const Widget* const p` is a shape with two
            // qualifier positions, and no parser of the *spelling* can put them back where the file had them.
            NamedDeclaration::Here(binding) => {
                // **A function's name has no type.** The declarator reader below assembles one from the declarator, and
                // for `shared_from_this()` that is the function type `T (*)()` — while what a call of it has is
                // [`DeclFact::returns`], which is the question a caller asks next. Measured: `auto p =
                // shared_from_this();` answered `T (*)()` for a member function this file declares.
                if matches!(
                    binding.kind,
                    crate::BindingKind::Function
                        | crate::BindingKind::Constructor
                        | crate::BindingKind::Destructor
                        | crate::BindingKind::ConversionFunction
                        | crate::BindingKind::OperatorFunction
                        | crate::BindingKind::LiteralOperator
                ) {
                    return None;
                }
                // **An enumerator's type is its enumeration.** `enum class Colour { Red };` writes no type beside `Red`,
                // so the reader below works from the *enum's* specifier sequence and cannot answer the enumerator — and
                // `auto colour = Colour::Red;` had no type at all. The enumeration is the scope the enumerator was bound
                // in, which is what its own declaration opened.
                if binding.kind == crate::BindingKind::Enumerator {
                    return scopes
                        .scope(binding.scope)
                        .and_then(|scope| scope.name.clone())
                        .map(Type::named);
                }
                let declarator =
                    crate::sema::types::declarator_declaring(root, binding.name_range)?;
                let specifiers = declarator.ancestors().find_map(|node| {
                    node.children().find(|child| {
                        CppSyntaxKind::from(child.kind()) == CppSyntaxKind::DeclSpecifierSeq
                    })
                })?;

                // *query* path only, deliberately. `struct { unsigned three : 3; } bits;` has a type with no spelling,
                // and the members live in the class scope that `build_scopes` names after this declarator, so the two
                // sides meet only if this answer uses the same key.
                //
                // The *fact* keeps the empty spelling, and that is not an oversight: a hover on a file-scope
                // `static const struct { … } priority[]` prints the declaration's own text, and naming that type
                // `priority` made the hover say `priority[] priority;` (measured: one handshake test went red). So the
                // key exists where a member question needs it and nowhere a reader reads a type.
                let written = crate::sema::types::type_of_declaration_named(
                    &specifiers,
                    Some(&declarator),
                    binding.name_range,
                    binding.name.identifier_text(),
                    // **The same rule the fact builder applies**: a variable's own parameter list is its constructor
                    // call, so the reader must not turn it into a function type. See `declared_type_of_with`.
                    matches!(binding.kind, crate::BindingKind::Variable),
                );
                // **Only inside a function body.** A file-scope `static const struct { … } priority[]` keeps the empty
                // spelling, because a reader hovering it is shown the declaration's own text — naming its type made
                // that hover print `priority[] priority;` (measured: `a_hover_names_the_instantiation_and_never_invents_a_void`
                // went red). The member questions this key exists for are all about locals.
                let keyed_by_the_declarator = scopes
                    .scope_at(binding.name_range.start_offset)
                    .is_some_and(|scope| {
                        scopes.scope_chain(scope).into_iter().any(|id| {
                            scopes
                                .scope(id)
                                .is_some_and(|data| data.kind == crate::ScopeKind::Function)
                        })
                    });
                match (
                    written.to_string().is_empty(),
                    an_unnamed_class_body(&specifiers),
                ) {
                    (true, Some(_)) if keyed_by_the_declarator => {
                        Some(Type::named(binding.name.identifier_text()?))
                    }
                    _ => Some(written),
                }
            }
            // **Read from the spelling**, which is all the index has: a fact is a `String` on disk and the file
            // it came from is not open. `parse_type_spelling` is the bridge, and `class_name` the one field of
            // it that a member query needs.
            NamedDeclaration::Indexed(fact, _, bindings) => {
                let _ = scopes;
                fact.type_of
                    .as_deref()
                    .map(|written| bindings.applied_to(&parse_type_spelling(written)))
            }
        }
    }

    /// What a **call** of this declaration has: the type it returns, or the class it declares.
    ///
    /// Two answers because C++ has two, and the tokens do not separate them: `make()` is a call of a function and
    /// has what it returns, while `Widget()` — the same shape — is a *temporary* of the class. Only the
    /// declaration says which, which is why this is asked here rather than of the shape.
    ///
    /// **The return type is finished the same way a member's type is** — [`finish_a_nested_name`], over the class
    /// the member is declared in (`DeclFact::scope`). That is the whole of how `auto y = x.back()` gets `y`'s type:
    /// this is the reader the deduction path goes through, and until it ran the walk it answered with the *name*
    /// `reference` while the other reader of the same question answered `_Elem&`. One question, one reader.
    fn what_a_call_has(
        &self,
        index: &ProjectIndex,
        declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
        scopes: &crate::ScopeTree,
        root: &cpp_parser::CppSyntaxNode,
        path: &Path,
        written_arguments: &[Type],
        argument_types: &[Type],
    ) -> Option<Type> {
        // **The template arguments the call did not write**, deduced from the types of the arguments it did.
        //
        // Writing `<size_type>` is one way to say what a function template's parameter stands for; passing an
        // argument whose type *is* that parameter is the other, and it is the one the standard library uses almost
        // everywhere: `_Get_unwrapped(_First)` never writes `<int*>`, it passes one. Until this, only the written
        // form substituted — so a deduced return that *is* the parameter came back as the parameter's **name**:
        // measured on a two-line fixture, `template <class _It> auto f(_It p) { return p; }` called as `f(a_pointer)`
        // deduced **`_It`**, which is not a missing answer but a wrong one, and worse than a refusal because it reads
        // like a type.
        //
        // The rule is C++'s own, restricted to the case this layer can be sure of: a function parameter **written as
        // exactly one template parameter** takes that parameter's place, so the argument passed there is what the
        // parameter stands for. A parameter written as `vector<_Ty> const&` needs the argument's own template-id
        // taken apart, and that is not attempted — it is a different deduction, and half of it would be a guess.
        let deduced;
        let written_arguments = if written_arguments.is_empty() && !argument_types.is_empty() {
            let (names, written_list) = self.parameters_of(index, scopes, root, path);
            deduced = deduce_the_parameters(&names, written_list.as_deref(), argument_types);
            &deduced[..]
        } else {
            written_arguments
        };

        match self {
            NamedDeclaration::Here(binding) => {
                if binding.kind == crate::BindingKind::Class {
                    return binding.name.identifier_text().map(Type::named);
                }
                // **A body that `if constexpr` decides, read again with what the call site knows.**
                //
                // `declared_returns_of` answers for a return type the file *wrote*; a function whose return type is
                // deduced has none there, and the fact is built with no call site in hand — so a body branching on a
                // template parameter has no single answer when the index is made. Here both halves exist, and the
                // body is in this very tree, so no other file has to be read: the branch whose condition holds under
                // the substitutions is the only one instantiated, and `_It + 0` becomes `int* + 0`.
                let names_for_the_call =
                    crate::sema::declarations::declared_template_parameters_of(root, binding);
                let returns = match crate::sema::declarations::declared_returns_of(root, binding)
                    .filter(|returns| !is_a_placeholder(returns))
                {
                    Some(returns) => parse_type_spelling(&returns),
                    None => {
                        let substitutions = crate::sema::types::TypeSubstitutions::new(
                            &names_for_the_call,
                            written_arguments,
                        );
                        let written = crate::sema::declarations::deduced_returns_of_substituted(
                            root,
                            binding.clone(),
                            &substitutions,
                            argument_types,
                        )?;
                        parse_type_spelling(&written)
                    }
                };

                // **The same pairing the indexed half does, for the declaration this file writes.**
                //
                // A function template declared in the buffer is a `Here` binding, and only the `Indexed` arm below
                // substituted — so `_Convert_size<size_type>(n)` in the file that declares `_Convert_size` answered
                // with the unsubstituted `_Size_type` while the identical call through a header's fact answered
                // `size_type`. One question, two answers, and the difference was which of the two arms the lookup
                // happened to land in. Measured on a fixture with both: the same-file call refused and the
                // header's call deduced.
                let names =
                    crate::sema::declarations::declared_template_parameters_of(root, binding);
                if names.is_empty() || written_arguments.is_empty() {
                    return Some(returns);
                }
                let substitutions =
                    crate::sema::types::TypeSubstitutions::new(&names, written_arguments);
                Some(returns.substituted(&substitutions))
            }
            // A **call of a member**: `v.data()` has what `data` returns, and what it returns is written with the
            // class template's parameters — so the same pairing that finishes a member's type finishes this, and
            // the same walk over the class's own member names finishes it too.
            NamedDeclaration::Indexed(fact, file, bindings) => {
                // **A fact with no return type whose body can be read again with what the call site knows.**
                //
                // `what_a_call_has_in` answers `None` for a function whose return type is deduced and whose body
                // this layer could not type when the index was built — and the index is built with **no call site**
                // in hand, so a body that branches on a template parameter has no single answer there. At the call
                // site both halves exist: the argument types say what the parameters stand for, and the declaring
                // file can be read again. So the body is typed a second time, **with the substitutions**, and that
                // is what lets `if constexpr` pick its branch: `_It + 0` becomes `int* + 0` and the two branches of
                // `_Get_unwrapped` finally agree.
                let name = fact.name.clone();
                let offset = fact.name_range.start_offset;
                let returns = match what_a_call_has_in(fact) {
                    Some(returns) => returns,
                    None => {
                        let substitutions = crate::sema::types::TypeSubstitutions::new(
                            &fact.parameters,
                            written_arguments,
                        );
                        let declared_in = declaring(file.as_path())?;
                        // **The fact's offset is a *file* offset; the tree speaks the *reading*.**
                        //
                        // `name_range` comes from the index, which records where a token sits in the file it was
                        // written in. `definition_at` walks `declared_in.root`, whose offsets are the *rendering*'s —
                        // the file with its `#include`s expanded. For a file with no macro and no include the two are
                        // the same number, which is why this looked right; through a header that includes anything they
                        // are not, and the binding found at the raw offset is a different declaration. The translation
                        // is `reading_offset_of`, and the raw offset is tried after it because a region the rendering
                        // does not contain (`#if` branch nobody takes) still has to be looked at the way it was.
                        let found = [
                            declared_in.reading_offset_of(
                                crate::file::coordinates::FileOffset::new(offset),
                            ),
                            Some(crate::file::coordinates::ReadingOffset::new(offset)),
                        ]
                        .into_iter()
                        .flatten()
                        .find_map(|in_the_reading| {
                            match crate::sema::resolve::definition_at(
                                &declared_in.scopes,
                                &declared_in.root,
                                in_the_reading.get(),
                            ) {
                                // **The name has to be the one the fact named.** A matched offset in the wrong
                                // coordinates lands on a neighbouring declaration, and deducing *its* body would be a
                                // wrong answer that reads like a right one.
                                Known::Yes(found)
                                    if found.name.identifier_text() == Some(name.as_str()) =>
                                {
                                    Some(found)
                                }
                                _ => None,
                            }
                        });
                        let binding = found?;
                        let written = crate::sema::declarations::deduced_returns_of_substituted(
                            &declared_in.root,
                            binding,
                            &substitutions,
                            argument_types,
                        )?;
                        parse_type_spelling(&written)
                    }
                };
                let _ = &name;
                // **The class's arguments first, then the function's.** Both substitute into the same spelling and
                // they are written with disjoint names - the class's _Elem and the function's _Size_type in
                // asic_string<char>::_Convert_size<size_t> - so the order does not decide the answer; it decides
                // which name is left standing when the two lists overlap, and the function's is the nearer.
                let started = bindings.applied_to(&returns);
                let started = if fact.parameters.is_empty() || written_arguments.is_empty() {
                    started
                } else {
                    // **Written with names nobody had recorded until now.** _Convert_size returns _Size_type`r
                    // and is called _Convert_size<size_type>(_Length): the argument list is right there in the
                    // callee, the parameter names are in the fact, and the whole of the answer is the pairing - the
                    // same positional substitution a member's type already goes through. Measured on
                    // <vector>/<xutility>: 11 uto refusals were exactly this call, every one of them a return
                    // type that had been read and left unpaired.
                    let substitutions = crate::sema::types::TypeSubstitutions::new(
                        &fact.parameters,
                        written_arguments,
                    );
                    started.substituted(&substitutions)
                };

                // **An injected-class-name stands for the class with its own arguments.** `std::string::substr` returns
                // `basic_string` — the name a class uses for *itself* inside its own body — and a reader needs the
                // instantiation, not the bare name: measured, `auto cut = text.substr(1, 2);` answered `basic_string`
                // where `std::string` is the type. The arguments are the ones the receiver was used with, which is what
                // `bindings` holds.
                let started = match started.class_name() {
                    Some(name)
                        if started.arguments().is_empty()
                            && !bindings.arguments().is_empty()
                            && fact
                                .scope
                                .as_deref()
                                .is_some_and(|scope| scope.rsplit("::").next() == Some(name)) =>
                    {
                        let arguments: Vec<String> = bindings
                            .arguments()
                            .iter()
                            .map(|argument| argument.to_string())
                            .collect();
                        crate::sema::types::parse_type_spelling(&format!(
                            "{name}<{}>",
                            arguments.join(", ")
                        ))
                    }
                    _ => started,
                };

                let Some(class) = fact.scope.as_deref() else {
                    // A free function: there is no class whose members could name its return type. An alias at
                    // file scope (`using size_type = size_t;` and a function returning `size_type`) is resolved by
                    // the caller that has the file's aliases, not here.
                    return Some(started);
                };
                let (finished, _) = finish_a_nested_name(
                    index,
                    scopes,
                    root,
                    path,
                    class,
                    bindings,
                    started,
                    file.clone(),
                    vec![fact.name.clone()],
                );

                Some(finished)
            }
        }
    }

    /// **What a call of this declaration may leave for the call site to say** — its template parameter names, and the
    /// parameter list as the declaration wrote it.
    ///
    /// Both halves are needed by the deduction [`what_a_call_has`] does, and neither is enough alone: the names say
    /// *which* words are placeholders, and the written list says *where* they stand among the function's parameters.
    /// A declaration that is not a template answers with no names, which is the ordinary case and costs nothing.
    fn parameters_of(
        &self,
        index: &ProjectIndex,
        _scopes: &crate::ScopeTree,
        root: &cpp_parser::CppSyntaxNode,
        _path: &Path,
    ) -> (Vec<String>, Option<String>) {
        let _ = index;
        match self {
            NamedDeclaration::Here(binding) => (
                crate::sema::declarations::declared_template_parameters_of(root, binding),
                crate::sema::declarations::parameter_list_at(root, binding.name_range.start_offset),
            ),
            NamedDeclaration::Indexed(fact, _, _) => {
                (fact.parameters.clone(), fact.parameter_list.clone())
            }
        }
    }

    /// **What each of those parameters defaults to**, in the same order, `""` for none — the other half of
    /// [`NamedDeclaration::parameters_of`], and what a use that writes *fewer* arguments needs.
    ///
    /// `template <class T, class U = T> constexpr U twice = U(2);` used as `twice<float>` writes one argument for two
    /// parameters: `U`'s meaning is `T`'s, which the use wrote as `float`. Without this the answer is the parameter's
    /// own name — see `substituted_at_the_use`.
    fn parameter_defaults_of(
        &self,
        _index: &ProjectIndex,
        root: &cpp_parser::CppSyntaxNode,
    ) -> Vec<String> {
        match self {
            NamedDeclaration::Here(binding) => {
                crate::sema::declarations::declared_parameter_defaults_of(root, binding)
            }
            NamedDeclaration::Indexed(fact, _, _) => fact.parameter_defaults.clone(),
        }
    }
    ///
    /// A name range rather than the declaration's range, because the two answer different questions: a rename
    /// edits the name, and a caller looking for the declaration's own declarator has to be *at* the name — see
    /// [`callee_of_a_call`].
    fn name_offset(&self) -> usize {
        match self {
            NamedDeclaration::Here(binding) => binding.name_range.start_offset,
            NamedDeclaration::Indexed(fact, _, _) => fact.name_range.start_offset,
        }
    }

    /// **The declaration's parameter list, as its fact holds it** — `(const char* __format, ...)`.
    ///
    /// `None` for a binding in the file being edited, whose list is read from the tree the caller
    /// already has.
    fn parameter_list(&self) -> Option<String> {
        match self {
            NamedDeclaration::Here(_) => None,
            NamedDeclaration::Indexed(fact, _, _) => fact.parameter_list.clone(),
        }
    }
}

/// **A type that is still a member's name is followed to what that member declares** — one step at a time, with
/// the class's own template pairing applied at each one.
///
/// # Why it exists, and why it is one function
///
/// `_Ty& reference; reference front;` is how the standard library writes almost every type it has: the type of
/// `front` is the *name* `reference`, which mentions no parameter at all, so substituting the arguments into it
/// replaces nothing. The step that finishes it is a member lookup — `reference` in the same class, with the same
/// pairing — and the walk repeats while the type is still a name.
///
/// Measured, in MSVC's `<xstring>`: `back()` returns `reference`, which is `value_type&`, which is `_Elem&`, which
/// is `char&` for a `std::string`. **Two callers need this** — the member read as a value (`v.front`) and the
/// member *called* (`v.back()`) — and they had it twice with different answers: the second one skipped the walk
/// entirely, so `auto y = x.back()` recorded the *name* `reference` as `y`'s type. It is one function now, which
/// is this crate's rule for a question with two readers.
///
/// # What it looks up, and where it stops
///
/// The name looked up is the type's **base** rather than its whole spelling ([`Type::class_name`], to which a
/// reference is transparent): `value_type&` is a reference to the member alias `value_type`, and it is the alias
/// that has to be followed. A pointer is where the walk stops, because following one is a *decay* — a decision
/// about the expression rather than about the declaration, and the caller's to make.
///
/// The operators stay where they are written ([`Type::replacing`]): `value_type&` with `value_type` = `_Ty*` is
/// `_Ty*&`, and dropping either would answer a different type.
///
/// The walk is bounded by [`MAX_NESTED_TYPE_DEPTH`] rather than by an argument about termination: each step asks
/// about a *different* name and a class has finitely many members, but two members can name each other (`a b; b a;`
/// is not valid C++ and *is* writable text), and a walk that trusted validity would not terminate on the file a
/// language server has to survive.
#[allow(clippy::too_many_arguments)]
fn finish_a_nested_name(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    class: &str,
    bindings: &crate::sema::types::TypeBindings,
    mut current: Type,
    mut current_file: PathBuf,
    mut asked: Vec<String>,
) -> (Type, PathBuf) {
    for _ in 0..MAX_NESTED_TYPE_DEPTH {
        // **The class *with* the arguments the use wrote.** A return type's qualifier may name the class's own
        // parameters — `_Tree::find` answers `_Mybase::iterator`, and `_Mybase` is `_Tree<_Tmap_traits<_Kty, _Ty, …>>` —
        // and only the arguments turn those into types. The pairing arrives here as `bindings` (the object's type produced
        // it), so every caller of this walk gets the benefit: measured on a real project, without it the chain stopped at
        // `conditional<_Test, _Ty1, _Ty2>::type`.
        let class_with_arguments = if bindings.is_empty() || class.contains('<') {
            class.to_string()
        } else {
            let arguments: Vec<String> = bindings
                .arguments()
                .iter()
                .map(|argument| argument.to_string())
                .collect();
            format!("{class}<{}>", arguments.join(", "))
        };
        let class = class_with_arguments.as_str();
        // **A *qualified* name of the class's own aliases is followed here first.** `_Tree::find` is declared
        // `_Mybase::iterator find(...)` — a member alias of the very class the function belongs to — and the loop below
        // reads one *bare* name at a time, so this spelling was carried out unchanged and every later step asked about
        // a class called `_Mybase::iterator` (measured on a real project: `LuaReserved.find(text)` typed as exactly
        // that). The alias walk resolves it in the class's own scope, which is the same step a member's type goes
        // through.
        let spelling = current.to_string();
        if spelling.contains("::") && !asked.contains(&spelling) {
            let resolved = a_spelling_through_the_aliases(
                index,
                scopes,
                root,
                path,
                &crate::sema::types::parse_type_spelling(class),
                &spelling,
                MAX_ALIAS_HOPS,
            );
            if resolved != spelling {
                asked.push(spelling);
                current = bindings.applied_to(&crate::sema::types::parse_type_spelling(&resolved));
                continue;
            }
        }

        let Some(nested) = current.class_name().map(str::to_string) else {
            break;
        };
        if !writes_a_name(&nested) || asked.contains(&nested) {
            break;
        }
        asked.push(nested.clone());

        // **A nested name whose head is another class.** `std::shared_ptr`'s `element_type` is
        // `typename __shared_ptr<_Tp>::element_type`: the alias is the **base's**, and the head of the spelling names the
        // base. Asking the outer class for a member spelled `__shared_ptr<Resource>::element_type` finds nothing, and the
        // walk stopped right there — measured on `test_cpp`'s `smart_pointers.cpp`, where `locked->identifier()` answered
        // "`shared_ptr<Resource>` has no member `identifier`" for a `shared_ptr<Resource>` that has one.
        //
        // The step is the same question [`the_pointee_of_a_handle`] asks, so it is the same `member_fact` call: the head
        // resolved in the enclosing scopes (a base name is not a member, so `resolve_aliases` is the reader that knows how
        // it is written) and the tail looked up in it, with the head's own arguments as the pairing.
        let found = match member_fact(index, scopes, root, path, class, &nested, None) {
            Known::Yes(found) => Known::Yes(found),
            miss => match the_head_and_the_member_of(&nested) {
                Some((head, tail)) => {
                    let head = resolve_aliases(index, scopes, root, path, head).to_string();
                    let arguments: Vec<String> = parse_type_spelling(&head)
                        .arguments()
                        .iter()
                        .map(|argument| argument.to_string())
                        .collect();
                    match member_fact(
                        index,
                        scopes,
                        root,
                        path,
                        &head,
                        tail,
                        (!arguments.is_empty()).then_some(&arguments),
                    ) {
                        Known::Yes(found) => Known::Yes(found),
                        _ => miss,
                    }
                }
                None => miss,
            },
        };
        let Known::Yes((inner, inner_file)) = found else {
            break;
        };
        let Some(inner_type) = inner.type_of.as_deref() else {
            break;
        };

        let resolved = bindings.applied_to(&parse_type_spelling(inner_type));
        current = current.replacing(&nested, &resolved);
        current_file = inner_file;
    }

    (current, current_file)
}

/// **Split `A<B>::C` into its head and its last member** — `("A<B>", "C")` — at the last `::` outside angle brackets.
///
/// `None` when there is no `::` to split at, or when either half would be empty. The head keeps its arguments: a base
/// written `__shared_ptr<_Tp>` is looked up by the name `__shared_ptr` and substituted by `_Tp`'s argument, and the two
/// halves are what the caller passes on.
fn the_head_and_the_member_of(nested: &str) -> Option<(&str, &str)> {
    let mut depth = 0usize;
    let mut boundary = None;
    let bytes = nested.as_bytes();
    let mut at = 0usize;
    while at + 1 < bytes.len() {
        match bytes[at] {
            b'<' => depth += 1,
            b'>' => depth = depth.saturating_sub(1),
            b':' if depth == 0 && bytes[at + 1] == b':' => {
                boundary = Some(at);
                at += 1;
            }
            _ => {}
        }
        at += 1;
    }
    let boundary = boundary?;
    let head = nested[..boundary].trim();
    let tail = nested[boundary + 2..].trim();
    (!head.is_empty() && !tail.is_empty()).then_some((head, tail))
}

/// **A declaration's type finished when it is an alias template applied to arguments.**
///
/// `enable_if_t<__is_same(int, int), double> when_the_same;` records the *spelling*, and what it stands for is
/// `typename enable_if<__is_same(int, int), double>::type` — a member of a class template applied to arguments. The
/// two steps are the ones the member arm already takes ([`the_alias_behind`] for the alias, then the member lookup,
/// which pairs the use's arguments with the class's parameters by pattern): this is the same pair, applied to the one
/// place they were missing.
///
/// `None` for every ordinary declaration — a spelling with no `<` is not an alias template, and that is the cheap
/// question this asks first.
fn a_trait_alias_resolved(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    named: &NamedDeclaration,
    written: &Type,
) -> Option<Type> {
    let spelling = written.to_string();
    if !spelling.contains('<') {
        return None;
    }
    let (class, member) = the_alias_behind(index, &named.file(path), &spelling)?;
    let Known::Yes((fact, _)) = member_fact(index, scopes, root, path, &class, &member, None)
    else {
        return None;
    };
    let target = fact.type_of.as_deref()?;
    let arguments: Vec<String> = crate::sema::types::parse_type_spelling(&class)
        .arguments()
        .iter()
        .map(|one| one.to_string())
        .collect();
    let bare = crate::sema::types::parse_type_spelling(&class);
    let class_name = bare.class_name()?;
    let parameters = index.template_parameters_for(class_name, path, &arguments);
    let defaults = index.template_parameter_defaults_for(class_name, path, &arguments);
    let resolved = crate::sema::types::substituted_spelling_with_defaults(
        target,
        &parameters,
        &defaults,
        &arguments,
    );
    Some(crate::sema::types::parse_type_spelling(&resolved))
}
/// The type a declaration was written with — or, where it wrote `auto`, the type its **initializer** has.
///
/// # What `auto` means here
///
/// `auto n = count();` declares `n` with the type of `count()`, and until this existed the answer to "what is `n`"
/// was the word `auto` — which is not a type, and which every consumer then had to special-case or give up on:
/// `auto w = Widget{}; w.` listed nothing, hover said `auto`, and the parameter hints could not say what an
/// argument was. The deduction is the language's own rule read off the declaration the file wrote:
///
/// ```text
/// auto n = count();          the initializer's type                          `int`
/// const auto& r = n;         that type with what was written around `auto`    `const int&`
/// auto p = &r;               the initializer is `&r`, so `const int*`         `const int*`
/// auto q = Widget{};         a braced initializer names the type it makes     `Widget`
/// ```
///
/// # What it refuses, and why that is the rule rather than a shortcut
///
/// * **`auto&&`** — the language deduces a reference *or* a value depending on the initializer's value category
///   (`T&` for an lvalue, `T&&` for an rvalue), and nothing in a declaration's spelling says which. Reporting what
///   was written around `auto` would be wrong half the time, so the answer is `Unknown`.
/// * **a `*` the initializer does not have** — `auto* p = x;` where `x` is not a pointer is ill-formed; a type
///   invented to make the declaration work would hide that.
/// * **a declaration in another file** — `auto` at namespace scope in a header is deduced from that header's
///   syntax, and this layer holds one file's tree. The spelling in the index (`auto`) is not a type, so the answer
///   is `Unknown` rather than a guess.
/// * **a chain longer than [`MAX_TYPE_DEPTH`]** — see the guard in [`type_of_expression`].
fn declared_type(
    memo: &TypeMemo,
    index: &ProjectIndex,
    declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    named: &NamedDeclaration,
    depth: usize,
) -> Known<Type> {
    // **An enumerator's type is its enumeration** — the *indexed* half of the rule `NamedDeclaration::type_of` carries for
    // a declaration in this file. `enum class Colour { Red };` writes no type beside `Red`, so the fact records
    // `type_of: None` and this answered nothing: measured, `auto colour = Colour::Red;` in a `.cpp` whose enum is in the
    // header had no type at all, while the same declaration in one file worked.
    if let NamedDeclaration::Indexed(fact, _, _) = named
        && fact.type_of.is_none()
        // **An enumerator only.** `DeclKind` has no enumerator — it is a `Variable` in the enum's scope — and a
        // *function* has the same (`type_of: None`, scope = a class). Without this guard `shared_from_this` declared in
        // `Base` answered the type `Base`, which is the class it is a member of, not what it is.
        && fact.kind == crate::DeclKind::Variable
        && let Some(scope) = fact.scope.as_deref()
        && let Known::Yes(enclosing) = index.definition(scope, path)
        && enclosing.fact.kind == crate::DeclKind::Type
    {
        return Known::Yes(Type::named(scope));
    }

    let declaration = named.type_of(root, scopes);
    let Some(declaration) = declaration else {
        return Known::No;
    };

    // **The declaration reads its own type**, and the only case left over is the placeholder: for anything else
    // the shape the reader built *is* the answer, qualifiers and operators and all.
    //
    // **An alias's name is not an intermediate to be substituted away here.** The obvious next step — seeing
    // `reference`, asking what it aliases, and answering `_Elem&` — was tried and is **wrong at this layer**: it
    // broke three tests that had been passing, because `basic_string<char>::reference` is a *member looked up by
    // that name*, and the class's own arguments are substituted into the target only once the lookup has found it.
    // Measured: `a_member_of_a_class_reached_through_an_alias_gets_the_aliass_arguments` expects `char&` and got
    // `_Elem&`, because the substitution had already consumed the name the lookup needed. See [`alias_target`] for
    // the step that is right here — an alias *declared in this file* has a target this can read directly — and the
    // note on [`the_alias_behind`] for where the other step belongs.

    let placeholder = declaration.to_string();
    // **C++17's *implicit* deduction guide** — `Box box(7);` where `Box` is a class template.
    //
    // The syntax reader answers the template's **name**, which is a type with an argument missing: `Box` is not
    // `Box<int>`, and a member query on it finds nothing because no declaration is called that. The language's rule for
    // this shape is the constructor's parameter list, and only that shape is deduced here — one template parameter, and
    // a constructor whose first parameter *is* that parameter. Anything else answers the name it wrote, because a
    // guessed argument would print an instantiation the reader never asked for.
    //
    // Measured on a C++20 project (`techniques.h` + `techniques.cpp`): `techniques::Box box(7)` typed as
    // `techniques::Box` while `techniques::Box<int> box(7)` typed correctly, so what was missing was the deduction
    // rather than the template.
    if let crate::sema::types::Type::Named { name, arguments } = &declaration
        && arguments.is_empty()
        && !name.contains('<')
    {
        // **The braced initialiser's elements are the constructor's arguments.** `std::pair pair{1, 2}` is a
        // `pair<int, int>` by the same C++17 rule the next block applies to `Box box(7)`, and the elements are where the
        // arguments are: the `initializer_type` below answers the *list's* type, which is a `std::initializer_list` this
        // layer deliberately does not invent.
        if let Some(initialisation) = the_braced_initialiser_of(root, named) {
            let elements: Vec<cpp_parser::CppSyntaxNode> = initialisation.children().collect();
            if let Some(with_arguments) = the_arguments_a_braced_initialisation_deduces(
                memo,
                index,
                declaring,
                scopes,
                root,
                path,
                &elements,
                name,
                depth + 1,
            ) {
                return Known::Yes(with_arguments);
            }
        }
        if let Known::Yes((from_the_initializer, _)) =
            initializer_type(memo, index, declaring, scopes, root, path, named, depth + 1)
            && let Some(with_arguments) = deduced_class_template_arguments(
                index,
                scopes,
                root,
                path,
                declaring,
                name,
                &from_the_initializer,
            )
        {
            return Known::Yes(crate::sema::types::parse_type_spelling(&with_arguments));
        }
    }

    // **A `typeof`/`__typeof__` specifier whose payload is an *expression*** — `typeof(value) copy = value;` — is
    // the type of that expression, and only the semantic layer can answer it: the reader of the *syntax* hands back
    // the spelling, `typeof(value)`, which no scope and no member list has heard of. The fact builder has the same
    // gap, so a summary records the spelling too.
    if let Some(payload) = a_typeof_payload(root, named)
        && let Known::Yes((type_of, _)) = type_of_expression(
            index,
            &mut |_: &Path| None,
            scopes,
            root,
            path,
            &payload,
            depth + 1,
        )
    {
        return Known::Yes(type_of);
    }
    if !writes_auto(&placeholder) {
        return Known::Yes(declaration);
    }

    let unknown = || Known::Unknown(UnknownReason::UnknownType(Box::from(placeholder.clone())));

    // The **written** spelling, with the qualifiers the reader drops: `const auto& r = x;` has to deduce a `const`
    // type, and `Type` models no qualifiers — so the spelling is carried beside the shape rather than inside it.
    // See `deduction_inputs`, which is the one place that reads a declaration's text for this reason.
    // **A range-based `for` head** — `for (auto x : range)`: the type is the range's **element**, not the range,
    // and there is no initializer for `deduction_inputs` to find. This is the ordinary spelling of a loop over a
    // container, and without it every such variable had no type: hovering `x` in `for (auto x : v)` answered "a
    // variable, declared in a function body" and nothing else, and `it->first` in `for (auto it : map)` could not
    // be resolved. See [`range_for_element_type`].
    if let Some(element) =
        range_for_element_type(memo, index, declaring, scopes, root, path, named, depth)
    {
        return element;
    }

    let Some((as_written, initializer)) = deduction_inputs(root, named) else {
        return unknown();
    };

    // **The walk's own reason, rather than the placeholder again.** The initializer walk knows *which* expression it
    // could not type — `UnknownType("_Mypair._Myval2")` — and returning `UnknownType("auto")` in its place threw that
    // away: every refusal in a standard-library header read as the same four characters, and a reader could not tell
    // "the initializer is not there" from "the initializer is there and its third subexpression is a template
    // parameter". Measured on eight headers: 294 refusals, **246 of them reported as `UnknownType("auto")`** — a
    // payload that answers no question, and one that hid the real reason from a probe written to find it.
    //
    // `Known::No` still means the walk declined to take the question at all, which is what the placeholder reason is
    // for; only a walk that *tried and failed* has a better answer to give.
    let deduced =
        match initializer_type(memo, index, declaring, scopes, root, path, named, depth + 1) {
            Known::Yes((deduced, _)) => deduced,
            Known::Unknown(reason) => return Known::Unknown(reason),
            Known::No => return unknown(),
        };

    match auto_substituted(&as_written, &deduced, an_lvalue(&initializer)) {
        Some(type_of) => Known::Yes(parse_type_spelling(&type_of)),
        None => unknown(),
    }
}

/// **Is this initializer an lvalue?** — the one thing `auto&&` collapsing needs that a *type* cannot say.
///
/// `auto&& bound = base;` and `auto&& bound = 42;` deduce two different references, and both initializers type as
/// `int`: the difference is the expression's **value category**, not its type. The categories this layer can decide
/// from the shape are the ones that are decided by it — a name, a member of one, a dereference and a subscript are
/// lvalues; a literal, an object construction and a call that does not return a reference are not. A call *returning*
/// `T&` says so in its deduced type, which the caller has already put in hand.
fn an_lvalue(expression: &cpp_parser::CppSyntaxNode) -> bool {
    use cpp_parser::CppSyntaxKind::{CallExpr, InitListExpr, LiteralExpr, NewExpr, ParenExpr};
    // **Everything is an lvalue except what is definitely a prvalue.** A negative list rather than a positive one
    // because the grammar reaches a name in four ways (`IdentifierExpr`, `NameExpr`, `RefExpr`, and a member's own
    // node) and a positive list is a list to get wrong: measured, `auto&& bound = base;` answered `int&&` with the
    // identifier's kind missing from it.
    let kind = cpp_parser::CppSyntaxKind::from(expression.kind());
    if matches!(kind, LiteralExpr | CallExpr | InitListExpr | NewExpr) {
        return false;
    }
    // A parenthesised initializer keeps its inner expression's category.
    if kind == ParenExpr
        && let Some(inner) = expression.children().next()
    {
        return an_lvalue(&inner);
    }
    // Anything else — a name in any of its four shapes, a member, a dereference, a subscript — is an lvalue, which is
    // the safe direction here: a wrong `&` is still a reference to the right class, while a wrong `&&` names no class
    // at all.
    true
}

/// **Where the other half of the alias step belongs, and why it is not here.**
///
/// An `auto` whose initializer is a name of an alias type deduces that alias's **spelling** — `auto a = q;` where
/// `q` is a `pointer` answers `pointer`. Following it to the target (`int*`, or in the standard library
/// `typename _Alty_traits::pointer`) looks like the obvious completion of [`alias_target`], and it was written,
/// measured and **removed**:
///
/// * it moved the standard library's own count by **one** declaration in 631 — 130 deduced to 131 — because the
///   targets there are template-dependent names this cannot resolve anyway; and
/// * it **broke three tests** that had been passing, all of them about aliases, because substituting at this layer
///   destroys the alias *name* that a member lookup needs: `basic_string<char>::reference` is a member found by
///   that name, and the class's arguments are substituted into the target only after the lookup has found it.
///   Measured: `a_member_of_a_class_reached_through_an_alias_gets_the_aliass_arguments` wants `char&` and got
///   `_Elem&`.
///
/// The step belongs where a type's **shape** is wanted and its name is not — the operator and member queries — and
/// it belongs there with the class's arguments in hand, which is the generic instantiation this analysis does not
/// yet do. Recorded here rather than in a plan: the next reader of `alias_target` is the reader who will try it.
///
/// Does this spelling use the `auto` placeholder? A word, not a substring: `automatic` is a name.
fn writes_auto(written: &str) -> bool {
    written
        .split(|character: char| !character.is_alphanumeric() && character != '_')
        // **`__auto_type` is GNU's spelling of the same placeholder**, and it is one *word* here, so comparing against
        // `auto` alone missed it: `__auto_type value = 41;` had a fact typed `int` — the fact builder deducts — while
        // `type_at(value)` answered `__auto_type`, because this predicate is what decides whether the deduction is
        // asked for at all. Measured on a nine-file C corpus, and pinned by
        // `gnu_auto_type_is_deduced_from_its_initializer`.
        .any(|word| word == "auto" || word == "__auto_type")
}

/// **The element type of the range a `for` head binds** — `for (auto x : v)` answers `int` for a `vector<int>`.
///
/// `None` when the declaration is not a range-based `for`'s, which is the ordinary case. The head is the one shape
/// whose declared variable has **no initializer**: `auto x = v[0]` has one and goes through [`initializer_type`],
/// while `for (auto x : v)` states the range in the loop's own syntax.
fn range_for_element_type(
    memo: &TypeMemo,
    index: &ProjectIndex,
    declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    named: &NamedDeclaration,
    depth: usize,
) -> Option<Known<Type>> {
    let NamedDeclaration::Here(binding) = named else {
        return None;
    };

    let declared_at = binding.name_range.start_offset;
    let loop_node = cpp_parser::token_at(root, declared_at)?
        .parent_ancestors()
        .find(|node| {
            cpp_parser::CppSyntaxKind::from(node.kind()) == cpp_parser::CppSyntaxKind::RangeForStat
        })?;

    let range = range_expression_of_the_pattern(&loop_node)?;

    // **A range built out of adaptors has its element computed from the expression**, because the view it makes has no
    // name this layer can spell: `numbers | std::views::filter(f) | std::views::take(2)` yields `int` even though no
    // declaration says so. See [`element_of_a_range_expression`].
    if let Some(element) = element_of_a_range_expression(
        memo,
        index,
        declaring,
        scopes,
        root,
        path,
        &range,
        depth + 1,
    ) {
        return Some(element.map(|(type_of, _)| type_of));
    }

    let Known::Yes((container, _)) = type_of_expression_memoed(
        memo,
        index,
        declaring,
        scopes,
        root,
        path,
        &range,
        depth + 1,
    ) else {
        return Some(Known::Unknown(UnknownReason::UnknownType(Box::from(
            "auto",
        ))));
    };

    Some(match range_element_of(&container) {
        Some(element) => Known::Yes(crate::sema::types::parse_type_spelling(&element)),
        None => Known::Unknown(UnknownReason::UnknownType(Box::from(container.to_string()))),
    })
}

/// **The element a range expression yields, when the expression *builds* the range.**
///
/// The named-container case above is one half; this is the other, and it is what C++20 ranges are written with:
///
/// ```text
/// numbers | std::views::filter(f) | std::views::take(2)   the element of `numbers`
/// map | std::views::keys                                  the key of the map's pair
/// map | std::views::values                                its value
/// rows | std::views::join                                 the element of the inner range
/// std::views::iota(1, 6)                                  the type of `1`
/// std::ranges::subrange(begin, end)                       the element of the range `begin` came from
/// ```
///
/// A view has no name this layer can spell — its type is a class template over a closure type — so the question is asked of
/// the **expression** and never of a `Type`: the left operand says the element, and each adaptor is a function on it. An
/// adaptor that changes the element through a body (`transform`'s lambda) is refused: reading a `return` there needs the
/// same deduction a function body does, and a guess would offer the wrong members in the loop.
///
/// `None` when the expression is not one of these shapes — the caller falls back to typing it as a value.
fn element_of_a_range_expression(
    memo: &TypeMemo,
    index: &ProjectIndex,
    declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    expression: &cpp_parser::CppSyntaxNode,
    depth: usize,
) -> Option<Known<(Type, PathBuf)>> {
    // **A pipe chain**: the element of the left, adapted by the right.
    if let Some((left, right)) = the_two_operands_of_a_pipe(expression)
        && let Some(left_element) = element_of_a_range_expression(
            memo,
            index,
            declaring,
            scopes,
            root,
            path,
            &left,
            depth + 1,
        )
    {
        return Some(adapted_element(&left_element, &right, index, path));
    }

    // **The base case: a range expression that is a value.** `numbers`, `collection`, a function call returning a
    // container — the element is the one its type yields, which is the path named containers already took. It has to be
    // here and not only in the caller, because the pipe case recurses to a value.
    if CppSyntaxKind::from(expression.kind()) != CppSyntaxKind::BinaryExpr
        && a_call_to_a_function(expression).is_none()
        && let Known::Yes((container, file)) = type_of_expression_memoed(
            memo,
            index,
            declaring,
            scopes,
            root,
            path,
            expression,
            depth + 1,
        )
        && let Some(element) = range_element_of(&container)
    {
        return Some(Known::Yes((
            crate::sema::types::parse_type_spelling(&element),
            file,
        )));
    }

    // **`std::views::iota(1, 6)`** — a counted range of the first argument's type.
    if let Some(callee) = a_call_to_a_function(expression) {
        let written = callee.text().to_string();
        let written = written.trim();
        let name = written.rsplit("::").next().unwrap_or(written);
        if name == "iota" {
            let arguments = crate::inlay::arguments_of(expression).unwrap_or_default();
            let first = arguments.first()?;
            return Some(
                match type_of_expression_memoed(
                    memo,
                    index,
                    declaring,
                    scopes,
                    root,
                    path,
                    first,
                    depth + 1,
                ) {
                    Known::Yes((type_of, file)) => Known::Yes((type_of, file)),
                    _ => Known::Unknown(UnknownReason::UnknownType(Box::from("std::views::iota"))),
                },
            );
        }
        // **`std::ranges::subrange(begin, end)`** — the element of the range a `begin()` came from.
        if name == "subrange" {
            let arguments = crate::inlay::arguments_of(expression).unwrap_or_default();
            let first = arguments.first()?;
            if let Some(element) = element_of_an_iterator_expression(
                memo,
                index,
                declaring,
                scopes,
                root,
                path,
                first,
                depth + 1,
            ) {
                return Some(element);
            }
        }
    }

    None
}

/// **The two operands of `a | b`**, when the expression is one.
///
/// The operator is a **token** between two nodes, so the two children are the operands — the same shape every
/// `BinaryExpr` has.
fn the_two_operands_of_a_pipe(
    expression: &cpp_parser::CppSyntaxNode,
) -> Option<(cpp_parser::CppSyntaxNode, cpp_parser::CppSyntaxNode)> {
    if CppSyntaxKind::from(expression.kind()) != CppSyntaxKind::BinaryExpr {
        return None;
    }
    let is_a_pipe = expression
        .children_with_tokens()
        .filter_map(|element| element.into_token())
        .any(|token| token.text() == "|");
    if !is_a_pipe {
        return None;
    }
    let mut operands = expression.children();
    let left = operands.next()?;
    let right = operands.next()?;
    Some((left, right))
}

/// **The element a view adaptor yields from `element`** — the right-hand side of a pipe, applied.
fn adapted_element(
    element: &Known<(Type, PathBuf)>,
    adaptor: &cpp_parser::CppSyntaxNode,
    index: &ProjectIndex,
    path: &Path,
) -> Known<(Type, PathBuf)> {
    let Known::Yes((element, file)) = element else {
        return element.clone();
    };
    let written = adaptor.text().to_string();
    let written = written.trim();
    let _ = (index, path);

    // **`transform`'s element is the lambda's return type.** It used to be refused — the body is where the answer is, and
    // a guess would offer the wrong members — but the deduction for a lambda's `return` exists
    // (`a_lambdas_return_type`, which a call of the lambda uses), so this is the same answer rather than a guess. A body
    // this layer cannot type (`return ++counter;`) still answers nothing.
    if written.contains("views::transform") || written.contains("views::transform_view") {
        let lambda = adaptor
            .descendants()
            .find(|child| CppSyntaxKind::from(child.kind()) == CppSyntaxKind::LambdaExpr);
        return match lambda
            .and_then(|lambda| crate::sema::declarations::a_lambdas_return_type(&lambda, &[]))
        {
            Some(label) => Known::Yes((
                crate::sema::types::parse_type_spelling(&label),
                file.clone(),
            )),
            None => Known::Unknown(UnknownReason::UnknownType(Box::from(
                "std::views::transform",
            ))),
        };
    }

    // **`keys` / `values`** are the two halves of the left element's `pair` — `map | std::views::keys` yields `K`.
    if written.contains("views::keys") {
        return match pair_component(element, 0) {
            Some(component) => Known::Yes((component, file.clone())),
            None => Known::Unknown(UnknownReason::UnknownType(Box::from("std::views::keys"))),
        };
    }
    if written.contains("views::values") {
        return match pair_component(element, 1) {
            Some(component) => Known::Yes((component, file.clone())),
            None => Known::Unknown(UnknownReason::UnknownType(Box::from("std::views::values"))),
        };
    }

    // **`join`** flattens a range of ranges: the element of the element.
    if written.contains("views::join") {
        return match element_of_the_element(element) {
            Some(inner) => Known::Yes((inner, file.clone())),
            None => Known::Unknown(UnknownReason::UnknownType(Box::from("std::views::join"))),
        };
    }

    // **Every other adaptor passes the element through**: `filter`, `reverse`, `take`, `drop`, `take_while`,
    // `drop_while`, `filter_view`, `reverse_view`, `take_view`, `drop_view`, `common`, `all`, `counted`, `elements`…
    Known::Yes((element.clone(), file.clone()))
}

/// **One component of a `pair`-shaped type**, without the `const` a map's key carries.
fn pair_component(element: &Type, position: usize) -> Option<Type> {
    let Type::Named { name, arguments } = element else {
        return None;
    };
    let plain = name.rsplit("::").next().unwrap_or(name);
    if plain != "pair" && plain != "tuple" {
        return None;
    }
    let component = arguments.get(position)?.clone();
    Some(strip_a_leading_const(&component))
}

/// The same type without a leading `const` — `keys` yields the key, and the key of a `map` is `const K` **in the pair**,
/// not in the view's element.
fn strip_a_leading_const(type_of: &Type) -> Type {
    let written = type_of.to_string();
    match written.strip_prefix("const ") {
        Some(rest) => crate::sema::types::parse_type_spelling(rest),
        None => type_of.clone(),
    }
}

/// **The element of the element** — `join`'s rule, for the shapes this layer can read.
fn element_of_the_element(element: &Type) -> Option<Type> {
    let written = element_of(element, 0)?;
    Some(crate::sema::types::parse_type_spelling(&written))
}

/// **The element of the range an iterator expression came from** — `numbers.begin()`, `numbers.begin() + 3`.
///
/// The iterator's own type is a class template this layer cannot read; the range whose `begin()` produced it is written in
/// the expression, and its element is the answer.
fn element_of_an_iterator_expression(
    memo: &TypeMemo,
    index: &ProjectIndex,
    declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    expression: &cpp_parser::CppSyntaxNode,
    depth: usize,
) -> Option<Known<(Type, PathBuf)>> {
    // `v.begin()` / `v.end()` — a member call whose object is the range.
    if let Some(access) = crate::sema::resolve::member_access_of(expression) {
        let written = access.member.clone();
        if written == "begin" || written.ends_with(".begin") {
            let Known::Yes((container, file)) = type_of_expression_memoed(
                memo,
                index,
                declaring,
                scopes,
                root,
                path,
                &access.object,
                depth + 1,
            ) else {
                return None;
            };
            let element = range_element_of(&container)?;
            return Some(Known::Yes((
                crate::sema::types::parse_type_spelling(&element),
                file,
            )));
        }
    }
    // `begin + 3` — the iterator is the left operand, and the question is the same.
    if CppSyntaxKind::from(expression.kind()) == CppSyntaxKind::BinaryExpr {
        let left = expression.children().next()?;
        return element_of_an_iterator_expression(
            memo,
            index,
            declaring,
            scopes,
            root,
            path,
            &left,
            depth + 1,
        );
    }
    None
}

/// **The callee of a call expression**, when the expression is one.
fn a_call_to_a_function(
    expression: &cpp_parser::CppSyntaxNode,
) -> Option<cpp_parser::CppSyntaxNode> {
    if CppSyntaxKind::from(expression.kind()) != CppSyntaxKind::CallExpr {
        return None;
    }
    expression.children().next()
}

/// **The element a range yields** — the whole element, where [`element_of`] answers one *component* of it.
///
/// The difference is what the two spellings ask: `for (auto x : map)` binds the `pair` itself, while
/// `for (auto [key, value] : map)` binds its two halves.
fn range_element_of(container: &Type) -> Option<String> {
    let Type::Named { name, arguments } = container else {
        return match container {
            Type::Array { of, .. } => Some(of.to_string()),
            _ => None,
        };
    };

    let plain = name.rsplit("::").next().unwrap_or(name);

    // **`>= 2`, not `== 2`.** The element of a map is `pair<const K, V>` whatever else the use
    // wrote, and a use writes the comparator as often as not: `std::map<std::string, LuaTokenKind,
    // std::less<>>` has three arguments, and requiring exactly two answered "no element" for the
    // ordinary spelling.
    if matches!(
        plain,
        "map" | "unordered_map" | "multimap" | "unordered_multimap"
    ) && arguments.len() >= 2
    {
        return Some(format!(
            "std::pair<const {}, {}>",
            arguments[0], arguments[1]
        ));
    }

    // The same allowance for the one-argument containers: a `vector<T, Alloc>` and a `set<K, Compare>` are the same
    // element as their one-argument spellings.
    if !arguments.is_empty()
        && matches!(
            plain,
            "vector"
                | "list"
                | "deque"
                | "forward_list"
                | "set"
                | "unordered_set"
                | "multiset"
                | "unordered_multiset"
                | "basic_string"
                | "string"
                | "span"
                | "initializer_list"
                | "valarray"
        )
    {
        return Some(arguments[0].to_string());
    }

    if matches!(plain, "array") && !arguments.is_empty() {
        return Some(arguments[0].to_string());
    }

    None
}

/// The type of what the declaration is initialized with.
///
/// The declaration's own syntax, found by **descending to the binding's range**: a binding's range is its
/// declarator (`n = count()` is the `InitDeclarator`), and the initializer is one of that node's children — the
/// shape the parser gives every initialized declaration, `int x = 0;` and `auto x = f();` alike.
fn initializer_type(
    memo: &TypeMemo,
    index: &ProjectIndex,
    declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    named: &NamedDeclaration,
    depth: usize,
) -> Known<(Type, PathBuf)> {
    let Some((_, expression)) = deduction_inputs(root, named) else {
        // Either the declaration is in another file — the initializer is written where the declaration is, and this
        // layer holds one file's syntax — or it has none at all (`auto n;` is ill-formed, and saying so is the
        // honest answer).
        return Known::Unknown(UnknownReason::UnknownType(Box::from("auto")));
    };

    type_of_expression_memoed(
        memo,
        index,
        declaring,
        scopes,
        root,
        path,
        &expression,
        depth,
    )
}

/// The spelling `auto` stands for, and the expression that decides it.
///
/// # Why the spelling is rebuilt rather than taken from the declaration's recorded type
///
/// [`crate::declared_type_of`] strips declaration **specifiers**, which is right for a lookup by name (`static
/// const Widget` names `Widget`) and wrong for a type a reader is shown: `const auto& r = x;` has to deduce
/// `const int&`, and the `const` is a specifier the recorded spelling has already dropped. So the two halves are
/// read from the syntax instead — the specifier sequence (`const auto`) and the declarator's own operators (`&`) —
/// and put back together the way the file would have spelled the type it let `auto` stand for.
///
/// The declarator's operators are its text with the name taken out: `& r ` is `&`, `* p ` is `*`, `p ` is nothing.
/// The **expression a `typeof`/`__typeof__` specifier names**, when that is what its payload is.
///
/// `None` for the type-id form (`typeof(struct point)`), which the syntax reader already resolves, and for every
/// declaration that has no `typeof` at all.
fn a_typeof_payload(
    root: &cpp_parser::CppSyntaxNode,
    named: &NamedDeclaration,
) -> Option<cpp_parser::CppSyntaxNode> {
    let NamedDeclaration::Here(binding) = named else {
        return None;
    };
    let declarator = node_covering(root, binding.name_range.start_offset, binding.range)?;
    let specifiers = declarator.ancestors().find_map(|node| {
        node.children().find(|child| {
            cpp_parser::CppSyntaxKind::from(child.kind())
                == cpp_parser::CppSyntaxKind::DeclSpecifierSeq
        })
    })?;
    let typeof_node = specifiers.children().find(|child| {
        let text = child.text().to_string();
        let name = text
            .trim()
            .split('(')
            .next()
            .unwrap_or("")
            .trim()
            .to_string();
        matches!(
            name.as_str(),
            "typeof" | "typeof_unqual" | "__typeof__" | "__typeof" | "__decltype" | "decltype"
        )
    })?;
    // The payload is the node inside the parentheses. A type-id has a TypeId child and is not this question.
    typeof_node.children().find(|child| {
        !matches!(
            cpp_parser::CppSyntaxKind::from(child.kind()),
            cpp_parser::CppSyntaxKind::TypeId | cpp_parser::CppSyntaxKind::DeclSpecifierSeq
        )
    })
}
/// Does this specifier sequence hold an **unnamed class body** — `struct { … }` with no tag of its own?
///
/// The shape whose type has no spelling, which the query path keys by the declarator's name. See the note on
/// `NamedDeclaration::type_of`.
fn an_unnamed_class_body(
    specifiers: &cpp_parser::CppSyntaxNode,
) -> Option<cpp_parser::CppSyntaxNode> {
    let body = specifiers.children().find(|child| {
        matches!(
            cpp_parser::CppSyntaxKind::from(child.kind()),
            cpp_parser::CppSyntaxKind::ClassDef
                | cpp_parser::CppSyntaxKind::StructDef
                | cpp_parser::CppSyntaxKind::UnionDef
        )
    })?;
    let tag = body.children().any(|child| {
        cpp_parser::CppSyntaxKind::from(child.kind()) == cpp_parser::CppSyntaxKind::NameExpr
    });
    (!tag).then_some(body)
}
fn deduction_inputs(
    root: &cpp_parser::CppSyntaxNode,
    named: &NamedDeclaration,
) -> Option<(String, cpp_parser::CppSyntaxNode)> {
    let NamedDeclaration::Here(binding) = named else {
        return None;
    };

    let declarator = node_covering(root, binding.name_range.start_offset, binding.range)?;
    // **The initializer is the *declarator*'s child, and a binding may range over the `InitDeclarator` that wraps it.**
    // `Box box(7);` is `InitDeclarator > Declarator > [NameExpr, Initializer]`, so a walk that looked for the initializer
    // among the outermost node's children found none and answered "this declaration has no initializer" — which is what
    // made class template argument deduction unreachable. Measured: `techniques::Box box(7)` typed as
    // `techniques::Box`.
    let is_an_initializer = |node: &cpp_parser::CppSyntaxNode| {
        cpp_parser::CppSyntaxKind::from(node.kind()) == cpp_parser::CppSyntaxKind::Initializer
    };
    let declarator = if declarator.children().any(|child| is_an_initializer(&child)) {
        declarator
    } else {
        declarator.children().find(|child| {
            cpp_parser::CppSyntaxKind::from(child.kind()) == cpp_parser::CppSyntaxKind::Declarator
        })?
    };
    let initializer = declarator
        .children()
        .find(|child| is_an_initializer(child))?;
    let first = initializer.children().next()?;
    // **A paren initialiser holds an *argument list*, not an expression.** `Box box(7);` is
    // `Initializer > ArgumentList > LiteralExpr`, and handing the list itself to the expression walk answers nothing —
    // the `auto` path never noticed because `auto n(7)` is unusual while `Box box(7)` is the shape C++17's class
    // template argument deduction is written for. Measured: `techniques::Box box(7)` typed as `techniques::Box`.
    let expression = if cpp_parser::CppSyntaxKind::from(first.kind())
        == cpp_parser::CppSyntaxKind::ArgumentList
    {
        first.children().next()?
    } else {
        first
    };

    // The specifiers are a sibling of the declarator's parent — `Declaration > [DeclSpecifierSeq, InitDeclarator]`
    // — and they are where the `auto` and its qualifiers are written.
    let specifiers = declarator
        .ancestors()
        .find_map(|node| {
            node.children().find(|child| {
                cpp_parser::CppSyntaxKind::from(child.kind())
                    == cpp_parser::CppSyntaxKind::DeclSpecifierSeq
            })
        })
        .map(|node| node.text().to_string())
        .unwrap_or_default();

    // The name's own text, taken from the file: the declarator's text minus the name is what was written *around*
    // it — the half the recorded type keeps and the specifiers do not. The **declarator** rather than the node the
    // binding ranges over, because that node is the whole `InitDeclarator` (`& r = x`) and its text holds the
    // initializer too.
    let name_range = binding.name_range;
    let name = root
        .text()
        .to_string()
        .get(name_range.start_offset..name_range.end_offset())
        .unwrap_or_default()
        .to_string();
    let operators: String = declarator
        .children()
        .find(|child| {
            cpp_parser::CppSyntaxKind::from(child.kind()) == cpp_parser::CppSyntaxKind::Declarator
        })
        .map(|node| node.text().to_string())
        .unwrap_or_default()
        .replace(&name, "")
        .split_whitespace()
        .collect();

    Some((
        format!("{} {}", specifiers.trim(), operators)
            .trim()
            .to_string(),
        expression,
    ))
}

/// The node whose span is exactly `range`, found along the path to `offset`.
///
/// A binding records a range, and the node it names can be several levels down; walking from the root along the
/// child that contains the offset costs the depth of the tree rather than a search of it.
fn node_covering(
    root: &cpp_parser::CppSyntaxNode,
    offset: usize,
    range: cpp_parser::SourceRange,
) -> Option<cpp_parser::CppSyntaxNode> {
    let matches = |node: &cpp_parser::CppSyntaxNode| {
        usize::from(node.text_range().start()) == range.start_offset
            && usize::from(node.text_range().end()) == range.end_offset()
    };

    let mut node = root.clone();
    loop {
        if matches(&node) {
            return Some(node);
        }

        // **Nodes only, and half-open.** The descent follows the child that contains the offset, and two details
        // decide whether it arrives: a token contains the offset just as its node does (taking it would end the
        // walk one level early), and a node's `end` is *exclusive* — so an offset at the boundary between two
        // children belongs to the one that starts there. Both were wrong once: `auto n = …` answered `None`
        // because the name's offset is exactly where the specifier sequence before it ends.
        let next = node
            .children_with_tokens()
            .find(|element| {
                element.as_node().is_some_and(|child| {
                    let start = usize::from(child.text_range().start());
                    let end = usize::from(child.text_range().end());
                    offset >= start && offset < end
                })
            })
            .and_then(|element| element.into_node())?;

        node = next;
    }
}

/// The written spelling with the initializer's type substituted for `auto`.
///
/// What was written *around* `auto` is what a reader sees and what the language applies: the qualifiers in front
/// (`const`), and the declarator's operators behind (`&`, `*`). The `&&` case is refused here — see
/// [`declared_type`] — and each `*` has to match a pointer in the deduced type, because a `*` that does not is a
/// declaration that does not compile rather than a type to report.
fn auto_substituted(
    written: &str,
    deduced: &Type,
    initializer_is_an_lvalue: bool,
) -> Option<String> {
    // **`decltype(auto)` means "the type this expression has"** — so the deduced type *is* the answer, not a
    // `decltype(…)` written around it. Measured: `decltype(auto) same = widen_gently(1);` answered `decltype(int)`, which
    // is a type no reader writes and no declaration contains.
    if written.trim() == "decltype(auto)" {
        return Some(deduced.to_string().trim().to_string());
    }
    let deduced = deduced.to_string();
    let deduced = deduced.as_str();
    // The `auto` **word**, by position: a spelling can hold those four letters inside a longer name
    // (`automatic`), and splitting on words is what keeps the two apart.
    let is_word = |byte: u8| byte.is_ascii_alphanumeric() || byte == b'_';
    let bytes = written.as_bytes();
    let mut at = 0usize;
    let mut found = None;

    while at < bytes.len() {
        if !is_word(bytes[at]) {
            at += 1;
            continue;
        }
        let start = at;
        while at < bytes.len() && is_word(bytes[at]) {
            at += 1;
        }
        // **`__auto_type` is the same placeholder written with GNU's spelling**, and it is one word in this scan — so
        // comparing against `auto` alone left it unreplaced, and the whole deduction answered nothing: measured,
        // `__auto_type value = 41;` went from `__auto_type` to *no type at all*. Pinned by
        // `gnu_auto_type_is_deduced_from_its_initializer`.
        if matches!(&written[start..at], "auto" | "__auto_type") {
            found = Some((start, at));
            break;
        }
    }

    let (start, end) = found?;
    let prefix = written[..start].trim();
    let suffix = written[end..].trim();

    let mut base = deduced.trim().to_string();
    for _ in 0..suffix.matches('*').count() {
        base = pointee_type_name(&base)?.to_string();
    }
    // **The reference the declarator wrote, applied the language's way.**
    //
    // A reference in the initializer never survives into `auto`: `auto& v = f();` where `f()` returns `T&` deduces
    // `auto = T`, so `v` is `T&` — and the spelling this function built was `T&&`, a type that names no class and
    // that every later member query then failed on. Measured on a real project (`LSPHandle.cpp`'s
    // `auto &vfs = _server->GetVFS();`): `vfs` was typed **`VirtualFileSystem&&`**, and `vfs.GetVirtualFile(...)`
    // answered `Unknown(NotDeclaredHere("VirtualFileSystem::GetVirtualFile"))` — one class member away from the
    // declaration that is right there. Everything the variable fed (`vFile`, `opSyntaxTree`, `lineIndex`,
    // `totalLine`) inherited the refusal, which is why four unrelated-looking hover cards were wrong at once.
    //
    // `&&` collapses rather than refuting: `T&` stays `T&` and `T`/`T&&` become `T&&`. It used to be refused
    // outright — see the note on [`declared_type`] — which answered nothing for a declaration every C++ compiler
    // reads.
    let mut reference = "";
    if suffix.contains('&') {
        let deduced_had_one = base.ends_with("&&") || base.ends_with('&');
        if deduced_had_one {
            let trimmed = base.trim_end_matches('&').trim_end().len();
            base.truncate(trimmed);
            base = base.trim_end().to_string();
        }
        reference = match (
            suffix.contains("&&"),
            deduced_had_one || initializer_is_an_lvalue,
        ) {
            (true, false) => "&&",
            _ => "&",
        };
    }
    let stars = "*".repeat(suffix.matches('*').count());

    let mut type_of = String::new();
    if !prefix.is_empty() {
        type_of.push_str(prefix);
        type_of.push(' ');
    }
    type_of.push_str(base.trim());
    // A `*` and a `&` are glued to what they apply to (`const int*`, `int&`) — the way the file would have spelled
    // the type it let `auto` stand for. The declarator's own operators come back in the order they were written:
    // `auto *&` is a reference to a pointer, and the `*` has already been applied to the base above.
    type_of.push_str(&stars);
    type_of.push_str(reference);

    Some(type_of)
}

/// Is this a return spelling the *body* decides — `auto`, `auto&`, `decltype(auto)`?
fn is_a_placeholder(written: &str) -> bool {
    matches!(
        written.trim(),
        "auto" | "auto&" | "auto&&" | "const auto" | "const auto&" | "decltype(auto)"
    )
}

fn what_a_call_has_in(fact: &DeclFact) -> Option<Type> {
    match fact.kind {
        // `Widget()` is a temporary of `Widget`, so a call of a class has the class. `DeclKind::Type` is exactly
        // "this declaration declares a class-like type", which is the case a call whose callee is a *type* lands in.
        crate::DeclKind::Type => Some(Type::named(fact.qualified_name())),
        // **A placeholder is not a return type.** `auto copy_of() const { return value_; }` records `auto` as the spelling
        // the file wrote, and parsing it answers a type *called* `auto` — which reads like an answer and is not one. `None`
        // here is what lets the caller deduce from the body, which is the same thing the same-file arm already does; the
        // body is read from the declaring file at the fact's offset **translated into that file's rendering**, which is
        // where this path used to land on a neighbouring declaration instead.
        _ => fact
            .returns
            .as_deref()
            .filter(|written| !is_a_placeholder(written))
            .map(parse_type_spelling),
    }
}

/// The declaration an expression names, or why it names none. See [`NamedDeclaration`].
/// Is this word written the way MSVC writes the macro that stands for a namespace?
///
/// `_STD`, `_CSTD`, `_RANGES`, `_STDEXT`, `_CHRONO` — every one of them a leading underscore, which is the half of
/// the convention the standard gives to the implementation. The other half is the all-capitals spelling
/// (`MY_API`, `HUGEP`), and both are what a reader looks at when deciding whether the word in front of a `::` is a
/// namespace or a macro that stands for one.
///
/// A **spelling**, and it is used where nothing better is available: the environment that could settle it is not
/// part of a name, and the alternative — splitting every `::` — would read `std::f` as `f` and answer with whichever
/// `f` it found. See the caller, which is the only place this decides anything.
fn written_like_a_macro(word: &str) -> bool {
    word.starts_with('_')
        || (word.len() > 1
            && word
                .chars()
                .all(|character| !character.is_alphabetic() || character.is_uppercase()))
}

/// **The type of one name a structured binding declared** — `value` in `for (auto [key, value] : map)`.
///
/// `None` when the name is not one: the ordinary case, and the one that must stay cheap. The check is the **binding**
/// the name resolves to, not the syntax around the *use* — `value.size()` is a `NameExpr` with no pattern above it,
/// and looking for one there answered nothing for exactly the position a reader hovers.
///
/// The element type comes from the **range** (or the initializer), decomposed by the standard library's own shapes:
///
/// ```text
///   map<K, V> / unordered_map<K, V>     the element is `pair<const K, V>`, so [key, value] is const K, V
///   vector<T> / list<T> / set<T> …      the element is `T`
///   pair<A, B> / tuple<A, B, …>         the element is the i-th argument
///   T[N] / std::array<T, N>             the element is `T`
/// ```
///
/// Anything else answers `None`: a class that specializes `tuple_size`/`tuple_element` is the language's extension
/// point, and this layer has no way to read a specialization it has not been taught.
fn structured_binding_type(
    memo: &TypeMemo,
    index: &ProjectIndex,
    declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    expression: &cpp_parser::CppSyntaxNode,
    depth: usize,
) -> Option<Known<(Type, PathBuf)>> {
    // **The declaration the name resolves to**, and then the pattern it was declared in.
    let at = end_of_the_written_name(expression);
    let Known::Yes(binding) = crate::sema::resolve::definition_at(scopes, root, at) else {
        return None;
    };
    if binding.kind != crate::BindingKind::Variable {
        return None;
    }

    let declared_at = binding.name_range.start_offset;
    let pattern = cpp_parser::token_at(root, declared_at)?
        .parent_ancestors()
        .find(|node| {
            cpp_parser::CppSyntaxKind::from(node.kind())
                == cpp_parser::CppSyntaxKind::StructuredBinding
        })?;

    // **Which name of the pattern this is**, by position — the order maps into the components, and the names
    // themselves mean nothing (`[first, second]` and `[a, b]` are the same binding).
    let mut position = None;
    let mut seen = 0usize;
    for child in pattern.children() {
        if cpp_parser::CppSyntaxKind::from(child.kind()) != cpp_parser::CppSyntaxKind::NameExpr {
            continue;
        }
        let range = cpp_parser::source_range(child.text_range());
        if range.start_offset == declared_at {
            position = Some(seen);
            break;
        }
        seen += 1;
    }
    let position = position?;

    // The container: the range of the `for` this pattern is a binding of, or the initializer of a plain declaration.
    let container = match range_expression_of_the_pattern(&pattern) {
        Some(range) => type_of_expression_memoed(
            memo,
            index,
            declaring,
            scopes,
            root,
            path,
            &range,
            depth + 1,
        ),
        None => {
            let initializer = initializer_of_the_pattern(&pattern)?;
            type_of_expression_memoed(
                memo,
                index,
                declaring,
                scopes,
                root,
                path,
                &initializer,
                depth + 1,
            )
        }
    };
    let Known::Yes((container, file)) = container else {
        return Some(container);
    };

    // **A class this project declares, whose members are `first` and `second`.** `element_of` is a table of the
    // standard library's shapes and knows nothing about a class's members; a pair-like type is exactly a class with those
    // two, and `members_of` has their types — substituted with the container's arguments, so `Pair<int, double>` binds
    // `int` and `double` and not the parameters it was declared with. The order is asked by **name** rather than by
    // position: the member list is sorted, so "the first data member" is not a question it can answer.
    let element = element_of(&container, position).or_else(|| {
        let Type::Named { name, .. } = &container else {
            return None;
        };
        let wanted = match position {
            0 => "first",
            1 => "second",
            _ => return None,
        };
        let Known::Yes(listed) = members_of(index, scopes, root, path, name) else {
            return None;
        };
        // **And the container's arguments substituted through it.** The session's `members_of` does this for a caller that
        // asked with a template-id (`Pair<int, double>`); a caller here holds the list *before* that step, so it runs it —
        // the same function, so the two cannot disagree about what `first` is.
        let Known::Yes(listed) =
            substituted_members(index, path, &container.to_string(), Known::Yes(listed))
        else {
            return None;
        };
        listed
            .members
            .iter()
            .find(|member| {
                member.fact.name == wanted && member.fact.kind == crate::DeclKind::Variable
            })
            .and_then(|member| member.fact.type_of.clone())
    });

    Some(match element {
        Some(element) => Known::Yes((crate::sema::types::parse_type_spelling(&element), file)),
        None => Known::Unknown(UnknownReason::UnknownType(Box::from(container.to_string()))),
    })
}

/// The expression after the `:` of the range-based `for` this pattern is a binding of.
fn range_expression_of_the_pattern(
    binding: &cpp_parser::CppSyntaxNode,
) -> Option<cpp_parser::CppSyntaxNode> {
    use cpp_parser::CppTokenKind;

    let loop_node = binding.ancestors().find(|node| {
        cpp_parser::CppSyntaxKind::from(node.kind()) == cpp_parser::CppSyntaxKind::RangeForStat
    })?;

    let mut after_the_colon = false;
    for child in loop_node.children_with_tokens() {
        match child {
            cpp_parser::CppSyntaxElement::Token(token) => {
                if CppTokenKind::from(token.kind()) == CppTokenKind::Colon {
                    after_the_colon = true;
                }
            }
            cpp_parser::CppSyntaxElement::Node(node) => {
                if after_the_colon && node != *binding {
                    return Some(node);
                }
            }
        }
    }
    None
}

/// The initializer of `auto [a, b] = pair;` — the expression after the `=`.
///
/// **The `=` is inside the `InitDeclarator`**, not a child of the `Declaration`: measured, the tree is
/// `Declaration > InitDeclarator "[number, fraction] = pair" > [StructuredBinding, =, NameExpr]`. The first version scanned
/// the declaration and found no `=` there, so every structured binding over a `pair` answered nothing and the name rule below
/// then made up a spelling (`int()` for both names). The declarator is asked first and the declaration is the fallback for a
/// tree that writes the initializer one level up.
fn initializer_of_the_pattern(
    pattern: &cpp_parser::CppSyntaxNode,
) -> Option<cpp_parser::CppSyntaxNode> {
    use cpp_parser::CppTokenKind;

    let holders: Vec<cpp_parser::CppSyntaxNode> = pattern
        .ancestors()
        .take_while(|node| {
            !matches!(
                cpp_parser::CppSyntaxKind::from(node.kind()),
                cpp_parser::CppSyntaxKind::FunctionDef | cpp_parser::CppSyntaxKind::TranslationUnit
            )
        })
        .filter(|node| {
            matches!(
                cpp_parser::CppSyntaxKind::from(node.kind()),
                cpp_parser::CppSyntaxKind::InitDeclarator | cpp_parser::CppSyntaxKind::Declaration
            )
        })
        .collect();

    for holder in holders {
        let mut after_the_equals = false;
        for child in holder.children_with_tokens() {
            match child {
                cpp_parser::CppSyntaxElement::Token(token) => {
                    if CppTokenKind::from(token.kind()) == CppTokenKind::Assign {
                        after_the_equals = true;
                    }
                }
                cpp_parser::CppSyntaxElement::Node(node) if after_the_equals => return Some(node),
                cpp_parser::CppSyntaxElement::Node(_) => {}
            }
        }
    }
    None
}

/// **The type of the `position`-th component** of a container's elements, as a spelling.
///
/// The standard library's shapes, by name: `map`'s element is a `pair`, a sequence's element is its argument, and
/// `tuple`'s is the i-th. A name this does not recognise answers `None` — `tuple_size`/`tuple_element` specializations
/// are a language feature with no reader here.
fn element_of(container: &Type, position: usize) -> Option<String> {
    let Type::Named { name, arguments } = container else {
        // An array's element is its own type: `int[4]` binds `int`.
        return match container {
            Type::Array { of, .. } => Some(of.to_string()),
            _ => None,
        };
    };

    let plain = name.rsplit("::").next().unwrap_or(name);

    // A `map`'s element is `pair<const K, V>`: the key is `const`, and the position picks the side.
    if matches!(
        plain,
        "map" | "unordered_map" | "multimap" | "unordered_multimap"
    ) && arguments.len() == 2
    {
        return match position {
            0 => Some(format!("const {}", arguments[0])),
            _ => Some(arguments[1].to_string()),
        };
    }

    if matches!(plain, "array") && arguments.len() == 2 {
        return Some(arguments[0].to_string());
    }

    // A sequence, a set, or a span: one argument, and the element is it.
    if arguments.len() == 1
        && matches!(
            plain,
            "vector"
                | "list"
                | "deque"
                | "forward_list"
                | "set"
                | "unordered_set"
                | "multiset"
                | "unordered_multiset"
                | "basic_string"
                | "string"
                | "span"
                | "initializer_list"
                | "valarray"
        )
    {
        return Some(arguments[0].to_string());
    }

    // `pair` and `tuple` are the components themselves.
    if matches!(plain, "pair" | "tuple") {
        return arguments
            .get(position)
            .map(|component| component.to_string());
    }

    None
}
fn writes_a_name(written: &str) -> bool {
    let spelling = written.strip_prefix("::").unwrap_or(written);

    // **A whole expression is not a name**, and this is the half that keeps the widening below from swallowing one.
    //
    // `static_cast<T>(y)` has no `::` trouble and its segments pass once the argument list comes off — but the name
    // arm asks its question at the **last identifier**, which is `y` there, so the answer became `int` for a cast
    // that names `T`. Measured by a test that had been passing: `a cast names the type it casts to: int`. The arms
    // below this gate exist for exactly those spellings, and a gate that lets them through answers a different
    // question than the caller asked.
    //
    // What is left after this test is a name: `std::vector<int>` and `A<B>::C<D>` pass, `f(x)`, `a + b`, `{1, 2}`
    // and `static_cast<T>(y)` do not. `,` is in the list because `A<B, C>` is a name and `f(a, b)` is not — and
    // after the argument list comes off, the two are otherwise the same shape.
    // **A braced construction is not a name either.** `B<int>{}` passes every other test here — its one segment is
    // `B` once the `<…>` comes off — so the name arm claimed it and answered `UnknownType("B<int>{}")` before the
    // braced-list arm could type it. `auto x = B{};` worked only because a list with values writes a comma
    // (`std::pair{1, 2.5}`) and the comma was already in the list. Measured on `Builder<int>{}.with(2)` in
    // `templates.cpp`: the member access reported "the type of `Builder<int>{}` is not known".
    if spelling.contains('(')
        || spelling.contains(')')
        || spelling.contains(',')
        || spelling.contains('{')
        || spelling.contains('}')
    {
        return false;
    }

    !spelling.is_empty()
        && spelling
            .split("::")
            // Every segment is one identifier, or a **run of them** separated by single spaces — the macro prefix
            // and the name it stands in front of. A segment with a space in the middle of a word (`_STD  f` with
            // two) is still a run, because `split_whitespace` is what reads it.
            .all(|segment| {
                // **A template-id is still a name, and this gate used to say it was not.**
                //
                // `std::vector<int>` splits on `::` into `std` and `vector<int>`, and the second is not an
                // identifier — so the gate refused, the whole name lookup was **skipped**, and the answer was
                // `UnknownType("std::vector<int>")`. Measured on the report that started this: `auto x =
                // std::vector<int>();` refused while `std::vector<int> v;` worked, because a *declaration's* type
                // is read by another reader — one that understands a template-id — and only the call path came
                // through here.
                //
                // What comes off is the argument list, not the name: `A<B>::C<D>` is two segments and the name of
                // the first is `A`. A spelling that only *looks* like a template-id (`i<n` from a comparison the
                // grammar read as one) is harmless: this is a gate, and the lookup that follows finds nothing for a
                // name nobody declared.
                let bare = segment.split('<').next().unwrap_or(segment);
                let mut words = bare.split_whitespace();
                words.clone().count() > 0 && words.all(is_an_identifier)
            })
}

/// Is this segment a name a declaration could carry?
fn is_an_identifier(segment: &str) -> bool {
    !segment.is_empty()
        && segment
            .chars()
            .all(|character| character.is_alphanumeric() || character == '_')
}

/// **What a function template's parameters stand for, from the types of the arguments the call passed.**
///
/// `template <class _It> auto f(_It p)` called as `f(a_pointer)` says `_It = int*` without writing it. The rule is
/// C++'s, restricted to the one case this layer can be sure of: a function parameter written as **exactly one**
/// template parameter takes that parameter's place, so the argument passed there is what the parameter stands for.
///
/// A parameter written as `vector<_Ty> const&` would need the argument's own template-id taken apart, and that is a
/// different deduction — attempted for none of the parameters if it is attempted for one, because a half-substituted
/// list is a type nobody wrote.
///
/// The result is **positional against the template parameter names**, which is how every consumer of a substitution
/// reads it: a name with no deduced argument stays itself, so `_Alloc` in `template <class _Ty, class _Alloc>` does
/// not silently become `_Ty`'s argument.
fn deduce_the_parameters(
    names: &[String],
    written_list: Option<&str>,
    argument_types: &[Type],
) -> Vec<Type> {
    let mut deduced: Vec<Type> = names.iter().map(Type::named).collect();
    if names.is_empty() || argument_types.is_empty() {
        return deduced;
    }

    let Some(list) = written_list else {
        return deduced;
    };

    for (at, parameter) in written_parameters(list).into_iter().enumerate() {
        // **The parameter's type, which is the parameter minus its name.** `_It p` is `_It` and `int count` is `int`;
        // a parameter written with no name at all (`int`) is one word and is its own type. Getting this wrong is
        // silent: the first version compared the whole `_It p` against the template parameter's `_It`, never matched,
        // and deduced nothing — so the wrong answer it was written to remove (`b = _It`) stayed exactly as it was.
        let words: Vec<&str> = parameter.split_whitespace().collect();
        let written_type = match words.len() {
            0 => continue,
            1 => words[0],
            _ => {
                &parameter[..parameter
                    .rfind(words[words.len() - 1])
                    .unwrap_or(parameter.len())]
            }
        };
        let written_type = written_type.trim();
        if written_type.is_empty() {
            continue;
        }

        // **Exactly one parameter name**, once a reference is taken off — and the reference is the point.
        //
        // Standard library functions are written `template <class _Iter> auto f(_Iter&& _It)`, which is a **forwarding
        // reference**: C++ deduces `_Iter` from the argument, and that is what the syntax is for. A rule that insisted
        // on the bare name matched nothing here, and the failure was quiet — the substitution fell back to the
        // parameter's own name, so `written_arguments` was `["_Iter"]` and every substitution was a no-op. Measured:
        // 54 `auto` declarations over eight MSVC headers, every one of them a `_STD` call whose callee takes `_Iter&&`.
        //
        // What this layer does with the reference is the part `auto` would do anyway: an argument passed to `_Iter&&`
        // gives `_Iter` the argument's own type, and the caller is an `auto` initializer, which strips references and
        // top-level `const` by definition. `_Iter*` — the parameter *contains* the parameter — is still not attempted,
        // because undoing a `*` needs the argument taken apart and a half-done version pairs the wrong argument with
        // the wrong parameter.
        let bare = written_type
            .strip_suffix("&&")
            .or_else(|| written_type.strip_suffix('&'))
            .map(str::trim)
            .unwrap_or(written_type);

        let Some(name_at) = names.iter().position(|name| name == bare) else {
            continue;
        };
        let Some(argument) = argument_types.get(at) else {
            continue;
        };

        deduced[name_at] = argument.clone();
    }

    deduced
}

/// A written parameter list, cut into its parameters at the commas that are **not inside brackets**.
///
/// `(int count, double factor)` is two; `(_Ty (*fn)(int, char))` is one, and a split on every comma would make it
/// three and pair the wrong argument with the wrong parameter — worse than not deducing at all.
fn written_parameters(list: &str) -> Vec<String> {
    let body = list.trim();
    let body = body.strip_prefix('(').unwrap_or(body);
    let body = body.strip_suffix(')').unwrap_or(body);

    let mut out = Vec::new();
    let mut depth = 0usize;
    let mut at = 0usize;
    for (index, character) in body.char_indices() {
        match character {
            '(' | '[' | '<' => depth += 1,
            ')' | ']' | '>' => depth = depth.saturating_sub(1),
            ',' if depth == 0 => {
                out.push(body[at..index].to_string());
                at = index + 1;
            }
            _ => {}
        }
    }
    out.push(body[at..].to_string());

    out
}

/// **The offset at which "which name is this" is asked**: the expression's **last identifier**.
///
/// The offset decides the question, because [`crate::sema::resolve::definition_at`] builds a name's spelling by
/// walking its chain *up to the cursor* — a cursor on `a` in `a::b::c` asks about `a::b`, and one on `c` asks about
/// the whole of it. An expression node is the **whole** chain: the user pointed at an entity, and what identifies
/// that entity is all of it (`std::cin`, not the namespace `std`). So the question is asked at the far end, which
/// for a bare name is the offset it always was.
///
/// The last **identifier** rather than the node's end offset, and the difference is a bug this had for one revision:
/// a node's range covers its trailing trivia (`NameExpr` for `w` in `int w = 1;` ends after the space), so the end
/// offset lands *past* the name and the lookup answers `UnparsableName` — every plain name in the file losing its
/// type at once.
fn end_of_the_written_name(expression: &cpp_parser::CppSyntaxNode) -> usize {
    // **Not the last identifier in the text — the last identifier of the *name*.** The difference is the whole of
    // how a template-id is called: `_Convert_size<size_type>(n)` holds two identifiers, and the later of them is
    // the template **argument**. Taking it asked the scope for `size_type` — an alias, not a function — and the
    // call was then refused with a type that had nothing to do with the callee. Measured on a fixture where the
    // same function called through a header deduced and called in its own file refused.
    //
    // A `TemplateArgumentList` is where those identifiers live, and skipping its subtrees is the whole fix: the
    // name of `A<B>::C<D>` is still `C`, and the arguments on both sides are no longer candidates.
    let mut last = None;

    for element in expression.descendants_with_tokens() {
        let Some(token) = element.into_token() else {
            continue;
        };
        if cpp_parser::CppTokenKind::from(token.kind()) != cpp_parser::CppTokenKind::Identifier {
            continue;
        }
        if token
            .parent_ancestors()
            .any(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::TemplateArgumentList)
        {
            continue;
        }
        last = Some(usize::from(token.text_range().start()));
    }

    last.unwrap_or_else(|| usize::from(expression.text_range().start()))
}

fn declaration_of_expression(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    expression: &cpp_parser::CppSyntaxNode,
) -> Known<NamedDeclaration> {
    let offset = end_of_the_written_name(expression);
    let written = expression.text().to_string();
    let written = written.trim();

    let asked = crate::sema::resolve::definition_at(scopes, root, offset);

    match asked {
        Known::Yes(binding) => Known::Yes(NamedDeclaration::Here(binding)),
        Known::Unknown(UnknownReason::NotDeclaredHere(name)) => {
            // **A name whose spelling carries a macro prefix is two spellings, and one of them is real.** `_STD`
            // is `::std::` to a compiler and an ordinary identifier to a file that has not read `<yvals.h>`, so
            // the expression reads the pair as one name — `_STD f`, `_CSTD memmove` — and the lookup then asks the
            // index for a name nobody declares. Measured, this is what most of the `auto` declarations in MSVC's
            // headers were refused for: 476 of them reached this arm and stopped.
            //
            // The part **after** the prefix is the name, and it is tried second rather than first: a file whose
            // macro the analysis *can* see has its full spelling bound in the scope tree, and that case never
            // reaches here at all. What is left is the prefix, and dropping it is what a reader does with the
            // line in front of them.
            //
            // **Two separators, because the name arrives in two spellings.** A macro prefix and what follows it are
            // written `_STD f` — two words — and the reader above builds its qualified spelling with `::`, so the
            // name this arm is handed is **`_STD::f`**. Measured, that is exactly what it was: the space-split never
            // matched, and `auto a = _STD f();` stayed refused while `auto a = f();` gave `int`.
            //
            // Splitting a `::` is only safe when the **first segment is written like a macro** (`_STD`, `_CSTD`,
            // `_RANGES` — the leading underscore MSVC uses for every one of them), because `std::f` is a real
            // qualified name and dropping `std` to find some other `f` would be a wrong answer rather than a
            // missing one. That is the same discriminator the expression grammar uses for the same question, and it
            // is a spelling here for the same reason: the environment that could settle it is not part of a name's
            // spelling, and the segment in front of a `::` is what a reader would look at.
            let mut candidates: Vec<&str> = vec![name.as_ref()];

            // **A leading `::` is not part of the name.** It says "start at the global namespace", and for a name
            // that is already qualified — which is every name this arm is handed — that is a no-op: `::std::f` and
            // `std::f` are one entity. The index stores the second spelling, so a lookup with the first finds nothing.
            //
            // This is what kept every `_STD`-prefixed call in the standard library refused, and the count said so
            // without saying where: 54 `auto` declarations over eight MSVC headers, every one of them
            // `UnknownType("::std::…")`. The comment above notes that the spelling arrives as `_STD::f` — and for
            // `_STD`, which is `::std::`, that is `::std::f`. The fallback below is asked about the segment **before**
            // the first `::`, which for a leading `::` is the empty string: never macro-like, so it never fired.
            if let Some(without) = name.strip_prefix("::") {
                candidates.push(without);
            }

            if let Some((_, without_the_prefix)) = name.split_once(' ') {
                candidates.push(without_the_prefix.trim());
            }
            if let Some((first, rest)) = name.split_once("::")
                && written_like_a_macro(first)
            {
                candidates.push(rest);
            }

            // **Whether the index said "more than one" rather than "nothing"**, which is the difference between an
            // ambiguity a reader can act on and a name nothing declares. See the final arm below.
            let mut was_ambiguous = false;
            for candidate in candidates {
                let found: Option<(crate::DeclFact, PathBuf)> =
                    match index.definition(candidate, path) {
                        Known::Yes(found) => Some((found.fact, found.file)),
                        // **Several declarations of one name, and one type between them.** A name query answers
                        // `Ambiguous` when more than one declaration is visible, and that is right for "where is this
                        // declared" — but the question here is *what type it has*, and a type is not ambiguous when
                        // every declaration spells it the same way. MSVC's `<iostream>` declares `cin` twice (once
                        // plain, once as `_EXPORT_STD extern "C++" … istream cin;`), so `std::cin` was `Ambiguous` and
                        // every use of it lost its type: `std::cin.read(…)`, `std::cin.eof()`, a completion after
                        // `std::cin.` — measured, 8 offsets in one file. Candidates that **disagree**, and functions
                        // (which have no type as a name), keep the `Unknown` that the name query gave.
                        Known::Unknown(UnknownReason::Ambiguous(_)) => {
                            was_ambiguous = true;
                            agreeing_type(index, path, candidate)
                        }
                        Known::Unknown(_) | Known::No => None,
                    };

                if let Some((fact, file)) = found {
                    return Known::Yes(NamedDeclaration::Indexed(
                        fact,
                        file,
                        TypeBindings::default(),
                    ));
                }
            }

            // **Several declarations this file can see, and no type they all agree on.** The reason is kept rather
            // than flattened into `UnknownType`: `Ambiguous` already has a sentence a reader can act on ("declared
            // more than once in what this file can see, and nothing here chooses between the declarations"), and it is
            // what the editor report of `auto enenn = std::format(…)` needed — the popup said nothing at all, and the
            // reason it had nothing to say was exactly this. Measured on that file: `std::format` has four overloads
            // visible (narrow and wide, with and without a locale) and none of them is selected by the call.
            if was_ambiguous {
                Known::Unknown(UnknownReason::Ambiguous(Box::from(written)))
            } else {
                Known::Unknown(UnknownReason::UnknownType(Box::from(written)))
            }
        }
        // A name this layer cannot place at all is not a type it can read. `No` means the offset is not on a name;
        // any other `Unknown` is already the most specific answer available and is passed through.
        Known::Unknown(reason) => Known::Unknown(reason),
        Known::No => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
    }
}

/// The type of a **call**: `make().size` needs this, and so does `fac.build().size`.
///
/// # The two callees, and the one lookup behind them
///
/// ```text
/// make()          a name: what it returns
/// Widget()        a name, and the same tokens — a temporary of the class it names
/// fac.build()     a member access: what the member returns
/// ns::make()      a qualified name: what it returns
/// ```
///
/// The first two are one case because only the *declaration* separates them, and the last two go through the
/// lookups that already exist — the member lookup for a member call, the name lookup for everything else. What
/// this adds is the last step: the callee's declaration says what a call of it has ([`what_a_call_has_in`]).
///
/// Everything else stays [`UnknownReason::UnknownType`]: a call of a function pointer, of a lambda, of a template
/// parameter whose type is not known here. Each of those needs a type *computed* rather than read off a
/// declaration, which is the same boundary the rest of this function has.
/// **What the lambda the callee names returns**, when the callee is a name initialised with one.
///
/// ```cpp
/// auto doubler = [](int value) { return value * 2; };
/// auto result = doubler(3);      // what `result` is
/// **What a call through a function pointer has** — the return type of the function it points at.
///
/// `int (*fp)(int)` is a `Pointer` to a `Function`, and calling `fp(3)` has what that function returns. `None` for every other
/// type, which is the ordinary case: a name whose type is not a function pointer is not called through one.
fn a_function_pointer_returns(a_type: &Type) -> Option<Type> {
    let Type::Pointer { to } = a_type else {
        return None;
    };
    match to.as_ref() {
        Type::Function { returns, .. } => Some(returns.as_ref().clone()),
        // A pointer to a *pointer* to a function is not this: C++ would need the intermediate dereference, and answering
        // the deep return type would make `(**fpp)(1)` and `fpp(1)` the same call.
        _ => None,
    }
}

/// ```text
///
/// A lambda's type is unnamed, so `type_of` on the name answers nothing and the call has no return type to read. The syntax
/// does hold the answer: the declarator that carries the name also carries the lambda.
///
/// **Any binding kind is accepted**, because a name whose value can be called is recorded as a `Function` in this scope tree —
/// measured, `auto doubler = […];` gives `kind=Function` with the variable's own name range — and the question here is not what
/// kind it is, but whether a lambda is what it was initialised with.
fn a_lambdas_body_the_callee_names(
    root: &cpp_parser::CppSyntaxNode,
    scopes: &crate::ScopeTree,
    callee: &cpp_parser::CppSyntaxNode,
    argument_types: &[Type],
) -> Option<String> {
    let inside = callee.text_range();
    let Known::Yes(binding) =
        crate::sema::resolve::definition_at(scopes, root, inside.start().into())
    else {
        return None;
    };
    // **The declarator that holds the name**, found by the range the binding already carries — no name comparison, which
    // would confuse two names of the same spelling in sibling scopes.
    let name = binding.name_range;
    let declarator = root.descendants().find(|node| {
        let range = node.text_range();
        CppSyntaxKind::from(node.kind()) == CppSyntaxKind::InitDeclarator
            && usize::from(range.start()) <= name.start_offset
            && name.end_offset() <= usize::from(range.end())
    })?;
    let lambda = declarator
        .descendants()
        .find(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::LambdaExpr)?;
    crate::sema::declarations::a_lambdas_return_type(&lambda, argument_types)
}

fn type_of_a_call(
    memo: &TypeMemo,
    index: &ProjectIndex,
    declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    call: &cpp_parser::CppSyntaxNode,
) -> Known<(Type, PathBuf)> {
    let written = call.text().to_string();
    let written = written.trim();

    let Some(callee) = call.children().next() else {
        return Known::Unknown(UnknownReason::UnknownType(Box::from(written)));
    };

    // **The template arguments the call wrote**, which is the half of a function-template call that was being read
    // and thrown away: `_Convert_size<size_type>(_Length)` names the type it returns, and nothing was pairing that
    // name with the declaration's parameters. Read from the **syntax** rather than from the text, for the reason
    // `read_template_arguments` gives — an argument's text can contain commas a splitter would get wrong.

    // **An iterator-producing member call is a view of its container's element** — `v.begin()`, `m.find(k)`.
    //
    // The standard library's iterator types are class templates this layer cannot instantiate, so their own
    // members are not readable; what a reader writes next is `it->first`, `it->second` and `*it`, and all three are
    // questions about the **element**. Answering the element type is what makes them work — and the declared
    // `iterator` type, whose members are `operator*` and four typedefs, is both harder to compute and less useful.
    if let Some(element) =
        iterator_element_type(memo, index, declaring, scopes, root, path, &callee)
    {
        return element;
    }

    // **The template arguments the call wrote, from the *call* and not only from the callee.** A member call's `‹…›`
    // may be a sibling of the member-access node rather than a descendant of it — measured on a real project:
    // `_server->GetService<CommandService>()` found no written arguments, so the member's `returns` came back with
    // its template parameter still standing (`Service *`) and nothing after the arrow could be typed. The arguments
    // are searched for **before the argument list**, so that `f(g<int>(1))` cannot lend its inner `<int>` to `f`.
    let written_arguments = {
        let from_the_callee = written_template_arguments(&callee);
        if from_the_callee.is_empty() {
            call.children()
                .take_while(|child| {
                    CppSyntaxKind::from(child.kind()) != CppSyntaxKind::ArgumentList
                })
                .filter_map(|child| {
                    // **The child may *be* the list** — `descendants()` does not include the node it is called on,
                    // and a member call's template arguments sit beside the member access rather than inside it.
                    if CppSyntaxKind::from(child.kind()) == CppSyntaxKind::TemplateArgumentList {
                        return Some(child);
                    }
                    child.descendants().find(|node| {
                        CppSyntaxKind::from(node.kind()) == CppSyntaxKind::TemplateArgumentList
                    })
                })
                .next()
                .map(|list| crate::sema::types::read_template_arguments(&list))
                .unwrap_or_default()
        } else {
            from_the_callee
        }
    };

    // **The types of the arguments the call passed**, which is the other way a function template is told what its
    // parameters stand for — and the way the standard library uses almost everywhere: `_Get_unwrapped(_First)`
    // never writes `<int*>`, it passes one. Computed only when nothing was written, which is the only case it is
    // used in, because typing every argument of every call is not free.
    let argument_types: Vec<Type> = if written_arguments.is_empty() {
        crate::inlay::arguments_of(call)
            .unwrap_or_default()
            .iter()
            .filter_map(|argument| {
                match type_of_expression_memoed(
                    memo, index, declaring, scopes, root, path, argument, 0,
                ) {
                    Known::Yes((type_of, _)) => Some(type_of),
                    _ => None,
                }
            })
            .collect()
    } else {
        Vec::new()
    };

    // **A call through a function pointer** — `int (*fp)(int) = negate; fp(3)`. The callee is a variable whose type is a
    // *pointer to a function*, so what the call has is that function's return type. Measured: `auto through_pointer = fp(3)`
    // answered *"the type of `fp(3)` is not known here"*.
    if let Known::Yes((callee_type, file)) =
        type_of_expression_memoed(memo, index, declaring, scopes, root, path, &callee, 0)
        && let Some(returns) = a_function_pointer_returns(&callee_type)
    {
        return Known::Yes((returns, file));
    }

    // **A call of a lambda** — `auto f = [](int v) { return v * 2; }; f(3)`. The name has no type that says anything (a
    // lambda's type is unnamed), so the answer comes from the body of the lambda it was initialised with — the same deduction
    // an `auto`-returning function goes through. Measured: `auto result = doubler(3)` answered *"the type of `doubler(3)` is
    // not known here"* while the body plainly returns an `int`.
    if let Some(returns) = a_lambdas_body_the_callee_names(root, scopes, &callee, &argument_types) {
        return Known::Yes((
            crate::sema::types::parse_type_spelling(&returns),
            path.to_path_buf(),
        ));
    }

    // **A call of an object** — `f(1)` where `f`'s type declares `operator()`. The callee is not a function
    // declaration at all, so the lookup below would answer `No`; what the call has is what the operator returns.
    //
    // **Asked after the callee's declaration, and only when that is not a function.** This model has no function
    // type: the type of a *member function's name* is what the member **returns** — `vFile.GetSyntaxTree` types as
    // `std::optional<LuaSyntaxTree>` — so asking "does this callee have an `operator()`?" of a perfectly declared
    // member call answered **`std::optional`'s `operator()`**, and `auto op = vFile.GetSyntaxTree(vfs);` deduced
    // `value_type`. Measured on a real project: four unrelated-looking hover cards were this one arm, because the
    // wrong answer propagated to everything the variable fed.
    let resolved =
        declaration_of_a_callee(memo, index, declaring, scopes, root, path, &callee, written);
    let names_a_function = match &resolved {
        Known::Yes(named) => named.fact_kind() == crate::DeclKind::Function,
        _ => false,
    };
    if !names_a_function
        && let Known::Yes((callee_type, file)) =
            type_of_expression_memoed(memo, index, declaring, scopes, root, path, &callee, 0)
        && matches!(callee_type, Type::Named { .. })
        && let Some(returns) = operator_returns_of(
            index,
            declaring,
            scopes,
            root,
            path,
            &callee_type,
            "operator()",
        )
    {
        return Known::Yes((crate::sema::types::parse_type_spelling(&returns), file));
    }

    // **The standard library's factories, whose return type the standard fixes.** `make_shared<T>(args…)` is a
    // `shared_ptr<T>` and `make_unique<T>(args…)` a `unique_ptr<T>` — but the implementation is free to return a wrapper:
    // libstdc++ writes `shared_ptr<_NonArray<_Tp>>`, and substitution produced `shared_ptr<_NonArray<Node>>`, whose
    // `element_type` is the wrapper. A member reached through the arrow then looked in `std::shared_ptr` and answered
    // `Unknown`, measured on `auto twin = node->twin();`. The table is two families and says only what [util.smartptr]
    // says, so it holds for any library.
    if let Some(pointer) = the_factory_the_call_names(&callee)
        && let Some(argument) = written_arguments.first()
    {
        return Known::Yes((
            crate::sema::types::parse_type_spelling(&format!("{pointer}<{argument}>")),
            path.to_path_buf(),
        ));
    }

    // **The ranges algorithms, whose return type the standard fixes.** The implementation's `iterator` is a class
    // template over a closure type, so the index cannot spell it; what a reader does with the result is dereference it or
    // count with it, and those are the two answers below. See [`a_ranges_algorithm_the_call_names`].
    if let Some(algorithm) = a_ranges_algorithm_the_call_names(&callee) {
        let arguments = crate::inlay::arguments_of(call).unwrap_or_default();
        match algorithm.as_str() {
            "find" | "find_if" | "find_if_not" | "max" | "min" | "max_element" | "min_element"
            | "lower_bound" | "upper_bound" | "equal_range" | "search" => {
                if let Some(element) = arguments.first().and_then(|first| {
                    element_of_a_range_expression(
                        memo, index, declaring, scopes, root, path, first, 0,
                    )
                }) {
                    return element;
                }
            }
            "count" | "count_if" | "distance" | "ssize" => {
                return Known::Yes((
                    crate::sema::types::parse_type_spelling("std::ptrdiff_t"),
                    path.to_path_buf(),
                ));
            }
            "size" => {
                return Known::Yes((
                    crate::sema::types::parse_type_spelling("std::size_t"),
                    path.to_path_buf(),
                ));
            }
            "subrange" => {
                if let Some(first) = arguments.first()
                    && let Some(element) = element_of_an_iterator_expression(
                        memo, index, declaring, scopes, root, path, first, 0,
                    )
                {
                    return element;
                }
            }
            _ => {}
        }
    }

    // **A call whose callee names a class is a temporary of that class** — `std::shared_ptr<int>(p, deleter)`,
    // `Widget(1)`. The constructor is not a function the spelling names, so every arm above answers nothing, and the
    // class (with its written template arguments, which `parse_type_spelling` reads) was in the spelling all along.
    // Measured: `std::shared_ptr<int>(shared, nullptr).use_count()` answered *"the type of … is not known here"*, and the
    // hover on the member then had no class to look it up in.
    if let Some(spelling) = a_callee_that_names_a_type(index, path, &callee) {
        return Known::Yes((
            crate::sema::types::parse_type_spelling(&spelling),
            path.to_path_buf(),
        ));
    }

    let resolved =
        declaration_of_a_callee(memo, index, declaring, scopes, root, path, &callee, written);
    let known_so_far = match resolved {
        Known::Yes(named) => match named.what_a_call_has(
            index,
            declaring,
            scopes,
            root,
            path,
            &written_arguments,
            &argument_types,
        ) {
            Some(type_of) => return Known::Yes((type_of, named.file(path))),
            None => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
        },
        Known::Unknown(reason) => Known::Unknown(reason),
        Known::No => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
    };

    // **A call of an overload set, where the call's own arguments choose.** `std::to_string(count)` has five declarations
    // visible and one takes an `int`; `std::get<int>(either)` has three the `variant` can reach, and the survivors spell the
    // written `int`. The name query answers `Ambiguous` — right for "where is this declared", wrong for "what does this call
    // return", and the argument types are exactly the thing that decides. See
    // [`the_return_the_overloads_agree_on`] for the two questions it asks and what it refuses.
    if let Some(returns) = the_return_the_overloads_agree_on(
        index,
        path,
        &the_names_the_call_may_use(&callee),
        &written_arguments,
        &argument_types,
        crate::inlay::arguments_of(call)
            .map(|arguments| arguments.len())
            .unwrap_or_default(),
    ) {
        return Known::Yes((
            crate::sema::types::parse_type_spelling(&returns),
            path.to_path_buf(),
        ));
    }

    known_so_far
}

/// **The smart pointer a factory function returns** — `make_shared` → `shared_ptr`, `make_unique` → `unique_ptr`.
///
/// Asked of the **last** segment of the callee`s spelling, because the standard library's are written `std::make_shared`
/// and a project may write `using std::make_shared;` and then call it bare. A name that is only *similar* is not in the
/// table, and the ordinary arms answer for it.
fn the_factory_the_call_names(callee: &cpp_parser::CppSyntaxNode) -> Option<&'static str> {
    let spelled = callee.text().to_string();
    let spelled = spelled.trim();
    // The template arguments are the type the factory makes, not part of its name.
    let bare = match spelled.find('<') {
        Some(at) => spelled[..at].trim(),
        None => spelled,
    };
    let last = bare.rsplit("::").next().unwrap_or(bare);
    match last {
        "make_shared" => Some("shared_ptr"),
        "make_unique" | "make_unique_for_overwrite" => Some("unique_ptr"),
        _ => None,
    }
}

/// **The callee's spelling when it names a class** — the temporary a call of a type constructs.
///
/// A template-id is kept as written, because its arguments are part of the type: `std::shared_ptr<int>`. The name is
/// looked up without them (`std::shared_ptr`), and every declaration of it must be a type — the ordinary case for a class
/// template, whose first declaration is a forward one, so the singular query answers `Ambiguous` and the plural one says
/// whether they agree about being a class.
/// **The name before a template-id's arguments** — `make_sized<3>` → `make_sized`, and `None` for anything else.
///
/// The rule is C++'s own spelling and nothing more: a name-like prefix, a `<`, and a `>` that ends the text. A member
/// access and an operator are not touched — the caller asks this only of a callee whose ordinary lookup answered nothing.
fn the_name_before_its_template_arguments(callee: &cpp_parser::CppSyntaxNode) -> Option<String> {
    let kind = CppSyntaxKind::from(callee.kind());
    if !matches!(
        kind,
        CppSyntaxKind::NameExpr | CppSyntaxKind::IdentifierExpr
    ) {
        return None;
    }
    let text = callee.text().to_string();
    let text = text.trim();
    let open = text.find('<')?;
    if open == 0 || !text.ends_with('>') {
        return None;
    }
    let name = &text[..open];
    let names_something = name
        .chars()
        .all(|character| character.is_alphanumeric() || character == '_' || character == ':');
    names_something.then(|| name.to_string())
}

/// **The ranges algorithm a callee names** — `std::ranges::find`, `ranges::find`.
///
/// The name is read from the spelling the call wrote, and only the `std::ranges` family is recognised: a project's own
/// `find` is a function whose declaration the ordinary path reads, and answering it from a table would be a guess.
fn a_ranges_algorithm_the_call_names(callee: &cpp_parser::CppSyntaxNode) -> Option<String> {
    let written = callee.text().to_string();
    let written = written.trim();
    let last = written.rsplit("::").next()?;
    // **A call written in the ranges namespace's own spelling** — `std::ranges::find`, `ranges::find`. A bare `find`
    // is left to the ordinary path: a project declares one as often as not, and the table would take it.
    let in_the_ranges_namespace = written.contains("ranges::");
    let is_an_algorithm = matches!(
        last,
        "find"
            | "find_if"
            | "find_if_not"
            | "max"
            | "min"
            | "max_element"
            | "min_element"
            | "count"
            | "count_if"
            | "distance"
            | "size"
            | "ssize"
            | "subrange"
            | "lower_bound"
            | "upper_bound"
            | "equal_range"
            | "search"
    );
    (in_the_ranges_namespace && is_an_algorithm).then(|| last.to_string())
}

fn a_callee_that_names_a_type(
    index: &ProjectIndex,
    path: &Path,
    callee: &cpp_parser::CppSyntaxNode,
) -> Option<String> {
    let spelled = callee.text().to_string();
    let spelled = spelled.trim();
    if spelled.is_empty() || spelled.contains(' ') {
        return None;
    }
    let bare = match spelled.find('<') {
        Some(at) => spelled[..at].trim(),
        None => spelled,
    };
    let names_a_type = match index.definition(bare, path) {
        Known::Yes(found) => found.fact.kind == crate::DeclKind::Type,
        Known::Unknown(UnknownReason::Ambiguous(_)) => {
            index.definitions(bare, path).value().is_some_and(|found| {
                !found.found.is_empty()
                    && found
                        .found
                        .iter()
                        .all(|declaration| declaration.fact.kind == crate::DeclKind::Type)
            })
        }
        Known::Unknown(_) | Known::No => false,
    };
    names_a_type.then(|| spelled.to_string())
}

/// **The spellings a call's callee may be declared under** — its own text without the template arguments, and its last
/// `::` segment. `std::to_string(count)`'s callee is `std::to_string` and `to_string`, two names the index may hold.
fn the_names_the_call_may_use(callee: &cpp_parser::CppSyntaxNode) -> Vec<String> {
    let spelled = callee.text().to_string();
    let spelled = spelled.trim();
    // **The template arguments are not part of the name**: `get<int>` is `get`, and `<int>` is what the call *wrote*.
    let bare = match spelled.find('<') {
        Some(at) => spelled[..at].trim(),
        None => spelled,
    };
    let last = bare.rsplit("::").next().unwrap_or(bare);
    let mut names = vec![bare.to_string()];
    if last != bare {
        names.push(last.to_string());
    }
    names
}

/// **What an overload set returns, when every candidate the call could reach agrees.**
///
/// A name declared more than once answers `Ambiguous` to the name query — right for "where is this declared" and wrong for
/// "what does this call return", because the call's own arguments choose. Two questions narrow the set, and neither is a
/// guess:
///
/// * **can this candidate be called this way** — the arity fits and every parameter takes the argument in its position. Only
///   a *definite* refusal drops a candidate (`sema::convert::conversion`'s `Refused`); one this layer cannot compare keeps
///   its place, because dropping it would be the same guess in the other direction;
/// * **do the survivors say the same type** — their return spellings, with the call's **written** template arguments
///   substituted in, read as `auto` would read them (no top-level reference, no `const`).
///
/// `std::to_string(count)` has five overloads and the one taking an `int` answers `std::string`; `std::get<int>(either)` has
/// two left once the unexpanded spelling is dropped, and both say `int` — with and without a reference, which `auto` then
/// removes. A spelling that still holds a template-id after substitution (`variant_alternative_t<int, …>`) names a trait this
/// cannot evaluate, so it is **dropped** rather than compared: it would disagree with every concrete answer for a reason that
/// is not about the type. A set that still disagrees answers `None` — choosing between them is overload *ranking*, which this
/// layer does not do.
fn the_return_the_overloads_agree_on(
    index: &ProjectIndex,
    path: &Path,
    names: &[String],
    written_arguments: &[Type],
    argument_types: &[Type],
    how_many_arguments: usize,
) -> Option<String> {
    for name in names {
        let Known::Yes(found) = index.definitions(name, path) else {
            continue;
        };
        let mut agreed: Option<String> = None;
        let mut any = false;
        for candidate in found
            .found
            .iter()
            .filter(|declaration| declaration.fact.kind == crate::DeclKind::Function)
        {
            // **A deleted function is not a candidate** — [dcl.fct.def.delete]: it participates in overload resolution
            // only to make the call ill-formed. `std::make_unique` declares
            // `template <class T, class... Args> void make_unique(Args&&...) = delete;` to stop `make_unique<T[]>(…)`,
            // and keeping it made the set disagree with the two real overloads around it.
            if candidate
                .fact
                .modifiers
                .contains(crate::summary::DeclModifiers::DELETED)
            {
                continue;
            }
            let Some(written) = candidate.fact.returns.as_deref() else {
                continue;
            };
            if !a_candidate_that_can_be_called_this_way(
                candidate.fact.parameter_list.as_deref(),
                argument_types,
                how_many_arguments,
            ) {
                continue;
            }
            let substituted =
                if written_arguments.is_empty() || candidate.fact.parameters.is_empty() {
                    written.to_string()
                } else {
                    let arguments: Vec<String> = written_arguments
                        .iter()
                        .map(|one| one.to_string())
                        .collect();
                    crate::sema::types::substituted_spelling(
                        written,
                        &candidate.fact.parameters,
                        &arguments,
                    )
                };
            // **A spelling that still names one of the candidate's own parameters could not be substituted** —
            // `variant_alternative_t<int, variant<_Types...>>` keeps `_Types` — and comparing it with a concrete
            // answer would make every set holding such an overload disagree for a reason that is not about the type.
            let still_unsubstituted =
                candidate.fact.parameters.iter().any(|parameter| {
                    !parameter.is_empty() && substituted.contains(parameter.as_str())
                });
            if still_unsubstituted {
                continue;
            }
            let read_as_auto_reads_it = read_the_way_auto_does(&substituted);
            if read_as_auto_reads_it.is_empty() {
                continue;
            }
            any = true;
            match &agreed {
                None => agreed = Some(read_as_auto_reads_it),
                Some(previous) if *previous == read_as_auto_reads_it => {}
                Some(_) => return None,
            }
        }
        if any && agreed.is_some() {
            return agreed;
        }
    }
    None
}

/// **Can a call with this many arguments, of these types, reach this parameter list?**
///
/// Arity first — a **parameter pack** accepts any count from its position on — and then each parameter in turn, when the
/// arguments could be typed at all. A call that wrote its template arguments (`std::get<int>(either)`) has no
/// `argument_types` to compare, and its arity is still known: the counts are checked, the conversions are not.
fn a_candidate_that_can_be_called_this_way(
    parameter_list: Option<&str>,
    argument_types: &[Type],
    how_many_arguments: usize,
) -> bool {
    let Some(parameter_list) = parameter_list else {
        // **A declaration with no recorded list has no vote.** It cannot be refused either, so it is skipped rather
        // than kept: `std::make_unique` has a `void`-returning declaration with no parameter list recorded, and keeping
        // it made every set holding such a declaration disagree with the concrete answers around it.
        return false;
    };
    let parameters = crate::sema::overload::parameters_in(parameter_list).0;
    // **A pack is recognised from the written list**, because `parameters_in` strips the `...`: `(_Types&&... _Args)`
    // comes back as one parameter, `_Types&&`, and reading that as an exact arity dropped every variadic candidate
    // — measured, `std::make_unique<Closing>()` answered nothing while two of its three overloads agree on the type.
    let a_pack = parameter_list.contains("...");
    if a_pack {
        let fixed = parameters.len().saturating_sub(1);
        if how_many_arguments < fixed {
            return false;
        }
    } else if parameters.len() != how_many_arguments {
        return false;
    }
    if argument_types.len() != how_many_arguments {
        // The arguments could not be typed (the call wrote its template arguments instead), and the counts are all there
        // is to check.
        return true;
    }
    parameters
        .iter()
        .zip(argument_types)
        .all(|(parameter, argument)| {
            !crate::sema::convert::conversion(argument, parameter, |_| None).is_refused()
        })
}

/// **The type `auto` would give this spelling** — no top-level reference and no `const`, which is what `auto x = f();` keeps.
fn read_the_way_auto_does(written: &str) -> String {
    let mut spelling = written.trim();
    while let Some(rest) = spelling.strip_prefix("const ") {
        spelling = rest.trim();
    }
    while let Some(rest) = spelling.strip_suffix('&') {
        spelling = rest.trim();
    }
    spelling.to_string()
}

/// The types a callee's own `<…>` names, when it wrote one.
///
/// An empty list is what both "no argument list" and "an argument list this could not read" give, and the caller's
/// only use for it is a positional substitution — substituting nothing is what it already does when there is nothing
/// to substitute, so the two need not be told apart.
/// **The element type an iterator-producing member call yields** — `v.begin()`, `m.find(k)`, `m.lower_bound(k)`.
///
/// `None` for every other call, which is the ordinary case and stays cheap: one member lookup and a name test.
fn iterator_element_type(
    memo: &TypeMemo,
    index: &ProjectIndex,
    declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    callee: &cpp_parser::CppSyntaxNode,
) -> Option<Known<(Type, PathBuf)>> {
    let member = crate::sema::resolve::member_access_at(root, end_of_the_written_name(callee))?;
    if !matches!(
        member.member.as_str(),
        "begin"
            | "cbegin"
            | "rbegin"
            | "end"
            | "cend"
            | "rend"
            | "find"
            | "lower_bound"
            | "upper_bound"
    ) {
        return None;
    }

    let Known::Yes((object, file)) = type_of_expression_memoed(
        memo,
        index,
        declaring,
        scopes,
        root,
        path,
        &member.object,
        0,
    ) else {
        return None;
    };

    let element = range_element_of(&object)?;
    Some(Known::Yes((
        crate::sema::types::parse_type_spelling(&element),
        file,
    )))
}

fn written_template_arguments(callee: &cpp_parser::CppSyntaxNode) -> Vec<Type> {
    let Some(list) = callee
        .descendants()
        .find(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::TemplateArgumentList)
    else {
        return Vec::new();
    };

    crate::sema::types::read_template_arguments(&list)
}

/// **The scope a bare class name was declared in**, as `scope::name`, from the index.
///
/// The companion of the note in [`member_fact`]: a member query arrives with the spelling the *use* wrote, and an
/// unqualified one names a class whose declaration is filed under a scope the use did not spell out. This is the
/// step that recovers it — by bare name, over the files visible from `from`, taking the first declaration that has
/// a scope at all.
///
/// `None` when nothing declares the name, or when the only declaration has no scope (a class at file scope is
/// already spelled correctly, and qualifying it would look for `::Widget`).
pub(crate) fn qualified_from_the_index(
    index: &ProjectIndex,
    from: &Path,
    class: &str,
) -> Option<String> {
    // **A spelling that already writes its namespace is the index's own.** Qualifying it again produced
    // `std::std::unique_ptr` — measured on `classes.cpp`'s `clone->describe()`, whose receiver is already
    // `std::unique_ptr<Base>` — and every member query after it was about a class nothing declares.
    if class.contains("::") {
        return None;
    }
    // **A *type* called that, not the first thing called that.** `files_declaring` is a name lookup, and a class's
    // name is also its constructors': `std::shared_ptr` has a dozen facts named `shared_ptr` whose scope is
    // `std::shared_ptr` itself — qualifying from one of those gives `std::shared_ptr::shared_ptr`, a class nothing
    // declares, and every member query after it answers nothing. Measured: this function is what turned
    // `shared_ptr<Resource>` into a class with **0 members** while `std::shared_ptr<Resource>` answered **39**, and
    // the hover on `locked->identifier()` said "has no member" because of it. The question here is a *class* spelling,
    // so the declaration has to be the class.
    let declared = index.files_declaring(class, from);
    let found = declared
        .into_iter()
        .find(|declared| declared.fact.kind == crate::DeclKind::Type)?;
    let scope = found.fact.scope.as_deref()?;
    (!scope.is_empty()).then(|| format!("{scope}::{class}"))
}

/// The declaration a **callee expression** names — `make` in `make()`, `fac.build` in `fac.build()`.
///
/// The two lookups a call needs, in one place: a member access goes through the member lookup (the object's type,
/// then the member in it), everything else through the name lookup. The callers differ only in what they then ask
/// of the declaration — [`type_of_a_call`] wants what a call of it *has*, a parameter hint wants the parameters
/// it declares — and neither is a reason for a second copy of the resolution.
///
/// `written` is the **call's** spelling rather than the callee's, and it is what the `Unknown` answers carry: a
/// consumer reporting "not known" should name the code the user wrote, not the half of it the lookup started at.
fn declaration_of_a_callee(
    memo: &TypeMemo,
    index: &ProjectIndex,
    declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    callee: &cpp_parser::CppSyntaxNode,
    written: &str,
) -> Known<NamedDeclaration> {
    // A member call: the object's type, then the member's declaration.
    if let Some(access) = crate::sema::resolve::member_access_of(callee) {
        let object = match type_of_expression_memoed(
            memo,
            index,
            declaring,
            scopes,
            root,
            path,
            &access.object,
            0,
        ) {
            Known::Yes((type_of, _)) => type_of,
            Known::Unknown(reason) => return Known::Unknown(reason),
            Known::No => return Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
        };

        // **The class the arrow reaches, not the object's own class.** `lineIndex->GetTotalLine()` on a
        // `std::shared_ptr<LineIndex>` asks `LineIndex` for `GetTotalLine`; asking the smart pointer itself answered
        // `Unknown(NotDeclaredHere("std::shared_ptr::GetTotalLine"))` — measured on a real project, and the reason a
        // hover on `auto totalLine = lineIndex->GetTotalLine();` said the type "could not be typed". One
        // implementation of the rule: [`crate::completion::the_class_after_the_operator`], which pointer
        // completion has used since the smart pointers landed.
        let class = if access.arrow
            && let Some((reached, _)) = crate::completion::the_class_after_the_operator(
                index, scopes, root, path, &object, true,
            ) {
            reached
        } else {
            let Some(own) = member_access_class(&object) else {
                return Known::Unknown(UnknownReason::UnknownType(Box::from(object.to_string())));
            };
            own
        };
        // The class and the arguments **together**, which is the step this caller used to do half of: it paired
        // the class's parameters with the arguments the *use* wrote, and a use that wrote none (`std::string`)
        // therefore had none — while the same question asked of the same object from `type_of_expression` had
        // `char&`. One question, one reader.
        let (class, arguments) =
            member_access_class_and_arguments(index, scopes, root, path, &class, &object);
        let bindings = member_bindings(index, scopes, root, path, &class, &arguments);

        if crate::probes::inference() {
            eprintln!(
                "[inference] callee: object {object:?} -> class {class:?}, arguments {arguments:?}, bindings empty {}",
                bindings.is_empty()
            );
        }
        // The arguments as **spellings**, for the pattern rule — see [`direct_member`].
        let written_arguments: Vec<String> = arguments
            .iter()
            .map(|argument| argument.to_string())
            .collect();
        return match member_fact(
            index,
            scopes,
            root,
            path,
            &class,
            &access.member,
            Some(&written_arguments),
        ) {
            Known::Yes((fact, file)) => Known::Yes(NamedDeclaration::Indexed(fact, file, bindings)),
            Known::Unknown(reason) => Known::Unknown(reason),
            Known::No => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
        };
    }

    // Everything else is a name — `make()`, `Widget()`, `ns::make()` — and the name lookup is the one every other
    // **Several declarations of this name in this file, and a call that selects one of them.** `definition_at` answers
    // the *first* declaration of a name in one scope — the rule for a name, documented beside it — and for a call that
    // is wrong: `std::format("x {}", 1)` and `std::format(L"x {}", 1)` reach different overloads of one name, and only
    // the arguments say which. Both halves (this one and the index's, below) go through the same ranking.
    if let Some(call) = the_call_around(callee)
        && let Known::Yes(bindings) =
            crate::sema::resolve::definitions_at(scopes, root, end_of_the_written_name(callee))
        && bindings.len() > 1
        && let Some(types) =
            the_types_of_the_arguments(memo, index, declaring, scopes, root, path, &call)
    {
        let candidates: Vec<(DeclFact, PathBuf)> = bindings
            .iter()
            .map(|binding| (fact_from_binding(root, "", binding), path.to_path_buf()))
            .collect();
        let explicit_arguments: Vec<String> = call
            .children()
            .next()
            .map(|callee| written_template_arguments(&callee))
            .unwrap_or_default()
            .iter()
            .map(Type::to_string)
            .collect();
        if let Some(chosen) = the_one_the_arguments_select(&types, &candidates, &explicit_arguments)
            && let Some(binding) = bindings.get(chosen)
        {
            return Known::Yes(NamedDeclaration::Here(binding.clone()));
        }
    }

    // **C++'s unqualified member lookup, asked where the language puts it.**
    //
    // Inside a member function a name is looked up in the class and its bases **before** the enclosing namespaces —
    // `shared_from_this()` in a class deriving `std::enable_shared_from_this<Node>` is
    // `std::enable_shared_from_this<Node>::shared_from_this`, which no scope in the file declares. It has to come before
    // the index-wide name query, because that query resolves the base's declaration in its own header and answers the
    // **written** fact (`T *`), while the member list substitutes the class's arguments through it (`Node *`).
    //
    // Two conditions keep this from taking an answer that was already better: the file's own scopes must answer
    // **nothing** (a local variable, or a member declared here, keeps the scope tree's answer), and the class's member
    // must be finished (a member of a template base whose arguments the member list could not read is refused).
    if matches!(
        crate::sema::resolve::definition_at(scopes, root, end_of_the_written_name(callee)),
        Known::No | Known::Unknown(UnknownReason::NotDeclaredHere(_))
    ) && let Some(member) =
        a_member_of_the_enclosing_class(index, scopes, root, path, callee, true)
    {
        return Known::Yes(NamedDeclaration::Indexed(
            member.fact,
            member.file,
            crate::sema::types::TypeBindings::new(Vec::new(), Vec::new()),
        ));
    }

    // **A callee written as a template-id names the function before its `<`.** `make_sized<3>()` is a call of
    // `make_sized`, and the written arguments are read by `type_of_a_call`, which passes them to `what_a_call_has` for
    // substitution — but the name query was asked about `make_sized<3>`, which is no declaration's name, so the call had
    // no type at all (measured: `make_sized<3>().size()` reported the type as unknown while `std::array<int, 3>`'s members
    // were listable). The retry is one index query, and only when the ordinary lookup found nothing.
    let known = declaration_of_expression(index, scopes, root, path, callee);
    let known = match &known {
        Known::No
        | Known::Unknown(UnknownReason::NotDeclaredHere(_))
        | Known::Unknown(UnknownReason::Ambiguous(_)) => {
            match the_name_before_its_template_arguments(callee) {
                // **The scope tree first, by offset.** It is the reader that resolves a namespaced name —
                // `test_cpp::make_sized` is not reachable by `index.definition("make_sized")` — and it places the name
                // whose template-id the file wrote.
                Some(bare) => {
                    let start = usize::from(callee.text_range().start());
                    match crate::sema::resolve::definition_at(scopes, root, start + bare.len()) {
                        Known::Yes(binding) => Known::Yes(NamedDeclaration::Here(binding)),
                        _ => match index.definition(&bare, path) {
                            Known::Yes(found) => Known::Yes(NamedDeclaration::Indexed(
                                found.fact,
                                found.file,
                                crate::sema::types::TypeBindings::new(Vec::new(), Vec::new()),
                            )),
                            Known::Unknown(reason) => Known::Unknown(reason),
                            Known::No => Known::No,
                        },
                    }
                }
                // **Nothing was retried, so nothing is replaced.** An `Ambiguous` name stays ambiguous: the call's own
                // arguments are what picks one, and that question is asked below.
                None => known,
            }
        }
        _ => known,
    };

    // **A name with several declarations, and a call that selects one of them.** `std::format("…", value)` is four
    // overloads — narrow and wide, with and without a locale — and the name lookup is right to refuse to pick. What
    // was missing is that the *call* is the tie-breaker: the arguments' types are exactly what a compiler uses, and
    // the ranking for them already exists (it is what the signature popup and the hover's `→` marker use). Without
    // this, `auto enenn = std::format(…)` had no initializer type and therefore no type at all.
    let Known::Unknown(UnknownReason::Ambiguous(name)) = &known else {
        return known;
    };
    // **The call this callee belongs to, however many expression nodes sit between them** — `std::format` parses as
    // a name inside the call, and a member callee as a member access inside it, so the search is up the parents
    // rather than one `parent()`.
    let Some(call) = the_call_around(callee) else {
        return known;
    };
    match the_declaration_the_arguments_pick(
        memo,
        index,
        declaring,
        scopes,
        root,
        path,
        &call,
        name.as_ref(),
    ) {
        Some((fact, file)) => Known::Yes(NamedDeclaration::Indexed(
            fact,
            file,
            TypeBindings::default(),
        )),
        None => known,
    }
}

/// Where a call's callee is declared — what a parameter hint is read from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Callee {
    /// The file the declaration is written in.
    pub file: PathBuf,
    /// The offset of the declared **name** in that file.
    pub name_offset: usize,
    /// **The declaration's parameter list as the index already holds it**, parentheses included — the fallback a
    /// signature popup uses when that file has no *rendering* to read the list out of.
    ///
    /// The two are not the same source: `name_offset` is an offset into the file's **cooked rendering**, so a caller
    /// that has only the file's own text cannot read a parameter list at it — and a query may not build a rendering
    /// (65–190 ms for a standard-library header). Measured on a real C++23 module project: `math::add(` answered
    /// **no signatures at all** on the first request and only after a second `(` had queued and built the interface
    /// unit's rendering — which is what "the signature popup almost never appears" looks like from the outside.
    ///
    /// `None` for a declaration whose fact was built before the field existed — the popup then says nothing, which
    /// is the old behaviour rather than a wrong label.
    pub parameters: Option<String>,
}

/// **Every declaration a call's callee names** — one for an ordinary function, all of them for an overload set.
///
/// [`callee_of_a_call`] is the singular question ("where is *the* function this calls") and it is the right one for
/// a parameter *hint*, which labels one declaration's parameters. It is the wrong one for signature help: a call to
/// an overloaded function has several answers, the protocol's `SignatureHelp` carries a **list**, and declining with
/// `Ambiguous` — which is what this analysis did — leaves a reader typing `std::format(` with nothing at all.
/// Measured on the project this was written against: `std::format` is four overloads, so the popup was empty.
///
/// # What is plural, and what is not
///
/// A **name** goes through the plural lookup ([`ProjectIndex::definitions`]), which is the query that exists for
/// exactly this: it answers with every declaration of the name the cursor can see, in file order, each carrying the
/// fact — including the parameter list, which is what a signature is rendered from.
///
/// A **member call** (`s.push_back(`) goes through [`members_of`], the class's whole member list, filtered by the
/// name written — **bases included**, which is what a member call needs and what `direct_member` alone does not
/// give: `std::string::push_back` is two overloads, and a class that inherits an overloaded member inherits all of
/// it. The object's type is worked out exactly as the singular path works it out, because that is the question the
/// two share.
pub(crate) fn callees_of_a_call(
    index: &ProjectIndex,
    declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    call: &cpp_parser::CppSyntaxNode,
) -> Known<Vec<Callee>> {
    let memo = TypeMemo::default();
    let written = call.text().to_string();
    let written = written.trim();

    let Some(callee) = call.children().next() else {
        return Known::Unknown(UnknownReason::UnknownType(Box::from(written)));
    };

    if let Some(access) = crate::sema::resolve::member_access_of(&callee) {
        let members = member_callees(&memo, index, declaring, scopes, root, path, &access);

        // A member whose set could not be listed — the object's type is unknown, the class is not declared
        // anywhere the index can see — falls back to the singular path, which reports *why* rather than an empty
        // list. An empty list and an unanswerable question are different answers.
        return match members {
            Known::Yes(found) if !found.is_empty() => Known::Yes(found),
            other => match other {
                Known::Unknown(reason) => Known::Unknown(reason),
                _ => match callee_of_a_call(index, declaring, scopes, root, path, call) {
                    Known::Yes(one) => Known::Yes(vec![one]),
                    Known::Unknown(reason) => Known::Unknown(reason),
                    Known::No => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
                },
            },
        };
    }

    // Everything else is a name — `make`, `ns::make`, `std::format`. The qualified spelling a name resolves to is
    // what the index is asked about, and it is the answer's *failure* shapes that carry it: a name this file cannot
    // place is either absent from the index or declared there more than once, and both are questions for the plural
    // lookup.
    let offset = end_of_the_written_name(&callee);

    match crate::sema::resolve::definitions_at(scopes, root, offset) {
        // Declared in this buffer: every overload of it, and the file being edited is where they are. **All** of
        // them, which is the whole point of this function: `void scale(int); double scale(double, int);` in one
        // file is one name with two declarations in one scope, and a signature list that showed one of them would
        // be the old behaviour with extra steps.
        Known::Yes(bindings) if !bindings.is_empty() => Known::Yes(
            bindings
                .iter()
                .map(|binding| Callee {
                    file: path.to_path_buf(),
                    name_offset: binding.name_range.start_offset,
                    // The buffer is parsed in front of the caller, so its own list is read from the tree — the
                    // fallback exists for a declaration in a file nobody has cooked.
                    parameters: None,
                })
                .collect(),
        ),
        Known::Yes(_) => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
        Known::Unknown(UnknownReason::NotDeclaredHere(name))
        | Known::Unknown(UnknownReason::Ambiguous(name)) => match index.definitions(&name, path) {
            Known::Yes(found) => Known::Yes(
                found
                    .found
                    .iter()
                    .map(|declaration| Callee {
                        file: declaration.file.clone(),
                        name_offset: declaration.fact.name_range.start_offset,
                        parameters: declaration.fact.parameter_list.clone(),
                    })
                    .collect(),
            ),
            Known::Unknown(reason) => Known::Unknown(reason),
            Known::No => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
        },
        Known::Unknown(reason) => Known::Unknown(reason),
        Known::No => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
    }
}

/// **The `CallExpr` a callee belongs to**, looking up the parents a few levels — see its first caller.
fn the_call_around(callee: &cpp_parser::CppSyntaxNode) -> Option<cpp_parser::CppSyntaxNode> {
    let mut node = callee.parent();
    for _ in 0..4 {
        let inner = node?;
        if cpp_parser::CppSyntaxKind::from(inner.kind()) == cpp_parser::CppSyntaxKind::CallExpr {
            return Some(inner);
        }
        node = inner.parent();
    }
    None
}
/// **Which declaration a call's own arguments select**, when the callee's name has more than one.
///
/// The engine used to stop at "several declarations" for a free function, and that is where `auto enenn =
/// std::format(FULL_NAME_FORMAT, myName.getFullName(0));` lost its type: `std::format` has four overloads visible from
/// that file (narrow and wide, with and without a locale) and nothing chose between them, so `auto` had no initializer
/// type to deduce from. The ranking machinery already existed — it is what the signature popup and the hover's `→`
/// marker use ([`crate::sema::overload::choose`]) — and what was missing was asking it here.
///
/// This is the **index** half: the declarations are in other files and the name is qualified. The same-file half is in
/// [`declaration_of_a_callee`], which has bindings rather than facts, and both go through
/// [`the_one_the_arguments_select`] so that the two decide alike.
fn the_declaration_the_arguments_pick(
    memo: &TypeMemo,
    index: &ProjectIndex,
    declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    call: &cpp_parser::CppSyntaxNode,
    name: &str,
) -> Option<(DeclFact, PathBuf)> {
    // **The spelling a call writes is not the spelling the index stores.** `std::make_unique<Resource>(1)` carries its
    // template arguments in the name the ambiguity reports, and `definitions("std::make_unique<Resource>")` finds
    // nothing — measured — so the selection never ran at all. The arguments are the call's, not the declaration's name.
    let name = the_name_without_its_arguments(name);
    let Known::Yes(definitions) = index.definitions(name, path) else {
        return None;
    };
    if definitions.found.len() < 2 {
        return None;
    }
    let candidates: Vec<(DeclFact, PathBuf)> = definitions
        .found
        .iter()
        .map(|definition| (definition.fact.clone(), definition.file.clone()))
        .collect();
    let types = the_types_of_the_arguments(memo, index, declaring, scopes, root, path, call)?;
    let explicit_arguments: Vec<String> = call
        .children()
        .next()
        .map(|callee| written_template_arguments(&callee))
        .unwrap_or_default()
        .iter()
        .map(Type::to_string)
        .collect();
    let chosen = the_one_the_arguments_select(&types, &candidates, &explicit_arguments)?;
    candidates.get(chosen).cloned()
}

/// **A call's callee without the template arguments the call wrote** — the spelling the index keys a name on.
///
/// `std::make_unique<Resource>` → `std::make_unique`, and `A<B<C>>::f` stays whole: the arguments are stripped only
/// when the first `<`'s matching `>` is the **last** character, which is exactly the shape a call's argument list
/// leaves. Anything else is part of the name (`A<B<C>>::f` has a `::` after its arguments), and cutting there would
/// name a different entity.
fn the_name_without_its_arguments(written: &str) -> &str {
    let Some(open) = written.find('<') else {
        return written;
    };
    let mut depth = 0i32;
    for (at, character) in written[open..].char_indices() {
        match character {
            '<' => depth += 1,
            '>' => {
                depth -= 1;
                if depth == 0 {
                    let close = open + at;
                    return if close + character.len_utf8() == written.len() {
                        &written[..open]
                    } else {
                        written
                    };
                }
            }
            _ => {}
        }
    }
    written
}
/// **The types of a call's arguments**, as spellings — `Unknown` for an argument whose type the engine cannot read.
fn the_types_of_the_arguments(
    memo: &TypeMemo,
    index: &ProjectIndex,
    declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    call: &cpp_parser::CppSyntaxNode,
) -> Option<Vec<Known<String>>> {
    let arguments = crate::inlay::arguments_of(call)?;
    Some(
        arguments
            .iter()
            .map(|argument| {
                match type_of_expression_memoed(
                    memo, index, declaring, scopes, root, path, argument, 0,
                ) {
                    Known::Yes((type_of, _)) => Known::Yes(type_of.to_string()),
                    Known::No => Known::No,
                    Known::Unknown(reason) => Known::Unknown(reason),
                }
            })
            .collect(),
    )
}

/// **Which of these declarations the arguments select**, as an index into `candidates`.
///
/// # The tie the ranker leaves, and the one it is allowed to break
///
/// `std::format`'s narrow and wide overloads are spelled `format(const format_string<_Types...> _Fmt, _Types&&...
/// _Args)` and the same with `wformat_string`; against a call's arguments the ranker answers `Ambiguous`, because the
/// character width of the format string is a property of the *class* those parameters have, not of their spelling. The
/// tie-break here is the one a reader makes: **the argument's character width selects the family** — a narrow string
/// cannot construct a `wformat_string` and a wide one cannot construct a `format_string` — so when exactly one
/// candidate's *first* parameter is written for the width the call writes, that candidate is the answer. If several
/// are (or none is definite), the tie stands and the caller keeps its `Ambiguous`: a tie between two candidates of the
/// same width is a real one.
fn the_one_the_arguments_select(
    types: &[Known<String>],
    candidates: &[(DeclFact, PathBuf)],
    explicit_arguments: &[String],
) -> Option<usize> {
    // **A deleted declaration cannot be the meaning of a call this layer reports.** `std::make_unique` has a third
    // overload `= delete`d so that arrays are rejected ([memory.syn]); it ties with the real one on every argument, and
    // keeping it in the running is what made `auto unique = std::make_unique<Resource>(1);` ambiguous and left the
    // variable with no type. `usable` holds the original indices, in the order the ranking sees them.
    let usable: Vec<usize> = (0..candidates.len())
        .filter(|at| {
            !candidates[*at]
                .0
                .modifiers
                .contains(crate::DeclModifiers::DELETED)
        })
        .collect();
    if usable.is_empty() {
        // Every candidate is deleted: the call is ill-formed whichever one it means, and "no answer" is the honest
        // report of that.
        return None;
    }
    let built: Vec<crate::sema::overload::Candidate> = usable
        .iter()
        .enumerate()
        .map(|(at, &index)| {
            let (fact, _) = &candidates[index];
            let (declared, variadic) = fact
                .parameter_list
                .as_deref()
                .map(crate::sema::overload::parameters_in)
                .unwrap_or_default();
            let names = fact.parameters.clone();
            let declared_for_ordering = declared.clone();
            // **The deduction starts from what the call wrote.** `std::make_unique<Resource>(1)` states `_Tp` as
            // `Resource`; without that seed the candidate's every parameter stayed unbound and it ranked `Unranked`.
            let substituted = match crate::sema::deduction::deduce_with_written(
                &names,
                &declared,
                types,
                explicit_arguments,
            ) {
                Some(deduced) => (
                    declared
                        .iter()
                        .map(|spelling| {
                            crate::sema::types::substituted_spelling(spelling, &names, &deduced)
                        })
                        .collect::<Vec<String>>(),
                    true,
                ),
                None => (declared, !names.is_empty()),
            };
            let candidate = crate::sema::overload::Candidate::new(
                substituted.0,
                variadic,
                format!("declaration {at}"),
            );
            if substituted.1 {
                candidate.with_declaration(declared_for_ordering, names)
            } else {
                candidate
            }
        })
        .collect();

    if crate::probes::inference() {
        eprintln!(
            "[inference] pick among {} candidates ({} usable), argument types {types:?} written {explicit_arguments:?}",
            candidates.len(),
            usable.len()
        );
        for (at, (fact, _)) in candidates.iter().enumerate() {
            eprintln!(
                "[inference]   candidate {at}: bits={} deleted={} params={:?}",
                fact.modifiers.bits(),
                fact.modifiers.contains(crate::DeclModifiers::DELETED),
                fact.parameter_list
            );
        }
        for (at, (fact, _)) in candidates.iter().enumerate() {
            eprintln!(
                "[inference]   candidate {at}: scope {:?} returns {:?} params {:?}",
                fact.scope, fact.returns, fact.parameter_list
            );
        }
    }
    let choice = crate::sema::overload::choose(types, &built);
    if crate::probes::inference() {
        eprintln!("[inference]   choice: {choice:?}");
    }
    match choice {
        // The rank is a position in `built`, which is `usable`'s order — the original index is what the caller wants.
        crate::sema::overload::Choice::One(at) => usable.get(at).copied(),
        crate::sema::overload::Choice::Ambiguous => {
            let written = types.iter().find_map(|argument| match argument {
                Known::Yes(spelling) => the_character_width(spelling),
                _ => None,
            })?;
            let definite: Vec<usize> = usable
                .iter()
                .filter(|at| {
                    let (fact, _) = &candidates[**at];
                    fact.parameter_list
                        .as_deref()
                        .and_then(|list| {
                            crate::sema::overload::parameters_in(list)
                                .0
                                .into_iter()
                                .next()
                        })
                        .and_then(|first| the_character_width(&first))
                        == Some(written)
                })
                .copied()
                .collect();
            match definite[..] {
                [only] => Some(only),
                _ => None,
            }
        }
        crate::sema::overload::Choice::None => None,
    }
}
/// **Is this spelling written for wide characters, narrow ones, or neither?** — the tie-break
/// [`the_declaration_the_arguments_pick`] uses, and nothing else does.
///
/// `wchar_t` contains `char` and `wstring` contains `string`, so the wide spellings are asked first. `None` for a
/// spelling that says neither (`int`, `pair<A, B>`), which keeps such a candidate in the running.
fn the_character_width(spelling: &str) -> Option<bool> {
    if spelling.contains("wchar_t")
        || spelling.contains("wstring")
        || spelling.contains("wformat")
        || spelling.contains("wint_t")
    {
        return Some(true);
    }
    if spelling.contains("char") || spelling.contains("string") {
        return Some(false);
    }
    None
}
/// **Every declaration of one member name in the object's class** — the member-call half of [`callees_of_a_call`].
///
/// The class comes from the object's **type**, which is the same step [`declaration_of_a_callee`] makes: the two
/// questions differ only in what they then ask for (one member, or all of them), and a second way of working out
/// what `s` is would be a second answer to it.
///
/// `None`-typed objects, unknown types and classes nothing declares are reported as they are —
/// [`UnknownReason`] — rather than as an empty list, for the reason the plural name lookup gives: "there are no
/// members" and "this analysis cannot say" are different answers and a caller shows them differently.
fn member_callees(
    memo: &TypeMemo,
    index: &ProjectIndex,
    declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    access: &crate::sema::resolve::MemberAccess,
) -> Known<Vec<Callee>> {
    let object = match type_of_expression_memoed(
        memo,
        index,
        declaring,
        scopes,
        root,
        path,
        &access.object,
        0,
    ) {
        Known::Yes((type_of, _)) => type_of,
        Known::Unknown(reason) => return Known::Unknown(reason),
        Known::No => {
            return Known::Unknown(UnknownReason::UnknownType(Box::from(
                access.object.text().to_string(),
            )));
        }
    };

    let Some(class) = member_access_class(&object) else {
        return Known::Unknown(UnknownReason::UnknownType(Box::from(object.to_string())));
    };

    // **The member's name is looked up in every class it could come from**, which is what `members_of` answers and
    // what an overloaded member needs: `push_back` is declared twice in `basic_string` itself, and a base's
    // overloads are the derived class's overloads unless something hides them.
    let found = match members_of(index, scopes, root, path, &class) {
        Known::Yes(found) => found,
        Known::Unknown(reason) => return Known::Unknown(reason),
        Known::No => return Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(class))),
    };

    let wanted = &*access.member;
    let candidates: Vec<Callee> = found
        .members
        .iter()
        .filter(|member| member.fact.name == wanted)
        .map(|member| Callee {
            file: member.file.clone(),
            name_offset: member.fact.name_range.start_offset,
            parameters: member.fact.parameter_list.clone(),
        })
        .collect();

    Known::Yes(candidates)
}

/// The declaration a call names, as **a place in a file**: the file it is in, and the offset of its name.
///
/// [`type_of_a_call`]'s question asked for a different answer: "what does a call of this have" needs the
/// declaration's return type, while a parameter hint needs the parameters it declares — and both need the
/// declaration found the same way.
///
/// Nothing is refused here for not being a function. `Widget(1, 2)` and `fp(1)` are calls whose declaration is a
/// class or a variable, and whether either has a parameter list is a question about the *declaration's own
/// declarator*, which the caller asks: a class name has no declarator at all, and a function pointer's parameters
/// belong to its type rather than to the name. Answering "here is the declaration" and letting that reading say
/// "no parameters" keeps one rule instead of two.
///
/// # Why the *name's* offset rather than the declaration's first token
///
/// A caller looking for the parameters finds them in the declarator the name is a name *of*, so it has to start at
/// the name: a `const`, a `static` or a return type is outside the declarator, and a declaration may hold more
/// than one declarator (`void (*f(int a))(int b)`).
pub(crate) fn callee_of_a_call(
    index: &ProjectIndex,
    declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    call: &cpp_parser::CppSyntaxNode,
) -> Known<Callee> {
    let memo = TypeMemo::default();
    let written = call.text().to_string();
    let written = written.trim();

    let Some(callee) = call.children().next() else {
        return Known::Unknown(UnknownReason::UnknownType(Box::from(written)));
    };

    match declaration_of_a_callee(
        &memo, index, declaring, scopes, root, path, &callee, written,
    ) {
        Known::Yes(named) => Known::Yes(Callee {
            file: named.file(path),
            name_offset: named.name_offset(),
            parameters: named.parameter_list(),
        }),
        Known::Unknown(reason) => Known::Unknown(reason),
        Known::No => Known::Unknown(UnknownReason::UnknownType(Box::from(written))),
    }
}

/// The declaration of `member` in the class `class` names, and the file it is in.
///
/// The lookup is the qualified name `<class>::<member>`, which is why nothing here needs to know what a class
/// *is*: the file being edited is asked first through its scope tree, and the index second — the same two-layer
/// split [`definition_across_files`] makes, and for the same reason.
/// **The member a class's `operator->` reaches**, when the class declares one — see the call site in
/// [`member_fact_inner`].
///
/// One level, like the pointer rule: an object whose `operator->` returns another handle is a shape this layer does
/// not follow twice, and a second level would be a guess about which `operator->` the language picked.
/// **A member's written answer, read as a type in the class the member belongs to.**
///
/// `std::vector<T>::operator[]` is declared `reference operator[](size_type)`, and `reference` is `T&` — an alias
/// *inside the class*. Two things have to happen before that is a type a member lookup can ask about:
///
/// 1. the class's parameters are substituted with the arguments the use wrote (`reference` → `_Ty&` → `MarkEvent&`);
/// 2. the alias is read **in this class**, not by its bare name in the index.
///
/// The second is what a real project needs and a fixture does not show: `files_declaring("reference", …)` answers with
/// every class's `reference` — `basic_string`'s, `vector`'s, `_Vector_val`'s — and the first visible one is usually not
/// the one whose member was asked. Measured on EmmyLuaCodeStyle's `Mark.cpp`, where `events[Pos].U` on a
/// `std::vector<MarkEvent>` answered `Unknown(NotDeclaredHere("_Ty"))`: the alias was followed to a *different* class's
/// `reference`, whose `_Ty` nothing substitutes.
fn a_members_answer_as_a_type(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    class_type: &Type,
    returns: &str,
) -> String {
    let Some(class) = class_type.class_name() else {
        return returns.to_string();
    };
    let arguments: Vec<String> = class_type
        .arguments()
        .iter()
        .map(|argument| argument.to_string())
        .collect();
    let parameters = index.template_parameters_for(class, path, &arguments);
    // **A use that writes fewer arguments than the declaration has parameters**, which is the ordinary case:
    // `std::vector<int>` names one of two. The defaults are what the rest stand for — see
    // [`crate::substituted_spelling_with_defaults`], and `lineStartOffset` for the chain that needed it.
    let defaults = index.template_parameter_defaults_for(class, path, &arguments);
    let substituted = crate::sema::types::substituted_spelling_with_defaults(
        returns,
        &parameters,
        &defaults,
        &arguments,
    );

    // **The operators and qualifiers the spelling around the name carries**: `const reference&` is `const T&`, and
    // replacing only the name must keep both ends.
    let (leading, core, trailing) = split_the_operators_of(&substituted);
    if core.is_empty()
        || !core
            .chars()
            .all(|character| character.is_alphanumeric() || character == '_')
    {
        return substituted;
    }

    // **The class's own declaration of that name**, which is the only one whose parameters are the ones in hand.
    let Known::Yes((fact, _)) = member_fact(
        index,
        scopes,
        root,
        path,
        &class_type.to_string(),
        &core,
        None,
    ) else {
        return substituted;
    };
    let Some(target) = fact.type_of.as_deref() else {
        return substituted;
    };
    let target = crate::sema::types::substituted_spelling_with_defaults(
        target,
        &parameters,
        &defaults,
        &arguments,
    );
    // **And the target is a *name* too**, so it is followed before it is answered: `pointer` is `_Val*` in the class
    // that declares it, and `_Alloc_traits::reference` is whatever that alias names. Answering the spelling instead
    // is what made `map::find(text)->second` look `second` up in `_Rb_tree_iterator` rather than in its `pair`.
    let target = a_spelling_through_the_aliases(
        index,
        scopes,
        root,
        path,
        class_type,
        &target,
        MAX_ALIAS_HOPS,
    );
    format!("{leading}{target}{trailing}")
}

/// **How many aliases one spelling may be followed through** — see [`a_spelling_through_the_aliases`].
///
/// Six is past anything the standard library writes (`reference` → `_Alloc_traits::reference` →
/// `allocator_traits<_Alloc>::reference` → `_Tp&` is three), and it is what stops a cyclic `typedef` from looping.
const MAX_ALIAS_HOPS: usize = 6;

/// **A spelling with the aliases a class declares followed through** — `pointer` → `_Val*`, and
/// `_Alloc_traits::reference` → `std::size_t&`.
///
/// # Why this is a step of its own
///
/// A member's recorded type is a **name**: `typedef _Val* pointer;` records `_Val*`, while the use writes `pointer`,
/// and the two are the same type only once the class's parameters are paired with the use's arguments — after which
/// the answer is often *another* name (`_Alloc_traits::reference`) that has to be resolved in the same class again.
/// The layer used to answer the name it found, and every consumer downstream then treated a spelling as a type:
///
/// * `map::find(text)->second` — `_Rb_tree_iterator<_Val>::operator->` answers `pointer`, and the answer was used as
///   the class to look `second` up in: `Unknown(NotDeclaredHere("std::_Rb_tree_iterator::second"))`;
/// * `auto lineStartOffset = _lineOffsetVec[line]` — `vector::reference` is `_Alloc_traits::reference`, and the
///   `auto` variable was typed by that alias rather than by `std::size_t&`.
///
/// # The two shapes, and why `::` is the whole of the rule
///
/// ```text
/// pointer                 a member of this class            ask this class for it
/// _Alloc_traits::reference names `reference` in `_Alloc_traits`, which is a member of this class (an alias, a
///                         base's alias, a nested class)     resolve the qualifier here, then ask *it* for `reference`
/// ```
///
/// `depth` counts the hops, and a hop that would answer the spelling it was given is refused — the honest way to stop
/// on a `typedef` that names itself.
fn a_spelling_through_the_aliases(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    class: &Type,
    written: &str,
    depth: usize,
) -> String {
    if depth == 0 {
        return written.to_string();
    }

    let (leading, core, trailing) = split_the_operators_of(written);
    let a_name = !core.is_empty()
        && core.chars().all(|character| {
            character.is_alphanumeric() || matches!(character, '_' | ':' | '<' | '>' | ',' | ' ')
        });
    if !a_name {
        return written.to_string();
    }

    let Some(class_name) = class.class_name() else {
        return written.to_string();
    };
    let arguments: Vec<String> = class
        .arguments()
        .iter()
        .map(|one| one.to_string())
        .collect();
    let parameters = index.template_parameters_for(class_name, path, &arguments);
    let defaults = index.template_parameter_defaults_for(class_name, path, &arguments);
    if crate::probes::inference() {
        eprintln!(
            "[inference] alias step: {written:?} in {class:?} (class {class_name:?}, parameters {parameters:?}, \
             arguments {arguments:?})"
        );
    }

    // **An unqualified name is a member of this class.**
    let Some((qualifier, last)) = split_at_the_last_scope(&core) else {
        // **The lookup without the arrow fallback** — see [`a_member_the_class_declares`]: this
        // walk is *called from* the arrow path, so asking `member_fact` here asks about an arrow,
        // which comes back here. **An alias template declared elsewhere, before the class is
        // asked.** Following it produces a *qualified* spelling, which the branch below resolves:
        // the class selects the specialization its arguments name, and the member is read there.
        if let Some((named, member)) = the_alias_behind(index, path, &core) {
            let qualified = format!("{named}::{member}");
            if qualified != core {
                let followed = a_spelling_through_the_aliases(
                    index,
                    scopes,
                    root,
                    path,
                    class,
                    &qualified,
                    depth.saturating_sub(1),
                );
                if followed != core {
                    return format!("{leading}{followed}{trailing}");
                }
            }
        }

        let Some(fact) =
            a_member_the_class_declares(index, scopes, root, path, &class.to_string(), &core)
        else {
            return written.to_string();
        };
        let Some(target) = fact.type_of.as_deref() else {
            return written.to_string();
        };
        let target = crate::sema::types::substituted_spelling_with_defaults(
            target,
            &parameters,
            &defaults,
            &arguments,
        );
        if target == core {
            return written.to_string();
        }
        let followed =
            a_spelling_through_the_aliases(index, scopes, root, path, class, &target, depth - 1);
        return format!("{leading}{followed}{trailing}");
    };

    // **A qualified name is a member of whatever the qualifier names** — and the qualifier is itself resolved here,
    // because the library writes it without its namespace (`_Alloc_traits` inside `std`), and **substituted first**,
    // because the qualifier is often a template parameter of the class the member came from:
    // `allocator_traits<_Alloc>` declares `reference` as `typename _Alloc::value_type&`, so `_Alloc` has to become
    // `std::allocator<std::size_t>` before `value_type` can be looked up. Measured on `lineStartOffset`: without
    // this line the chain stops at `_Alloc::value_type&`, with it at `std::size_t&` — the difference between a
    // spelling no reader can use and the type they asked for.
    let qualifier = {
        let substituted = crate::sema::types::substituted_spelling_with_defaults(
            &qualifier,
            &parameters,
            &defaults,
            &arguments,
        );
        if substituted.trim().is_empty() {
            qualifier
        } else {
            substituted
        }
    };
    let inner =
        a_spelling_through_the_aliases(index, scopes, root, path, class, &qualifier, depth - 1);
    // **A qualifier that did not resolve is where this stops.** Carrying on with the spelling as if it were a class
    // asks the index for a *bare* name, and the library declares `_Alloc_traits` in a dozen classes: measured, the
    // chain silently continued in `std::basic_string` and answered a type from another class. Stopping answers the
    // last thing that *was* resolved, which is the honest place to hand over.
    // **A qualifier that did not resolve *and is not a class* is where this stops.** The guard used to stop whenever the
    // recursion came back unchanged, which also stopped at a qualifier that was already the answer —
    // `conditional<false, void, T>`, a class template applied to arguments, whose `type` lives in a *specialization*
    // (measured: the answer was the class `conditional` with one member listed, `type`).
    if inner.trim() == qualifier.trim()
        && !matches!(members_of(index, scopes, root, path, &inner), Known::Yes(_))
    {
        return written.to_string();
    }
    let inner_type = crate::sema::types::parse_type_spelling(&inner);
    let Some(inner_name) = inner_type.class_name() else {
        return written.to_string();
    };
    // **The arguments split where the language splits them.** `split_arguments` counts brackets
    // *and* parentheses, the same rule the pattern comparison uses.
    let inner_arguments: Vec<String> = crate::sema::builtins::split_arguments(
        inner
            .split_once('<')
            .map(|(_, rest)| rest.trim_end().strip_suffix('>').unwrap_or(rest))
            .unwrap_or_default(),
    );
    let inner_parameters = index.template_parameters_for(inner_name, path, &inner_arguments);
    let inner_defaults = index.template_parameter_defaults_for(inner_name, path, &inner_arguments);
    // **The class as the use wrote it** — with its arguments — because that is what selects a
    // partial specialization and what lets the qualifier's own aliases (`_Mybase =
    // _Tree_val<_Traits>`) be substituted.
    let found = a_member_the_class_declares(index, scopes, root, path, &inner, &last);
    if crate::probes::inference() {
        eprintln!(
            "[inference] qualified: {written:?} -> qualifier {qualifier:?} resolved {inner:?}, member {last:?}, fact {:?}",
            found
                .as_ref()
                .map(|fact| (fact.type_of.clone(), fact.pattern.clone()))
        );
    }
    let Some(fact) = found else {
        return written.to_string();
    };
    let Some(target) = fact.type_of.as_deref() else {
        return written.to_string();
    };
    // The pattern's slots are what say which written argument each parameter takes.
    let (pattern_parameters, pattern_arguments) = fact
        .pattern
        .as_deref()
        .map(|pattern| the_pairing_its_pattern_implies(pattern, &inner_arguments))
        .filter(|(parameters, _)| !parameters.is_empty())
        .unwrap_or_else(|| (inner_parameters.clone(), inner_arguments.clone()));
    let target = crate::sema::types::substituted_spelling_with_defaults(
        target,
        &pattern_parameters,
        &inner_defaults,
        &pattern_arguments,
    );
    let followed =
        a_spelling_through_the_aliases(index, scopes, root, path, &inner_type, &target, depth - 1);
    format!("{leading}{followed}{trailing}")
}

/// **A member this class (or one of its bases) declares, with no arrow fallback.**
///
/// `member_fact` ends by asking about an `operator->` when a name is not found — right for a member query, wrong for the
/// alias walk, which the arrow path itself calls: `pointer` → not found → `operator->` → this walk → `pointer` … is a
/// cycle, and it was measured as a stack overflow in the fixture that pins the arrow's element type. `members_of` walks
/// the bases (which is what `_Ptr_base`'s aliases need) and never asks about an arrow.
///
/// The declaration preferred is the one that *has* a type: a re-exposed alias (`using typename _Base::value_type;`)
/// declares none of its own, and answering that one would be answering nothing.
fn a_member_the_class_declares(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    class: &str,
    name: &str,
) -> Option<DeclFact> {
    // **First the class's own member list**, which is what walks the bases (`_Ptr_base`'s `element_type` is one) and
    // which substitutes the class's parameters. A re-exposed alias declares no type of its own, so the declaration
    // answered is the one that *has* one.
    let listed = members_of(index, scopes, root, path, class);
    if crate::probes::inference() {
        match &listed {
            Known::Yes(members) => eprintln!(
                "[inference] member of {class:?}: {} listed, {} unlisted, looking for {name:?}",
                members.members.len(),
                members.unlisted.len()
            ),
            other => eprintln!("[inference] member of {class:?}: {other:?}"),
        }
    }
    if let Some(found) = listed.value().and_then(|members| {
        members
            .members
            .iter()
            .filter(|member| member.fact.name == name)
            .map(|member| member.fact.clone())
            .find(|fact| fact.type_of.is_some())
    }) {
        return Some(found);
    }

    // **Then the declaration this *use* is an instance of.** A class template's partial specializations share their
    // primary's scope, and `conditional<false, T, F>::type` is a member of the *specialization*: the member list above
    // is built from the primary, which has no `type` at all. `direct_member` is the function with that rule — the
    // pattern comparison, with the arguments read from the spelling — and it is the one lookup that does **not** end by
    // asking about an `operator->`, which is what keeps this walk out of the arrow's cycle.
    direct_member(index, scopes, root, path, class, name, None).map(|(fact, _)| fact)
}
/// **The (parameters, arguments) pairing a declaration's `pattern` implies.**
///
/// A partial specialization's pattern names its parameters in *its* slots — `conditional<false, T, F>` has two
/// parameters and three slots — so the use's arguments do not pair with them by position. Each slot that is a *name*
/// binds the parameter of that name to the written argument in the same place; a literal slot (`false`, `true`) binds
/// nothing, which is what makes the specialization apply in the first place.
fn the_pairing_its_pattern_implies(
    pattern: &str,
    written: &[String],
) -> (Vec<String>, Vec<String>) {
    let slots = arguments_in_a_spelling(pattern).unwrap_or_default();
    let mut parameters = Vec::new();
    let mut arguments = Vec::new();
    for (at, slot) in slots.iter().enumerate() {
        let slot = slot.trim();
        let Some(argument) = written.get(at) else {
            continue;
        };
        let a_name = !slot.is_empty()
            && slot
                .chars()
                .all(|character| character.is_alphanumeric() || character == '_')
            && !matches!(slot, "true" | "false");
        if a_name {
            parameters.push(slot.to_string());
            arguments.push(argument.clone());
        }
    }
    (parameters, arguments)
}
/// `A::b` → (`A`, `b`), split at the last `::` **outside angle brackets** — the same boundary
/// [`without_the_namespace`] finds from the other side.
fn split_at_the_last_scope(spelling: &str) -> Option<(String, String)> {
    let bytes = spelling.as_bytes();
    let mut depth = 0usize;
    let mut boundary = None;
    let mut at = 0usize;
    while at + 1 < bytes.len() {
        match bytes[at] {
            b'<' => depth += 1,
            b'>' => depth = depth.saturating_sub(1),
            b':' if depth == 0 && bytes[at + 1] == b':' => {
                boundary = Some(at);
                at += 1;
            }
            _ => {}
        }
        at += 1;
    }

    let boundary = boundary?;
    let qualifier = spelling[..boundary].trim().to_string();
    let last = spelling[boundary + 2..].trim().to_string();
    (!qualifier.is_empty() && !last.is_empty()).then_some((qualifier, last))
}

/// `const reference&` → (`const `, `reference`, `&`). The middle is what a name lookup is asked about.
fn split_the_operators_of(spelling: &str) -> (String, String, String) {
    let mut leading = String::new();
    let mut rest = spelling.trim();
    for qualifier in ["const", "volatile", "constexpr", "static"] {
        if let Some(after) = rest.strip_prefix(qualifier)
            && after.starts_with(char::is_whitespace)
        {
            leading.push_str(qualifier);
            leading.push(' ');
            rest = after.trim_start();
        }
    }
    // **The elaborated-type keywords are dropped rather than kept**, because they are not part of the type: a lookup
    // asked for a member literally called `typename _Alloc_traits` finds nothing, and the chain then guessed a class
    // by *bare* name and silently followed the wrong one — `std::basic_string`'s `_Alloc_traits` instead of
    // `std::vector`'s, measured on `lineStartOffset`. They are not qualifiers either (`typename T&` and `T&` are the
    // same type), so they belong in neither half of the answer.
    loop {
        let trimmed = rest.trim_start();
        let Some(after) = ["typename", "class", "struct", "union", "enum"]
            .iter()
            .find_map(|keyword| trimmed.strip_prefix(keyword))
        else {
            break;
        };
        if !after.starts_with(char::is_whitespace) {
            break;
        }
        rest = after.trim_start();
    }
    let trimmed = rest.trim_end();
    let mut trailing = String::new();
    let mut core = trimmed;
    for _ in 0..4 {
        if let Some(before) = core
            .strip_suffix("&&")
            .or_else(|| core.strip_suffix('&'))
            .or_else(|| core.strip_suffix('*'))
        {
            let operator = &core[before.len()..];
            trailing.insert_str(0, operator);
            core = before.trim_end();
            continue;
        }
        break;
    }
    (leading, core.to_string(), trailing)
}

fn through_an_operator_arrow(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    class: &str,
    member: &str,
    arguments: Option<&[String]>,
) -> Option<(DeclFact, PathBuf)> {
    // **The class without its arguments**, because that is the name its members are filed under, and the arguments
    // are what the arrow's return type is substituted with.
    let target = the_class_an_arrow_points_at(index, scopes, root, path, class, arguments)?;
    direct_member(index, scopes, root, path, &target, member, None)
}

/// **The class an object's `operator->` reaches**, or `None` when it declares none — or when its answer is a
/// template parameter this call cannot substitute.
fn the_class_an_arrow_points_at(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    class: &str,
    arguments: Option<&[String]>,
) -> Option<String> {
    let bare = without_arguments(class).to_string();
    let arguments: Vec<String> = arguments
        .map(<[String]>::to_vec)
        .or_else(|| {
            class.split_once('<').map(|(_, rest)| {
                crate::sema::builtins::split_arguments(
                    rest.trim_end().strip_suffix('>').unwrap_or(rest),
                )
            })
        })
        .unwrap_or_default();
    // **The arguments are handed to the lookup**, so that a partial specialization whose pattern does not match is not
    // the declaration `operator->` is read from — the same rule `direct_member`'s members already follow.
    let (arrow, _) = direct_member(
        index,
        scopes,
        root,
        path,
        &bare,
        "operator->",
        Some(&arguments),
    )?;
    let returns = arrow.returns?;
    if crate::probes::inference() {
        eprintln!(
            "[inference] operator-> of {bare} on arguments {arguments:?}: the member wrote {returns:?}"
        );
    }

    if arguments.is_empty() {
        return None;
    }
    let parameters = index.template_parameters_for(&bare, path, &arguments);
    let defaults = index.template_parameter_defaults_for(&bare, path, &arguments);
    // **The arrow's return is a *name* in the class that declares it**, and it has to be followed
    // before it can be a class: `_Tree_iterator::operator->` answers `pointer`, which the
    // iterator's own `typedef _Val* pointer;` makes a `pair<const K, V>*`. The step is the same one
    // a member's recorded type goes through ([`a_spelling_through_the_aliases`]), applied here
    // because this is the second place a *spelling* is about to be used as a type.
    let class_type = crate::sema::types::parse_type_spelling(class);
    let resolved = a_spelling_through_the_aliases(
        index,
        scopes,
        root,
        path,
        &class_type,
        &returns,
        MAX_ALIAS_HOPS,
    );
    let substituted = crate::sema::types::substituted_spelling_with_defaults(
        &resolved,
        &parameters,
        &defaults,
        &arguments,
    );
    let mut target = base_type_name(&substituted).to_string();

    // **The member may be a template of its own**, and then its answer names *its* parameter, not the class's:
    //
    // ```cpp
    // template <class _Ty2 = _Ty, enable_if_t<!is_array_v<_Ty2>, int> = 0>
    // _NODISCARD _Ty2* operator->() const noexcept;
    // ```
    //
    // is how MSVC's `<memory>` writes `shared_ptr::operator->`. A fact records a template's parameter *names* and not
    // their defaults, so `_Ty2` cannot be substituted from here — and asking a member lookup about a class called
    // `_Ty2` is what an editor saw as "`file->` has no members" (`class "_Ty2": 0 member(s)`, measured on
    // EmmyLuaCodeStyle's `LuaFormat.cpp`).
    //
    // What settles it is the convention every pointer-like type in the standard library follows: `element_type` is
    // what the arrow reaches, and it is declared on the class or one of its bases.
    // **When the answer is a name nothing declares, it is a parameter** — the member's own, or the class's own written
    // somewhere the substitution could not reach. `_Ty2` is declared nowhere in a project, and a class called `_Ty2` is
    // a class no reader wrote.
    let names_nothing =
        index.files_declaring(&target, path).is_empty() && !is_a_builtin_name(&target);
    if target.is_empty()
        || target == bare
        || names_nothing
        || arrow.parameters.iter().any(|name| name == &target)
    {
        // **An answer only counts when it names a class the index has.** The walk can arrive at a spelling that is a
        // *trait* rather than a class — `remove_extent_t` after `remove_extent_t<_Ty>` is substituted, an alias template
        // whose target the standard library defines through `typename remove_extent<T>::type` — and asking a member
        // lookup about it answers "no members" with confidence.
        // **A class, not an alias of one.** Both are `DeclKind::Type`; what tells them apart is the same field
        // `operator_returns_of` uses — an alias declares a target in `type_of`, a class declares none. A bare
        // `remove_extent_t` is an alias template, and treating it as a class is exactly the mistake this guards.
        let names_a_class = |name: &str| {
            let bare = base_type_name(name);
            is_a_builtin_name(bare)
                || index.files_declaring(bare, path).iter().any(|found| {
                    found.fact.kind == crate::DeclKind::Type && found.fact.type_of.is_none()
                })
        };
        let walked = the_element_type_of(index, scopes, root, path, class, &bare, &arguments);
        target = match walked {
            Some(walked) if names_a_class(&walked) => walked,
            // **The pointer-like class's own argument, when its `element_type` leads through a trait this layer cannot
            // follow.** MSVC's `_Ptr_base` says `using element_type = remove_extent_t<_Ty>;`, which substitutes to
            // `remove_extent_t<LuaSource>` — an alias *template* whose target is `typename remove_extent<T>::type`, a
            // trait evaluation rather than a spelling. `base_type_name` then leaves `remove_extent_t`, a class template
            // with no arguments, and no member list can come of it. For a class template that declares a pointer-like
            // arrow, the element is its own argument — that is what `shared_ptr<T>`, `unique_ptr<T>` and every other
            // handle mean, and it is what the standard's `element_type` is for the non-array case.
            _ => match arguments.as_slice() {
                [only] if names_a_class(only) => base_type_name(only).to_string(),
                _ => target,
            },
        };
    }
    if crate::probes::inference() {
        eprintln!(
            "[inference] operator-> substitution: parameters {parameters:?}, the member's own {arrow_parameters:?}, {returns:?} -> {substituted:?} -> {target:?}",
            arrow_parameters = arrow.parameters
        );
    }
    (!target.is_empty() && target != bare).then_some(target)
}

/// A name the language spells, not one a declaration introduces — `int` is not a class to look members up in, and it is
/// also not a parameter whose meaning was lost.
fn is_a_builtin_name(name: &str) -> bool {
    matches!(
        name,
        "int"
            | "char"
            | "bool"
            | "void"
            | "float"
            | "double"
            | "long"
            | "short"
            | "signed"
            | "unsigned"
            | "auto"
            | "wchar_t"
            | "char8_t"
            | "char16_t"
            | "char32_t"
            | "size_t"
    )
}
/// **What a pointer-like class's arrow reaches** — its `element_type`, or `value_type` when it has one instead.
///
/// Both are read from the class or a base (a `shared_ptr`'s `element_type` is `_Ptr_base`'s), and both are substituted
/// with the arguments the use wrote, because the declaration spells them with the class's own parameter names.
///
/// # Two callers, one rule
///
/// [`the_arrow_a_member_returns_through`] asks this only when its own walk reached a name nothing declares (a member
/// template's parameter). `completion`'s arrow walk asks it **first**, for any class that declares one, and the
/// difference is a defect measured on a real project: `std::unique_ptr<int> p; p->` offered `get` and `get_deleter`
/// — the smart pointer's *own* members, none of which can be written after that arrow — because `operator->` returns
/// `pointer`, a member alias of `typename _Get_deleter_pointer_type<…>::type`, and that name *is* declared, so the
/// walk followed it into a trait template instead of the class it produces. `element_type` is the standard's own
/// answer to this question (`std::pointer_traits` is written in terms of it) and it is one lookup away.
pub fn element_type_of(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    class: &str,
    bare: &str,
    arguments: &[String],
) -> Option<String> {
    the_element_type_of(index, scopes, root, path, class, bare, arguments)
}

fn the_element_type_of(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    class: &str,
    bare: &str,
    arguments: &[String],
) -> Option<String> {
    let parameters = index.template_parameters_for(bare, path, arguments);
    // **The walk that follows member aliases as well as base clauses** — see
    // [`an_element_type_through_the_members`]. The class this exists for names its base through an alias
    // (`class shared_ptr : public _Mybase`), so the base's `element_type` is never in the class's own member list.
    let through_the_members = an_element_type_through_the_members(
        index,
        scopes,
        root,
        path,
        class,
        &parameters,
        arguments,
        0,
    );
    if through_the_members.is_some() {
        return through_the_members;
    }
    // **The member *list*, not the single-member query**: `member_fact` ends by falling back to this very function
    // (the arrow of a class that has no `element_type`), so asking it here recursed until the stack ran out — measured,
    // the test that produced this line overflowed it. A list walks the bases and never asks about an arrow.
    let Known::Yes(members) = members_of(index, scopes, root, path, class) else {
        if crate::probes::inference() {
            eprintln!("[inference] element_type: no member list for {class}");
        }
        return None;
    };
    if crate::probes::inference() {
        let found: Vec<String> = members
            .members
            .iter()
            .filter(|member| matches!(member.fact.name.as_str(), "element_type" | "value_type"))
            .map(|member| {
                format!(
                    "{} kind {:?} type_of {:?}",
                    member.fact.name, member.fact.kind, member.fact.type_of
                )
            })
            .collect();
        eprintln!(
            "[inference] element_type: {class} has {} member(s), {found:?}",
            members.members.len()
        );
    }
    for name in ["element_type", "value_type"] {
        let Some(fact) = members
            .members
            .iter()
            .find(|member| member.fact.name == name)
            .map(|member| &member.fact)
        else {
            continue;
        };
        let Some(written) = fact.type_of.as_deref() else {
            continue;
        };
        let substituted = crate::sema::types::substituted_spelling(written, &parameters, arguments);
        let target = base_type_name(&substituted).to_string();
        if crate::probes::inference() {
            eprintln!(
                "[inference] element_type: {class}::{name} wrote {written:?} -> {substituted:?} -> {target:?} ({} member(s))",
                members.members.len()
            );
        }
        // A parameter name is not an answer: it means the declaration named something this call cannot substitute.
        if !target.is_empty()
            && target != bare
            && !parameters.iter().any(|parameter| parameter == &target)
        {
            return Some(target);
        }
    }
    None
}

fn member_fact(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    class: &str,
    member: &str,
    arguments: Option<&[String]>,
) -> Known<(DeclFact, PathBuf)> {
    let started = std::time::Instant::now();
    let answer = member_fact_inner(index, scopes, root, path, class, member, arguments);
    if crate::probes::timing() && started.elapsed().as_millis() > 10 {
        eprintln!(
            "[member_fact] {:>5} ms  {class}::{member}",
            started.elapsed().as_millis()
        );
    }
    answer
}

fn member_fact_inner(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    class: &str,
    member: &str,
    // **The arguments the use wrote**, when the caller has them. See [`direct_member`]'s pattern rule: a class
    // template's partial specializations share their primary's scope, and this is what tells them apart. `None`
    // from a caller that does not know them, which answers the way this did before the rule existed.
    arguments: Option<&[String]>,
) -> Known<(DeclFact, PathBuf)> {
    // Followed **before** anything else, so that both the lookup and the spelling this answer reports when it
    // fails name the class rather than the alias: `Widget::size` is the question that could not be answered, and
    // `Alias::size` would be a question nobody asked. `direct_member` follows it again for the bases it is handed,
    // where the step is idempotent — a class resolves to itself.
    let class = &resolve_aliases(index, scopes, root, path, class);

    // **The arguments written on the class are what tells a partial specialization from its primary, and the caller
    // that has only a spelling has none to pass.** The nested-name walk is that caller: it arrives with
    // `enable_if<__is_same(int, int), double>` and asks for `type`, which is a member of the *specialization* — and
    // `a_pattern_matches` compares a candidate's pattern against what the use wrote, so with `None` it can only
    // answer "cannot be compared", which keeps every candidate and finds none. Measured: the member name itself came
    // back as the type.
    //
    // The spelling carries them, so they are read off it, and a caller that already knows them (from an object's
    // type) keeps its own — those are the ones paired with the class's parameters by `member_bindings` afterwards.
    let from_the_spelling: Option<Vec<String>> = class.split_once('<').map(|(_, rest)| {
        crate::sema::builtins::split_arguments(rest.trim_end().strip_suffix('>').unwrap_or(rest))
    });
    let arguments = arguments.or(from_the_spelling.as_deref());

    if let Some(found) = direct_member(index, scopes, root, path, class, member, arguments) {
        return Known::Yes(found);
    }

    // **An unqualified class name has to be looked up in a scope, and this is where that was missing.**
    //
    // The spelling a member query arrives with is the one the *use* wrote, and a use inside a namespace writes the
    // class without it: MSVC's `<vector>` says `_Compressed_pair<_Alty, _Scary_val> _Mypair;` and then
    // `_Mypair._Myval2`, because the file is inside `_STD_BEGIN`. The fact is filed under `std::_Compressed_pair` —
    // correctly, from the rendering — and `declarations_in("_Compressed_pair")` therefore finds nothing at all.
    //
    // Measured on `<vector>`: **42 `auto` declarations refused with `NotDeclaredHere("_Compressed_pair::_Myval2")`**
    // — every `auto& _My_data = _Mypair._Myval2;` in the file — while `v.size()` on a `std::vector<int>` worked,
    // because *that* spelling was qualified by the reader who wrote it. The difference looked like an alias problem,
    // then a partial-specialization problem, for several rounds; it is neither.
    //
    // The scope is found the way the base-clause note above finds one for a base name — from the declaration, which
    // is the only thing that knows where it was written. [`ProjectIndex::files_declaring`] searches by **bare name**,
    // so an unqualified spelling reaches a declaration filed under any scope; the first visible one is taken, which
    // is the same choice [`resolve_aliases`] makes and for the same reason.
    //
    // Only for a **bare** name: `std::_Compressed_pair` and `_Compressed_pair` are different questions, and a
    // qualified spelling that found nothing has already said which scope it meant.
    //
    // **And the template arguments come off first**, which is what this step was missing for the second half of the
    // family. The spelling arrives as the type of the *object* — `_Locked_pointer<_Ty>` — and a declaration is never
    // keyed by that: measured on the same name, `_Locked_pointer` resolves to `std::_Locked_pointer` while
    // `_Locked_pointer<_Ty>` answers `NotDeclaredHere`. Ten `auto` declarations in `<memory>` were refused that way,
    // seven of them for `_Locked_pointer::_Lock_and_load`, and the fact had `scope=std::_Locked_pointer` the whole
    // time. The arguments are not lost: [`member_bindings`] pairs them with the class's parameters **after** the
    // class is found.
    if !class.contains("::") {
        let bare = without_arguments(class);
        if let Some(declared_in) = qualified_from_the_index(index, path, bare)
            && let Some(found) =
                direct_member(index, scopes, root, path, &declared_in, member, arguments)
        {
            return Known::Yes(found);
        }
    }

    // Inherited members, **level by level**: a member of a direct base hides a member of that base's own base,
    // which is what C++ does, so the search stops at the first level that has any answer. Two answers at the same
    // level are ambiguous — a diamond where both sides declare the name — and reporting that is the honest
    // outcome: picking one would be a jump to an entity the language says is not uniquely named.
    //
    // As in `members_of`, each base is carried with the class whose base-clause wrote it, because that decides the
    // scope an unqualified base name is looked up in — `struct map : _Tree<…>` in `std` names `std::_Tree`.
    //
    // **And a template parameter is not a base**, for the same reason and with the same measurement as
    // [`members_of`]'s filter: `_Vector_base<_Tp, _Alloc>` contributes `_Tp` and `_Alloc` as "names a class can be
    // looked up by", and asking "who declares `_Tp`" is a whole-index name query. Measured on `LuaSyntaxTree.cpp`,
    // `member_fact(std::vector, size_t)` — a member the class does not have — cost **370–389 ms** per call, eight
    // times, which was 2 280 ms of the file's inference.
    let parameters = class_template_parameters(index, scopes, root, path, class);
    let mut level: Vec<(String, String)> = bases_of(index, scopes, root, path, class)
        .value()
        .unwrap_or_default()
        .into_iter()
        .filter(|base| !names_a_template_parameter(base, &parameters))
        .map(|base| (base, class.to_string()))
        .collect();
    let mut visited: Vec<String> = vec![class.to_string()];

    while !level.is_empty() {
        let mut found: Vec<(DeclFact, PathBuf)> = Vec::new();
        let mut next: Vec<(String, String)> = Vec::new();

        for (written, owner) in level {
            let base = resolved_in_the_enclosing_scopes(index, scopes, path, &owner, &written);
            if visited.contains(&base) {
                continue;
            }
            visited.push(base.clone());

            // A base that cannot be resolved contributes nothing *and* stops nothing: whatever it might inherit
            // from is unknown, not absent, and the levels below it are still worth asking.
            if let Some(member_found) =
                direct_member(index, scopes, root, path, &base, member, arguments)
            {
                found.push(member_found);
            }
            next.extend(
                bases_of(index, scopes, root, path, &base)
                    .value()
                    .unwrap_or_default()
                    .into_iter()
                    .filter(|base_of_base| !names_a_template_parameter(base_of_base, &parameters))
                    .map(|base_of_base| (base_of_base, base.clone())),
            );
        }

        match found.len() {
            0 => level = next,
            1 => return Known::Yes(found.remove(0)),
            _ => return Known::Unknown(UnknownReason::Ambiguous(Box::from(member))),
        }
    }

    // **A member reached through `operator->`** — `shared_ptr<T>::operator->` returns `T *`, so `config->Generate`
    // is `T::Generate`, and a lookup that stopped at the handle answered "`std::shared_ptr<LuaEditorConfig>` has no
    // member `Generate`" with no completion beside it (reported from an editor, on the ordinary way a smart pointer
    // is used). The rule is the language's: `->` on a class calls the class's `operator->` and looks at what it
    // returns, one level — the same one level [`member_access_class`] reaches through a pointer for.
    //
    // The return type is the *class's* parameter spelling (`_Ty *` for `shared_ptr`, `T *` for a hand-written
    // handle), so it is substituted with the arguments the use wrote before the lookup. A class with no
    // `operator->`, or one whose answer is not a class this analysis can name, answers as it did before.
    if let Some(found) =
        through_an_operator_arrow(index, scopes, root, path, class, member, arguments)
    {
        return Known::Yes(found);
    }

    Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(format!(
        "{class}::{member}"
    ))))
}

/// **A class spelling without its template arguments** — `_Locked_pointer<_Ty>` becomes `_Locked_pointer`.
///
/// A **trailing** `<…>` comes off, which is the shape a use writes: the type of an object is the class with the
/// arguments that finish it, and it is exactly that spelling which is never a declaration's own key. The arguments
/// are still used — [`member_bindings`] pairs them with the class's parameters once the class is found — so
/// dropping them here loses nothing and is the only reason a lookup keyed on the class can succeed at all.
///
/// Only the **last** angle-bracket group is removed, and that is deliberate rather than a parser: `A<B>::C<D>` has
/// two, and cutting at the first `<` would turn the qualification into nonsense. Stripping from the end leaves
/// `A<B>::C`, which is still not a key the index holds — and a lookup that fails is this module's ordinary answer,
/// where a lookup that matched a mangled spelling would be a wrong one.
fn without_arguments(class: &str) -> &str {
    let trimmed = class.trim();
    if !trimmed.ends_with('>') {
        return trimmed;
    }

    // Backwards to the `<` that opened this group, counting nesting so that `Box<Pair<int, int>>` closes at the
    // right place.
    let mut depth = 0usize;
    for (at, character) in trimmed.char_indices().rev() {
        match character {
            '>' => depth += 1,
            '<' => {
                depth -= 1;
                if depth == 0 {
                    let name = trimmed[..at].trim();
                    // `operator<` and a stray `<` with nothing before it: nothing to strip, and the spelling as
                    // written is the honest answer.
                    return if name.is_empty() { trimmed } else { name };
                }
            }
            _ => {}
        }
    }

    trimmed
}

///
/// Two sources for the two-layer split every query in this module makes: a class the file being edited declares is
/// in its scope tree (and its parameters are in its syntax), while a class a header declares is a fact, and the
/// parameters travel with it. A class neither holds answers nothing, which is the ordinary case for an ordinary
/// class.
/// **The pairing that finishes a member's type**: the class's parameters against the use's arguments.
///
/// Its own function because two callers need the same pairing for two different questions — the member's own type
/// (`std::vector<int>::data` is `_Ty*` and therefore `int*`) and what a call of it returns (`_Ty*` again) — and a
/// second copy of "which names go with which arguments" is a second place to get the pairing wrong.
fn member_bindings(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    class: &str,
    arguments: &[Type],
) -> crate::sema::types::TypeBindings {
    if arguments.is_empty() {
        return crate::sema::types::TypeBindings::default();
    }

    let names = class_template_parameters(index, scopes, root, path, class);
    crate::sema::types::TypeBindings::new(names, arguments.to_vec())
}

/// **The arguments a class template deduces from an initializer** — C++17's implicit guide, for the one shape this can be
/// sure of.
///
/// `Box box(7);` where `Box` is `template <typename T> class Box { Box(T); … };` is a `Box<int>`: the standard says
/// the implicit guides are built from the constructors, and a constructor taking exactly the template parameter is the
/// common case. `None` — meaning *answer the name as written* — for two parameters, for a constructor whose parameter
/// names something else, and for a class with no constructor of that shape, because a guessed argument would print an
/// instantiation nobody asked for.
/// **The arguments a class template deduces from an initializer** — C++17's implicit guide, for the one shape this can be
/// sure of.
///
/// ``Box box(7);`` where ``Box`` is ``template <typename T> class Box { Box(T); … };`` is a ``Box<int>``: the standard
/// says the implicit guides are built from the constructors, and a constructor taking exactly the template parameter is
/// the common case. ``None`` — meaning *answer the name as written* — for two parameters, for a constructor whose
/// parameter names something else, and for a class with no constructor of that shape, because a guessed argument would
/// print an instantiation nobody asked for.
///
/// # Where the constructor is read, and why from two places
///
/// A constructor is **not a binding** of its class's scope: a scope is keyed by name and `Box::Box` is not a name any
/// lookup asks for. So it is read from the class's own body —
///
/// ```text
/// the tree    the class is declared in the file being edited        `class Box { explicit Box(T); }`
/// the index   it is declared in a header this file includes         the header's facts, scope `ns::Box`, name `Box`
/// ```
///
/// — and the second case is not a refinement: measured on a `.cpp` that includes a header holding the template, the
/// rendering inlined the *facts* (members answered 2 of 2) and not the *body*, so the tree held no `ClassDef` at all and
/// the deduction answered the bare template name.
fn deduced_class_template_arguments(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
    class: &str,
    initializer: &crate::sema::types::Type,
) -> Option<String> {
    let parameters = class_template_parameters(index, scopes, root, path, class);
    let [only] = parameters.as_slice() else {
        return None;
    };
    let simple = class.rsplit("::").next().unwrap_or(class);

    // **A hand-written deduction guide** — the language's own spelling of the rule, and the only source for a class
    // whose constructor does not take the parameter: `template <typename T> Wrap(T) -> Wrap<T>;`. Asked first, because
    // a guide that exists *is* the rule the language applies.
    if let Some(deduced) = the_deduction_guide_deduces(root, class, simple, only, initializer) {
        return Some(deduced);
    }
    if the_constructor_takes(root, class, simple, only) {
        return Some(format!("{class}<{initializer}>"));
    }
    // **The header that declares it.** A `.cpp` whose rendering did not inline the template's *body* has no `ClassDef`
    // to read, and the index keeps no fact for a constructor — so the file that declares the class is parsed and the same
    // scan runs over its tree. `declaring` is the request layer's file provider, the one the type queries already use.
    for declared in index.files_declaring(simple, path) {
        if declared.file == path {
            continue;
        }
        let Some(view) = declaring(&declared.file) else {
            continue;
        };
        if let Some(deduced) =
            the_deduction_guide_deduces(&view.root, class, simple, only, initializer)
        {
            return Some(deduced);
        }
        if the_constructor_takes(&view.root, class, simple, only) {
            return Some(format!("{class}<{initializer}>"));
        }
    }
    None
}

/// Does `class` declare a constructor whose first parameter **is** the template parameter `only`?
///
/// The two sources are tried in the order the answer is cheapest: the tree this file's reading already holds, then the
/// index's facts for the header that declares it.
fn the_constructor_takes(
    root: &cpp_parser::CppSyntaxNode,
    _class: &str,
    simple: &str,
    only: &str,
) -> bool {
    // **In this file's own tree.** The class is found by its own name rather than through a scope: a class scope holds
    // its members, and the class itself is bound in the scope that encloses it, so a walk from the scope is the long way
    // round.
    let in_the_tree = root.descendants().find(|node| {
        matches!(
            cpp_parser::CppSyntaxKind::from(node.kind()),
            cpp_parser::CppSyntaxKind::ClassDef
                | cpp_parser::CppSyntaxKind::StructDef
                | cpp_parser::CppSyntaxKind::UnionDef
        ) && node.children().any(|child| {
            cpp_parser::CppSyntaxKind::from(child.kind()) == cpp_parser::CppSyntaxKind::NameExpr
                && child.text().to_string().trim() == simple
        })
    });
    if let Some(node) = in_the_tree {
        for declaration in node.descendants() {
            if cpp_parser::CppSyntaxKind::from(declaration.kind())
                != cpp_parser::CppSyntaxKind::Declaration
            {
                continue;
            }
            // **A constructor, by its own text.** `explicit Box(T value) : value_(value) {}` is a declaration whose
            // specifier sequence may hold `explicit` alone with the name in the declarator, so reading only the
            // specifiers found the constructor in a class without a member-initializer list and not in one with it.
            // The shape matched is `[explicit] Name (`, which nothing else in a class body is: a member function starts
            // with its return type.
            let text = declaration.text().to_string();
            let head = text
                .trim_start()
                .trim_start_matches("explicit")
                .trim_start();
            if !(head.starts_with(simple) && head[simple.len()..].trim_start().starts_with('(')) {
                continue;
            }
            let Some(parameters) = declaration.descendants().find(|child| {
                cpp_parser::CppSyntaxKind::from(child.kind())
                    == cpp_parser::CppSyntaxKind::ParameterList
            }) else {
                continue;
            };
            if the_first_parameter_is(&parameters.text().to_string(), only) {
                return true;
            }
        }
        return false;
    }
    false
}

/// **What a hand-written deduction guide says**, for the identity form: `Name(T) -> Name<T>`.
///
/// ```cpp
/// template <typename T>
/// Wrap(T) -> Wrap<T>;      //  Wrap wrapped(7);   is a Wrap<int>
/// ```
///
/// The guide is a declaration whose text holds `->`: the head is `[template <…>] Name(params)` and the tail is the type
/// it deduces to. Only the identity form is read — the return type is exactly `Name<T>` for the class's single template
/// parameter — because anything else (`Name<T*>`, two parameters, a pack) is a pattern match this layer does not do, and a
/// wrong argument would print an instantiation nobody asked for.
fn the_deduction_guide_deduces(
    root: &cpp_parser::CppSyntaxNode,
    class: &str,
    simple: &str,
    only: &str,
    initializer: &crate::sema::types::Type,
) -> Option<String> {
    let deduces_to = format!("{simple}<{only}>");
    for declaration in root.descendants() {
        if cpp_parser::CppSyntaxKind::from(declaration.kind())
            != cpp_parser::CppSyntaxKind::Declaration
        {
            continue;
        }
        let text = declaration.text().to_string();
        let Some((head, tail)) = text.split_once("->") else {
            continue;
        };
        let returns = tail.trim().trim_end_matches(';').trim();
        if returns != deduces_to {
            continue;
        }
        let head = head.trim();
        let Some(open) = head.rfind('(') else {
            continue;
        };
        // **The guide's name**, which is the last token before its parameter list: `template <typename T>` then `Wrap`.
        let name = head[..open]
            .rsplit(|character: char| character.is_whitespace() || character == '>')
            .find(|word| !word.is_empty())
            .unwrap_or_default();
        if name != simple {
            continue;
        }
        if the_first_parameter_is(&head[open..], only) {
            return Some(format!("{class}<{initializer}>"));
        }
    }
    None
}

/// Is the first parameter of `list` — `(T value)`, `(const T& value)` — spelled with the template parameter?
fn the_first_parameter_is(list: &str, only: &str) -> bool {
    list.trim_start_matches('(')
        .split(',')
        .next()
        .unwrap_or_default()
        .split(|character: char| !character.is_alphanumeric() && character != '_')
        .any(|word| word == only)
}

fn class_template_parameters(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    class: &str,
) -> Vec<String> {
    if let Some(scope) = scopes.scope_with_qualified_name(class)
        && let Some(binding) = scopes.scope(scope).and_then(|scope| {
            scope
                .bindings
                .iter()
                .find(|binding| binding.kind == crate::BindingKind::Class)
        })
    {
        let found = crate::sema::declarations::declared_template_parameters_of(root, binding);
        if !found.is_empty() {
            return found;
        }
    }

    index.template_parameters_of(class, path)
}

/// How many aliases deep a type spelling is followed before the walk gives up.
///
/// `using A = A;` and `using A = B; using B = A;` are both writable, and a walk that trusted the spelling would
/// follow them for ever. Eight is far past any real chain of aliases — the standard library's deepest are two or
/// three (`string` → `basic_string`, `size_type` → `size_t` → …) — and the answer when it is reached is the
/// spelling that was last resolved, which the caller then reports as not declared rather than as a wrong class.
const MAX_ALIAS_DEPTH: usize = 8;

/// The class a type spelling names, following `typedef`/`using` **aliases**.
///
/// `std::string` is `basic_string<char>`; nobody declares `substr` *in* `string`, because an alias has no members
/// of its own. So a spelling that resolves to an alias is replaced by the type the alias points at, and the
/// lookup carries on with that — which is one step, not a type system: no instantiation, no substitution, no
/// inference of what the target's template arguments mean.
///
/// # The target is resolved in the alias's own scope
///
/// ```cpp
/// namespace std { typedef basic_string<char> string; }   // the target is written *relative to* `std`
/// ```
///
/// Following it as a bare `basic_string` would look in the wrong place. The candidates are therefore
/// `<the alias's scope>::<target>` first and the bare target second — which is C++'s own enclosing-scope lookup,
/// done one step of it: the standard library's aliases are nearly all spelled this way, so the first candidate is
/// the one that answers, and a target that names something global still resolves through the second.
///
/// # Bounded, and honest when it stops
///
/// A spelling that cannot be resolved to a class comes back **unchanged**, so the caller reports
/// `NotDeclaredHere(<what the file wrote>)` rather than a name nobody wrote. See [`MAX_ALIAS_DEPTH`] for the bound
/// and why a bound is needed at all.
fn resolve_aliases(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    class: &str,
) -> String {
    resolve_aliases_with_arguments(index, scopes, root, path, class).0
}

/// **The class a spelling names, following aliases — and the template arguments the alias carried.**
///
/// `std::string` is `basic_string<char, char_traits<char>, allocator<char>>`. Following the alias gives the class
/// `std::basic_string`, and the **arguments are the other half of the answer**: they are what makes `_Elem` mean
/// `char`, so a member whose type is written `_Elem&` is `char&` for a `std::string` and `wchar_t&` for a
/// `std::wstring`. Both come back from here because they come from the same step, and a caller that had to ask
/// twice would have two chances to disagree about which step it was.
///
/// # The arguments of the *last* step, and why that is right
///
/// Each alias step replaces the spelling with its target, so an earlier step's arguments have already been written
/// into the target the next step sees: `using A = B<int>; using B = vector<T>;` — no, more simply, the standard
/// library's shape is one step (`string` → `basic_string<char, …>`), and for two steps the second target's own
/// arguments are the ones that describe the class finally named. Arguments found on an earlier step are therefore
/// kept only if the later one carries none, which is the case where the later target is a bare name
/// (`using B = basic_string;`).
///
/// # What it does not do
///
/// No substitution: `MyVec<T>` → `std::vector<T>` returns the *argument as written* (`T`), and pairing it with
/// `_Ty` is the caller's step, because the caller is the one that knows what `T` stands for. See
/// [`TypeBindings::applied_to`].
fn resolve_aliases_with_arguments(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    class: &str,
) -> (String, Vec<Type>) {
    let (name, carried, _unresolved) =
        resolve_aliases_or_unresolved(index, scopes, root, path, class);
    (name, carried)
}

/// [`resolve_aliases_with_arguments`], and **the class it could not find** when the chain ends at a spelling the
/// index does not declare.
///
/// That third answer is what tells a member query the difference between "this class has no members" and "this
/// spelling names a class I cannot see", and the two must not be answered the same way. Measured on
/// `CodeFormatCLib/src/CodeFormat.cpp` (libstdc++): `std::string` is `typedef basic_string<char> string;` inside
/// `std::__cxx11`, so the walk resolves the name `basic_string` from `std` — where nothing declares it — and used to
/// settle on `std::basic_string` anyway. `direct_members` then found no facts under that spelling, answered an
/// **empty, complete** list, and `undefined-field` reported `result.size()`, `formattedText.begin()` and eight more
/// members of `std::string` as undefined. Ten false positives on one file, all from this fallback.
fn resolve_aliases_or_unresolved(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    class: &str,
) -> (String, Vec<Type>, Option<String>) {
    let mut current = class.to_string();
    let mut carried: Vec<Type> = Vec::new();
    let mut seen: Vec<String> = Vec::new();

    for _ in 0..MAX_ALIAS_DEPTH {
        if seen.contains(&current) {
            break;
        }
        seen.push(current.clone());

        // **The whole spelling is not an alias, but its prefix may be one.**
        //
        // `vector:2920` writes `using _Alvbase_traits = typename _Mybase::_Alvbase_traits;`, and `_Mybase` is
        // **another alias of `vector`** — so the target is a qualified name whose *first* segment is itself a
        // name to follow, not a class to stop at. Asking `alias_target_of` for the whole spelling answers `None`
        // and the walk used to end there, one alias short of `allocator_traits`: measured,
        // `members_of("std::vector::_Alvbase_traits")` reported
        // `NotDeclaredHere("std::vector::_Mybase::_Alvbase_traits")`.
        //
        // The prefix is what gets resolved, and the rest is carried along — one segment at a time, longest
        // prefix first, so a name nested two aliases deep is followed the same way. `seen` bounds it, so an
        // alias that leads back to itself stops here rather than looping.
        let followed = alias_target_of(index, scopes, root, path, &current).or_else(|| {
            let segments: Vec<&str> = current.split("::").collect();
            (1..segments.len()).rev().find_map(|take| {
                let prefix = segments[..take].join("::");
                let (target, scope) = alias_target_of(index, scopes, root, path, &prefix)?;

                // **The arguments come off and the scope does not go on.** Both are the rules the candidate
                // list below already applies, and applying them here as well compounded them: the first
                // attempt produced `std::vector::std::vector::_Vb_val<_Alloc>::_Alvbase_traits`, with the
                // enclosing scope twice over and a `_Vb_val<_Alloc>` no fact is named by.
                let target =
                    a_class_name_without_spaces(parse_type_spelling(&target).class_name()?);

                Some((format!("{target}::{}", segments[take..].join("::")), scope))
            })
        });

        let Some((target, scope)) = followed else {
            break;
        };

        // **Read as a type, not as a name**: the target's own arguments are what the class it names was written
        // with, and `base_type_name` — which the name-only walk used — is exactly the part that threw them away.
        let target_type = parse_type_spelling(&target);
        let Some(target) = target_type.class_name().map(a_class_name_without_spaces) else {
            break;
        };
        if target.is_empty() {
            break;
        }
        if !target_type.arguments().is_empty() {
            carried = target_type.arguments().to_vec();
        }

        // An unqualified target is looked for **from the scope the alias was declared in, outward** — which is
        // C++'s own rule for an unqualified name, and it is not one step of it.
        //
        // Measured on MSVC's `<string>`: `basic_string` declares `using _Alty_traits = allocator_traits<_Alty>;`,
        // and `allocator_traits` is a **free template at namespace scope in `std`** (`xmemory:754`). With only
        // the alias's own scope tried, the candidate is `std::basic_string::allocator_traits` — a spelling
        // nothing declares — and the walk gives up one scope short of the answer. `members_of` reported exactly
        // that: `NotDeclaredHere("std::basic_string::allocator_traits")`.
        //
        // **A qualified target's first segment takes the same walk**, and that is not the same as taking the
        // target as it stands. `vector` declares two of them:
        //
        // ```cpp
        // using _Alvbase_traits = allocator_traits<_Alvbase>;            // vector:2828, unqualified target
        // using _Alvbase_traits = typename _Mybase::_Alvbase_traits;     // vector:2920, qualified target
        // ```
        //
        // and `_Mybase` is **another alias of `vector`**, so `_Mybase::_Alvbase_traits` is not a spelling
        // anything declares — it is a name whose *first* segment has to be found the same way. Taken as it
        // stands it stopped the walk dead: `members_of("std::vector::_Alvbase_traits")` answered
        // `NotDeclaredHere("_Mybase::_Alvbase_traits")`, one alias short of `allocator_traits`.
        //
        // The bare name is kept last, for a target that names something at global scope. A target that begins
        // with `::` is absolute and is taken as it stands — that is what the leading `::` is for.
        let candidates: Vec<String> = match &scope {
            Some(prefix) if !target.starts_with("::") => {
                let prefix = a_class_name_without_spaces(prefix);
                let prefix = prefix.as_str();
                let (first, rest) = match target.split_once("::") {
                    Some((first, rest)) => (first, Some(rest)),
                    None => (target.as_str(), None),
                };
                let segments: Vec<&str> = prefix.split("::").collect();
                let mut candidates: Vec<String> = (1..=segments.len())
                    .rev()
                    .map(|take| match rest {
                        Some(rest) => format!("{}::{first}::{rest}", segments[..take].join("::")),
                        None => format!("{}::{first}", segments[..take].join("::")),
                    })
                    .collect();
                candidates.push(target.clone());
                candidates
            }
            _ => vec![target.clone()],
        };

        // **A target nothing declares is not an answer.** The candidates are the target qualified by the scopes the
        // alias was written in, outermost last; when every one of them is undeclared the chain has reached a name
        // this index cannot see (a namespace opened by a macro the index did not expand is the ordinary case) and
        // the spelling it would have returned describes nothing. Measured: `std::basic_string` for libstdc++'s
        // `std::string`, and ten false `undefined-field` findings on one file. The caller is told instead.
        // **A leading `::` says "the global scope", and the index does not key on it.** The rendering writes a macro's
        // expansion absolutely — `::std::basic_string` — so the accepted candidate is stripped before it becomes the
        // spelling every later lookup uses: measured, `members_of` answered 0 members with
        // `NotDeclaredHere("::std::basic_string")` while the very same class is filed as `std::basic_string`.
        // **A name the standard library brings into a namespace with a using-declaration, or one an inline namespace
        // holds, is one namespace in.** libstdc++'s ABI-1 `std::string` is `typedef basic_string<char> string;` in
        // `std`, and the class it names is `std::__cxx11::basic_string` — the `using __cxx11::basic_string;` that makes
        // `std::basic_string` a name is a *using-declaration*, which the index does not record as a declaration. The
        // candidate list above is exact spellings, so it finds neither, and the walk used to give up one namespace
        // short: measured on `import std;`, `members_of("std::string")` answered **0 members** with
        // `NotDeclaredHere("std::basic_string")` while `std::__cxx11::basic_string` was in the index all along.
        //
        // The search is C++'s own rule for inline namespaces (the name is visible in the enclosing namespace), aimed by
        // the candidate the alias's target was written in, and it prefers the **fewest extra segments** — the nearest
        // enclosing scope, which is the one lookup would have reached first.
        let nested = |candidate: &str| {
            let (prefix, name) = candidate.rsplit_once("::")?;
            let mut best: Option<(usize, String)> = None;
            for found in index.files_declaring(name, path) {
                if found.fact.kind != crate::DeclKind::Type || found.fact.type_of.is_some() {
                    continue;
                }
                let Some(scope) = found.fact.scope.as_deref() else {
                    continue;
                };
                let Some(rest) = scope.strip_prefix(prefix)?.strip_prefix("::") else {
                    continue;
                };
                let depth = rest.split("::").count();
                if depth == 1 && best.as_ref().is_none_or(|(least, _)| depth < *least) {
                    best = Some((depth, format!("{scope}::{name}")));
                }
            }
            best.map(|(_, spelling)| spelling)
        };
        let found = candidates
            .iter()
            .find(|candidate| is_declared(index, scopes, path, candidate))
            .map(|candidate| candidate.trim_start_matches("::").to_string())
            .or_else(|| candidates.iter().find_map(|candidate| nested(candidate)));
        let Some(next) = found else {
            // **The target is still the answer, and the third slot says it was not found.** A caller that only wants
            // a spelling keeps the one the alias named — `animate_aliases_whose_target_is_not_indexed_reports_the_target`
            // pins that: the missing declaration is `Widget::size`, not `Alias::size` — while a caller that has to
            // decide whether "no members" means an empty class or an unreadable one reads the third slot.
            let named = candidates[0].trim_start_matches("::").to_string();
            return (named.clone(), carried, Some(named));
        };

        if next == current {
            break;
        }
        current = next;
    }

    // The arguments of the **first** step are the ones that describe the type as written when nothing later said
    // otherwise: `std::string` has none of its own, and the step that resolved it supplied them.
    (current, carried, None)
}

/// **A class name with the whitespace taken out** — the rendering writes a macro's expansion spaced, so a target read
/// out of it is spelled `:: std :: basic_string` rather than `::std::basic_string`.
///
/// Not a cosmetic step: every downstream lookup keys on the spelling. Measured on `std::string`'s alias:
/// `resolve_aliases_or_unresolved` produced `:: std :: basic_string`, `is_declared` answered false for it (nothing is
/// declared under that spelling), the chain gave up and `members_of` reported **0 members** — so `enenn.size()`, whose
/// object's type had just been deduced, offered no completion at all.
fn a_class_name_without_spaces(name: &str) -> String {
    name.chars()
        .filter(|character| !character.is_whitespace())
        .collect()
}
/// What an alias points at, and the scope it was declared in, or `None` when the spelling is not an alias.
///
/// # How an alias is recognised
///
/// In the buffer, by the binding's kind, which is exact. Through the index, by the rule [`DeclFact::type_of`]
/// documents: a **type** fact with a `type_of` is an alias, and a class is a type fact without one. That is the
/// whole of the test, and it is one test rather than a new field on purpose — the field was already there for
/// variables, and what an alias *has* is a type in the same sense: the one it points at.
/// **Every balanced `<…>` group removed** — `outer<int>::handle_type` becomes `outer::handle_type`.
///
/// A type spelling, so the only `<` that can appear is a template argument list's. Nesting is counted forwards
/// because `Box<Pair<int, int>>` has to close at the right `>`.
fn without_template_arguments(written: &str) -> String {
    let mut stripped = String::with_capacity(written.len());
    let mut depth = 0usize;
    for character in written.chars() {
        match character {
            '<' => depth += 1,
            '>' if depth > 0 => depth -= 1,
            _ if depth == 0 => stripped.push(character),
            _ => {}
        }
    }
    stripped
}

fn alias_target_of(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    class: &str,
) -> Option<(String, Option<String>)> {
    // **A qualifier's arguments are not the alias's arguments, and they have to come off first.**
    //
    // The split below separates an alias's **own** template argument list (`enable_if_t<int, double>`) and takes the
    // first `<` it finds. In `outer<int>::handle_type` the first `<` opens the *qualifier's* list, so the head became
    // `outer` — the class itself, which is not an alias — and the walk never found the member typedef. Measured:
    // `outer<int>::handle_type h; h.` offered `outer`'s own members while `outer::handle_type h;` (the same class
    // without the argument) offered the target's. Stripping runs only when the `<` is left of the last `::`, which is
    // exactly the shape of a qualified name whose qualifier is a template-id.
    let stripped_qualifier = without_template_arguments(class);
    let class = match (class.rfind('<'), class.rfind("::")) {
        (Some(argument_list), Some(scope)) if argument_list < scope => stripped_qualifier.as_str(),
        _ => class,
    };
    // **The arguments come off before the name is looked up, and go back on afterwards.**
    //
    // `enable_if_t<int, double>` is an alias *template*, and the index files it under the bare name `enable_if_t` —
    // so a lookup made with the whole spelling found nothing and the alias was never followed: measured, that
    // spelling came back as its own answer. The head is what the index holds, and the written arguments are what the
    // alias's own parameter names have to be replaced by in its target.
    let (head, written_arguments) = match class.split_once('<') {
        Some((head, rest)) => {
            let inside = rest.trim_end().strip_suffix('>').unwrap_or(rest);
            (
                head.trim().to_string(),
                crate::sema::builtins::split_arguments(inside),
            )
        }
        None => (class.to_string(), Vec::new()),
    };
    let class = head.as_str();

    // The buffer first: the alias may be in a file that has never been written to disk.
    let (scope_name, short) = match class.rsplit_once("::") {
        Some((prefix, short)) => (prefix.to_string(), short.to_string()),
        None => (String::new(), class.to_string()),
    };

    if let Some(scope) = scopes.scope_with_qualified_name(&scope_name)
        && let Some(data) = scopes.scope(scope)
        && let Some(binding) = data
            .bindings
            .iter()
            .find(|binding| binding.name.identifier_text() == Some(short.as_str()))
        && let Some(target) = crate::sema::declarations::declared_alias_target(root, binding)
    {
        // **The alias's own parameters replaced by what the use wrote.** A bare alias has no parameters and this
        // changes nothing; a template alias is the case the split above exists for.
        let target = crate::sema::types::substituted_spelling(
            &target,
            &crate::sema::declarations::declared_template_parameters_of(root, binding),
            &written_arguments,
        );
        return Some((
            target,
            (!scope_name.is_empty()).then_some(scope_name.clone()),
        ));
    }

    // **Every declaration of the name, and the target comes from whichever one is the alias.**
    //
    // Asking the singular `definition` here refused the alias outright whenever the name had two declarations —
    // `Unknown(Ambiguous)` is one of the arms below — and `_Mybase` in `std::_Vb_iterator` is exactly that: one
    // alias, matched by its **bare** name in more than one class, because that is how the index narrows a
    // lookup. The walk then returned the spelling unchanged, `direct_members` found no members under a name
    // nothing declares, and `members_of("std::_Vb_iterator::_Mybase")` answered **zero members** for a class
    // whose base has twenty-two. The same shape as `bases_of`: a name declared more than once is not a name
    // that cannot be read, it is a name that has to be asked for in the plural.
    match index.definitions(class, path) {
        Known::Yes(found) => found.found.iter().find_map(|declaration| {
            (declaration.fact.kind == crate::DeclKind::Type)
                .then(|| declaration.fact.type_of.clone())
                .flatten()
                .map(|target| {
                    (
                        crate::sema::types::substituted_spelling(
                            &target,
                            &declaration.fact.parameters,
                            &written_arguments,
                        ),
                        declaration.fact.scope.clone(),
                    )
                })
        }),
        Known::Unknown(_) | Known::No => None,
    }
}

/// Is this spelling a declaration this analysis can see?
///
/// Used to choose between the two ways of reading an alias's target — relative to the alias's scope, or as a
/// spelling in its own right — and deliberately a *cheap* question: a scope in the buffer or one fact in the
/// index is answered without walking anything.
fn is_declared(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    path: &Path,
    spelling: &str,
) -> bool {
    if scopes.scope_with_qualified_name(spelling).is_some() {
        return true;
    }

    // **`Ambiguous` is declared.** A class template with a forward declaration and a definition answers with
    // more than one declaration, and [`ProjectIndex::definition`] turns that into
    // `Unknown(Ambiguous(…))` — which `matches!(…, Known::Yes(_))` reads as "not here". The question this
    // function asks is *is the name declared*, not *is there exactly one declaration of it*, and the two
    // differ for most of the standard library.
    //
    // Measured: `alias_target_of` resolves `_Alty_traits` to `allocator_traits<_Alty>` declared in
    // `std::basic_string`, and the candidate that should answer is `std::allocator_traits` — a name the index
    // holds **twice** (`xmemory:554` forward-declares it, `755` defines it). Rejected here, the walk fell back
    // to `std::basic_string::allocator_traits`, a spelling nothing declares, and `members_of` reported
    // `NotDeclaredHere("std::basic_string::allocator_traits")` one scope short of the answer.
    matches!(
        index.definition(spelling, path),
        Known::Yes(_) | Known::Unknown(UnknownReason::Ambiguous(_))
    )
}

/// The declaration of `member` written **directly** in `class`, or `None`.
///
/// The qualified name `<class>::<member>`, which is why nothing here needs to know what a class *is*: the file
/// being edited is asked first through its scope tree, and the index second — the two-layer split
/// [`definition_across_files`] makes, for the same reason.
/// **A spelling with its namespace-alias prefixes followed** — `std::views::_Filter` → `std::ranges::views::_Filter`.
///
/// libstdc++ writes `namespace views = ranges::views;`, so every name inside it can be written through the alias.
/// `members_of` was taught to follow the alias for the **namespace itself**; a type, a member or a base spelled one level
/// deeper (`std::views::_Filter`, `std::views::filter`) needs the same substitution in its prefix.
///
/// Longest prefix first, so `a::b::c` asks about `a::b` before `a` — a namespace declared inside another one is the case
/// that needs it. A spelling with no alias in it comes back unchanged, which is what keeps this additive.
fn through_a_namespace_alias(index: &ProjectIndex, path: &Path, spelling: &str) -> String {
    const DEPTH: usize = 4;
    let mut rewritten = spelling.to_string();
    for _ in 0..DEPTH {
        let segments: Vec<&str> = rewritten.split("::").collect();
        if segments.len() < 2 {
            return rewritten;
        }
        let mut changed = false;
        for take in (1..segments.len()).rev() {
            let prefix = segments[..take].join("::");
            let Some(found) = index.definition(&prefix, path).value() else {
                continue;
            };
            if found.fact.kind != crate::DeclKind::Namespace {
                continue;
            }
            let Some(target) = found.fact.type_of.as_deref() else {
                continue;
            };
            if target == prefix {
                continue;
            }
            let qualified = if target.contains("::") {
                target.to_string()
            } else {
                match &found.fact.scope {
                    Some(scope) => format!("{scope}::{target}"),
                    None => target.to_string(),
                }
            };
            if qualified == prefix {
                continue;
            }
            rewritten = format!("{qualified}::{}", segments[take..].join("::"));
            changed = true;
            break;
        }
        if !changed {
            return rewritten;
        }
    }
    rewritten
}

fn direct_member(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    class: &str,
    member: &str,
    arguments: Option<&[String]>,
) -> Option<(DeclFact, PathBuf)> {
    // An alias has no members of its own, so the spelling is followed to the class it names before anything is
    // looked up: `std::string`'s members are `std::basic_string`'s. This is the one place a spelling becomes a
    // class for a **single** member, which is why the step lives here rather than at every caller.
    let class = &resolve_aliases(index, scopes, root, path, class);

    // A class declared in this file is looked up here first, which is what makes the whole query work on a buffer
    // that has never been written to disk. The declared type is filled in from the tree, because a member of a
    // member is exactly what a nested access asks for next.
    if let Some(scope) = scopes.scope_with_qualified_name(class)
        && let Some(scope_data) = scopes.scope(scope)
        && let Some(binding) = scope_data
            .bindings
            .iter()
            .find(|binding| binding.name.identifier_text() == Some(member))
    {
        return Some((fact_from_binding(root, class, binding), path.to_path_buf()));
    }

    // Several declarations of one name **in one class** are overloads, not an ambiguity. The language keeps them in
    // a single overload set and picks by argument types, which this layer does not have — and a cursor still needs
    // one answer, so the first in declaration order is it. That is the rule `definition_at` already uses within a
    // scope, and it is why [`ProjectIndex::declarations_in`] is asked here rather than
    // [`ProjectIndex::definition`], whose "several visible declarations" answer is right for a *name* and wrong
    // for a member: measured on the closure of `<string>`, every real member (`size`, `find`, `substr`) has
    // several declarations, so a member lookup that called that ambiguous reported `NotDeclaredHere` for the whole
    // standard library.
    //
    // A consumer that wants all of them asks [`members_of`], which is the query that exists for it — the split is
    // "a jump takes the first, a list takes them all".
    //
    // # A known wrong answer this rule can give, and the fix it needs
    //
    // **The declarations in one scope are not always overloads of one another.** A class template's *partial
    // specializations* are filed under the same scope as the primary — `atomic<shared_ptr<_Ty>>` and `atomic<_Ty>`
    // both have `qualified_name() == "std::atomic"` — so taking the first name match can take a **specialization's**
    // member for an instantiation that does not match its pattern.
    //
    // Measured, and it is a wrong type rather than a missing one: `std::shared_ptr<int> sp; std::atomic<int>
    // counter; auto n = counter.load();` answered **`shared_ptr<int>`** — the return of
    // `atomic<shared_ptr<_Ty>>::load` — because `<memory>` was indexed before `<atomic>` and its specialization came
    // first. Five declarations named `std::atomic::load` are visible and only one is the primary's.
    //
    // # The rule that is here
    //
    // [`DeclFact::pattern`] is the class's own name as its declaration wrote it — `atomic<_Ty>` for the primary,
    // `atomic<shared_ptr<_Ty>>` for the specialization — and a candidate is kept when its pattern matches the
    // arguments the **use** wrote: a pattern argument that is one of the class's own parameter names is a **slot**
    // and takes whatever the use put there, and anything else has to be equal to it. So `atomic<_Ty>` matches
    // `atomic<int>` and `atomic<shared_ptr<_Ty>>` does not — which is the wrong answer this removes.
    //
    // The arguments arrive as a parameter rather than being read off `class`, because **the class spelling reaching
    // this function has already been stripped to its bare name** — measured: `std::atomic`, never `std::atomic<int>`.
    // The pairing exists one step up, in `member_access_class_and_arguments`, and callers that have it pass it.
    //
    // **Two other fixes were tried and are not here**, so that nobody writes them again. Refusing whenever the
    // candidates disagree removes the wrong answer and also removes `v.begin()` — `vector`'s `const` and non-`const`
    // overloads return `iterator` and `const_iterator`, so they "disagree" too, and that is a call every file makes:
    // measured on a one-line fixture, one `auto` went from an answer to a refusal. Preferring the candidate whose
    // return type is one of the class's own parameters (`atomic<_Ty>::load` returns `_Ty`) keeps that fixture right
    // and does nothing for `begin`, whose overloads both return compound spellings.
    // **The class spelling carries its own arguments, and the declarations are filed under the bare name.**
    //
    // `enable_if<__is_same(int, int), double>` is a class *template applied to arguments*: the index holds the
    // primary and the partial specialization under `enable_if`, so a lookup made with the whole spelling found no
    // declaration at all — and the member then resolved to its own name, which is what a cursor in `A<B>::type` was
    // answered with. The arguments written in the spelling are also exactly what the candidate patterns are compared
    // against, so they are not merely dropped: they are what picks the specialization whose first slot is `true`.
    //
    // A caller that already knows the arguments (from an object's type, say) passes them itself; one that does not —
    // the nested-name walk, which has only a spelling — gets them here.
    let from_the_spelling: Option<Vec<String>> = class.split_once('<').map(|(_, rest)| {
        crate::sema::builtins::split_arguments(rest.trim_end().strip_suffix('>').unwrap_or(rest))
    });
    let (class, arguments) = match (class.split_once('<'), from_the_spelling.as_ref()) {
        (Some((head, _)), Some(written)) => (head.trim(), Some(written.as_slice())),
        _ => (class.as_str(), arguments),
    };

    if let Some(found) = index
        .declarations_in(class, path)
        .into_iter()
        .find(|declaration| {
            declaration.fact.name == member
                && a_pattern_matches(
                    declaration.fact.pattern.as_deref(),
                    &declaration.fact.parameters,
                    arguments,
                )
        })
    {
        return Some((found.fact.clone(), found.file.clone()));
    }

    // Nothing is scoped to that class, so the last thing to try is the qualified spelling itself: a member defined
    // out of line can have been filed under a spelling the class's own scope is not (`C::f` for a definition
    // written outside `C`), and that is exactly what this lookup is for.
    match index.definition(&format!("{class}::{member}"), path) {
        Known::Yes(found) => Some((found.fact, found.file)),
        Known::Unknown(_) | Known::No => None,
    }
}

/// **Does this declaration's class pattern match the arguments the use wrote?**
///
/// See the rule where it is used, in [`direct_member`]. `None` for either side is "cannot be compared" and answers
/// `true`: a class with no pattern is an ordinary class and matches any use of its name, and a use whose arguments
/// could not be read is not evidence against the declaration. That direction is deliberate — this rule removes a
/// **wrong** answer, and a spelling it could not read must not remove a right one.
fn a_pattern_matches(
    pattern: Option<&str>,
    parameters: &[String],
    written: Option<&[String]>,
) -> bool {
    let (Some(pattern), Some(written)) = (pattern, written) else {
        return true;
    };

    // **The whole pattern, once.** `arguments_in_a_spelling` finds the outermost `<…>` itself and splits at the
    // commas that are not inside brackets, so handing it the part between the brackets — which is what this did
    // first — makes it split again at the *inner* `<`: `shared_ptr<_Ty>` produced the slots `["_Ty"]`, `_Ty` is one
    // of the class's own parameters, and the specialization matched `atomic<int>` after all. The wrong answer
    // survived a version whose whole purpose was to remove it, and the shape of the mistake is the one this file
    // keeps making: a reader that takes a spelling apart twice.
    let Some(slots) = arguments_in_a_spelling(pattern) else {
        return true;
    };
    if slots.len() != written.len() {
        return true;
    }

    slots.iter().zip(written).all(|(slot, argument)| {
        let slot = slot.trim();
        // A **slot** is one of the class's own parameters, and takes whatever the use put there; anything else has
        // to be equal to it. `_Ty` against `int` matches; `shared_ptr<_Ty>` against `int` does not.
        parameters.iter().any(|name| name == slot) || slot == folded_for_matching(argument).trim()
    })
}

/// The arguments written between the outermost `<` and `>` of a spelling — `atomic<int>` gives `["int"]`, and a
/// spelling with no angle brackets gives `None`.
///
/// Split at the commas that are **not inside brackets**, which is the rule [`written_parameters`] uses for a
/// parameter list and for the same reason: `pair<int, int>` is one argument.
fn arguments_in_a_spelling(written: &str) -> Option<Vec<String>> {
    let (_, after) = written.split_once('<')?;
    let inside = after.trim_end().strip_suffix('>')?;

    let mut out = Vec::new();
    let mut depth = 0usize;
    let mut at = 0usize;
    for (index, character) in inside.char_indices() {
        match character {
            '<' | '(' | '[' => depth += 1,
            '>' | ')' | ']' => depth = depth.saturating_sub(1),
            ',' if depth == 0 => {
                out.push(inside[at..index].to_string());
                at = index + 1;
            }
            _ => {}
        }
    }
    out.push(inside[at..].to_string());

    let out: Vec<String> = out
        .into_iter()
        .map(|argument| argument.trim().to_string())
        .filter(|argument| !argument.is_empty())
        .collect();
    (!out.is_empty()).then_some(out)
}

/// One binding as a [`DeclFact`], under the qualified name of the scope it was written in.
///
/// The single reader of a binding's fact-shaped fields, shared by the single-member query and the member-list
/// query so that `Widget::size`'s type and `Widget`'s member `size` cannot come out differently: both are read
/// out of the tree through [`declared_type_of`](crate::sema::declarations::declared_type_of) and
/// [`declared_bases_of`](crate::sema::declarations::declared_bases_of), and a second call site would be a second
/// answer to "what does this declaration say".
///
/// The guard is [`FactGuard::Unconditional`] because a binding carries none: the region a declaration sits in is
/// a fact about the text, and the layer that sweeps the directives fills it in when the summary is built — see
/// [`build_facts`](crate::sema::declarations::build_facts).
///
/// # The two fields that are not answered on this path
///
/// A fact built from the **buffer's** scope tree has had no directive sweep and has no diagnostic list, so two of
/// its fields are defaults rather than answers: `guard` says `Unconditional` even for a member written inside an
/// `#if`, and `clean` says `true` even in a buffer that does not parse. Both are gaps rather than decisions, and
/// they are stated here rather than left to be discovered: this path is handed a **node** and the tree's
/// diagnostics are not on it, so a caller that needs either field has to ask the summary — which does have them —
/// and a consumer showing a member list has nothing to gain from either, which is why neither was worth
/// threading the tree through every query for. The same applies to the facts [`member_across_files`] returns
/// from this path.
fn fact_from_binding(
    root: &cpp_parser::CppSyntaxNode,
    class: &str,
    binding: &crate::Binding,
) -> DeclFact {
    fact_from_binding_with(
        &crate::sema::declarations::DeclarationShapes::of(root),
        root,
        class,
        binding,
    )
}

/// **One binding as a fact, given the file's shape table** — the form a caller with a *list* of bindings uses.
///
/// Every field below is read out of the tree by a reader that wants a
/// [`DeclarationShapes`](crate::sema::declarations::DeclarationShapes) table, and that table is a pass over the whole
/// tree. Asking `fact_from_binding` per member therefore built the table once per member, which is quadratic in a
/// class: measured on `std::vector` in libstdc++'s `<bits/stl_vector.h>` (151 members), a member list cost **927 ms**
/// and the answers are a lookup each. Passing the table in makes the whole list cost one pass — the same defect, and
/// the same fix, that [`DeclarationShapes`](crate::sema::declarations::DeclarationShapes) records for the index
/// builder.
fn fact_from_binding_with(
    shapes: &crate::sema::declarations::DeclarationShapes,
    root: &cpp_parser::CppSyntaxNode,
    class: &str,
    binding: &crate::Binding,
) -> DeclFact {
    let _ = root;
    DeclFact {
        // **The spelling, the same one the index stores** — `operator[]`, `~Widget`, `operator int`.
        //
        // This path used to answer an empty name for every declaration without an identifier, on the argument that
        // `~Derived` and `~Base` must not become one name. That argument is about *hiding*, and the spelling answers
        // it: the two destructors have different spellings, so nothing is hidden that should not be. What the empty
        // name cost was measured: a class whose member is `operator[]` answered `members_of → [""]`, so an operator
        // was invisible to a member list — and a completion after `.`, a hover and every member query with it.
        //
        // The name alone is a fact about the declaration and changes no inference.
        name: binding.name.text(),
        // `None` for an empty spelling, which is what a caller listing the names of a **body** passes: a local has
        // no qualified scope at all, and `Some("")` would be a scope that matches nothing while looking like one.
        // Every other caller passes the class or namespace the binding is in.
        scope: (!class.is_empty()).then(|| class.to_string()),
        // Known, and always: this path is handed the class a member belongs to, so there is no scope the file's text
        // could have left open. See [`DeclFact::scope_unknown`].
        // Answered rather than defaulted, and the answer is always `false`: this path exists for **members**, and a
        // member is declared in a class body by construction — the `class` spelling it is keyed by has no meaning
        // inside a function. A local class's members are members of that class, and the caller that asked for them
        // asked by name. See [`DeclFact::local`].
        local: false,
        // `None`, and it is a **gap rather than an answer** — the same kind [`fact_from_binding`]'s note above
        // states for `clean` and `access`: this path is handed a node and no scope tree, so it cannot say which
        // namespaces enclose a body. It is unreachable in practice here, because this path exists for members
        // and a member is never a local; the caller that does need it asks the file's summary, where the reading
        // was made with the scopes in hand. See [`DeclFact::in_namespace`].
        in_namespace: None,
        kind: crate::DeclKind::from_binding_kind(binding.kind),
        // The same bits the index fills — a fact must say the same thing whichever path produced it.
        // **No rendering here**: this path is handed a node and no file text, and the attribute is a sibling of the
        // declaration — a member query never asks for `[[maybe_unused]]`, so the bit is left unset rather than guessed.
        modifiers: crate::sema::declarations::declared_modifiers_with(shapes, binding),
        // **The other answer the index writes**, and for the same reason: a member function's body is where a
        // `delete` lives, so a call site that asks "does this free my argument" must not depend on which path built
        // the fact.
        frees: crate::sema::declarations::freed_parameters_of(root, binding),
        // **Read by the index path too**, when a member query leaves the file: the annotation is a fact like any other,
        // and a hover on a `UPROPERTY` member should find its specifiers wherever the member is declared.
        reflection: None,
        type_of: crate::sema::declarations::declared_type_of_with(shapes, binding),
        // Answered here as well, because **members** are exactly where a call happens: `fac.build().size` needs the
        // return type of a member function that the file being edited declares. See [`DeclFact::returns`].
        // **The deduction, when the file wrote no return type.** `declared_returns_of_in` answers only what is written, and
        // `auto` is not — the index's fact deduces through `declared_returns_of`, so this one must too, or the same function
        // has a return type in one answer and none in the other. Measured: `make_sized` printed `std::array<int, Size>` from
        // `facts` and "a function" from the hover.
        returns: crate::sema::declarations::declared_returns_of_in(shapes, root, binding)
            .or_else(|| crate::sema::declarations::declared_returns_of(root, binding)),
        split_by_a_directive: crate::sema::declarations::split_by_a_directive_with(shapes, binding),
        bases: crate::sema::declarations::declared_bases_of_with(shapes, binding),
        // **The same three fields the index fills**, because a fact must say the same thing whichever path produced it.
        //
        // These were empty here, with the argument that "substitution is the caller's step".
        // Substitution still is — what these fields carry is the *names* to substitute and the
        // class's written **pattern**, and a caller that has the use's arguments cannot pair them
        // without them.
        parameters: crate::sema::declarations::declared_template_parameters_with(shapes, binding),
        constraints: Vec::new(),
        // **The clause the declaration writes**, from the same shape table the modifiers come from — the two paths that
        // build a fact must say the same thing (a member queried from the file's own scopes went through this one, and
        // its card showed the declaration without the `requires` the index had).
        requires_clause: crate::sema::declarations::the_requires_clause_with(shapes, binding),
        parameter_defaults: crate::sema::declarations::declared_parameter_defaults_with(
            shapes, binding,
        ),
        pattern: crate::sema::declarations::pattern_of(shapes, binding),
        // …but the **parameter list as written** is here, because this is the path a member list's detail line is
        // built from: `size()` and `size_type size() const` are two rows a reader tells apart by exactly this, and
        // the declaration is in the buffer, so reading it costs one walk up the tree. See
        // [DeclFact::parameter_list].
        parameter_list: match binding.kind {
            crate::BindingKind::Function
            | crate::BindingKind::Constructor
            | crate::BindingKind::Destructor
            | crate::BindingKind::ConversionFunction
            | crate::BindingKind::OperatorFunction
            | crate::BindingKind::LiteralOperator => {
                crate::sema::declarations::declared_parameters_with(shapes, binding)
            }
            _ => None,
        },
        // **Who may name it**, read the same way and for the same reason: a member list built from the buffer is
        // what a completion after `.` offers, and a `private:` member must not be in it. See [DeclFact::access].
        access: shapes.access_at(binding.name_range.start_offset),
        // …and whether an importer may, which is the same kind of question about the same position — see
        // [DeclFact::exported]. A buffer's file is very often the module interface unit being edited.
        exported: shapes.exported_at(binding.name_range.start_offset),
        // **A member is a definition of itself** — this path exists for members, and a class body's members have no
        // separate forward declaration to be confused with.
        definition: true,
        range: binding.range,
        name_range: binding.name_range,
        clean: true,
        guard: FactGuard::Unconditional,
    }
}

/// **Is this base spelling one of the class's own template parameters?** — the filter [`members_of`] applies.
///
/// The head of the spelling is what is compared, because that is the name a class is looked up by: `_Tp` and `_Tp<T>`
/// are the same parameter, while `_Vector_base<_Tp, _Alloc>` is a class whose arguments happen to be parameters. A
/// destructor or a qualified spelling answers `false`, which is the direction that keeps a base.
fn names_a_template_parameter(spelling: &str, parameters: &[String]) -> bool {
    if parameters.is_empty() {
        return false;
    }
    let head = without_arguments(spelling.trim());
    let head = head.strip_prefix("::").unwrap_or(head);
    parameters
        .iter()
        .any(|parameter| parameter == head || parameter == head.rsplit("::").next().unwrap_or(head))
}

/// The base classes `class` was written with, from this file or from the index.
///
/// # Names, not spellings
///
/// What comes back is normalized for **lookup**: `public Base<int>` is the class `Base`. The spelling the file
/// wrote stays in [`DeclFact::bases`], which is a fact about the text; a base here is a name to find a class by,
/// and the template arguments say which *type* is inherited rather than which class declares the members. The
/// members of `Base<int>` are the members of `Base`'s primary template, which is the most useful answer available
/// without instantiating anything — and the same rule [`base_type_name`] applies to a declared type.
///
/// # Why this is `Known` and not a list
///
/// "This class has no bases" and "nothing here says what this class inherits from" are different statements, and
/// an empty `Vec` would merge them. The member **lookup** treats them alike — a base it cannot reach contributes
/// no members either way, so it walks on — while the member **list** reports the gap, because a list is a claim
/// about what a type has.
fn bases_of(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    class: &str,
) -> Known<Vec<String>> {
    bases_of_inner(index, scopes, root, path, class)
}

fn bases_of_inner(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    class: &str,
) -> Known<Vec<String>> {
    // In this file: the class scope's parent holds the binding of the class's *name*, which is the declaration the
    // bases were written on. Asking the tree through that binding is the same walk the fact builder makes, so the
    // two cannot disagree about what a class inherits from.
    if let Some(scope) = scopes.scope_with_qualified_name(class)
        && let Some(data) = scopes.scope(scope)
        && let Some(parent) = data.parent
        && let Some(name) = class.rsplit("::").next()
        && let Some(binding) = scopes.scope(parent).and_then(|scope| {
            scope
                .bindings
                .iter()
                .find(|binding| binding.name.identifier_text() == Some(name))
        })
    {
        return Known::Yes(lookup_names(&crate::sema::declarations::declared_bases_of(
            root, binding,
        )));
    }

    // **Every declaration of the class, not the first one, and `Ambiguous` is not a failure.**
    //
    // A class template is forward-declared and then defined, and only one of the two carries the base clause:
    // `xmemory:554` writes `struct _NO_SPECIALIZATIONS_CITING(…) allocator_traits;` and `755` writes the same
    // class with `: conditional_t<…>` after it. `definition` answers with the singular, so a class declared
    // twice comes back `Unknown(Ambiguous)` and the walk gave up — and even where it answers `Yes`, the one
    // declaration it picked is as likely to be the forward declaration, whose `bases` is empty, as the
    // definition. The plural [`ProjectIndex::definitions`] is the query that returns both, so the bases are
    // the union of what every declaration was written with, in the order the declarations came in.
    //
    // **And the declarations are looked for by their *bare* name as well as by the qualified one**, which is what
    // makes MSVC's stream classes work at all. Measured, and it cost `std::ios::` every one of its members:
    //
    // ```text
    //   std :: basic_ios  @ iosfwd:5011   bases []                 <- the forward declaration, qualified
    //   <file scope> :: basic_ios @ ios:507 bases ["ios_base"]     <- the definition, filed at file scope
    // ```
    //
    // `ios:507` is the definition and it is filed **unqualified**, because a raw reading of `<ios>` does not expand
    // `_STD_BEGIN` — the macro that opens `namespace std` — so the class lands at file scope in that reading while
    // the cooked reading of the same file places it in `std`. A lookup keyed on `std::basic_ios` therefore finds
    // only the forward declaration, whose base clause is empty, and answers "this class has no bases": `fail`,
    // `eof`, `good` and `rdbuf` vanish from `std::ios::` while `unlisted` stays empty, so the answer does not even
    // claim to be incomplete.
    //
    // A **forward declaration can never contribute a base clause**, so taking the union over every declaration of
    // the name cannot invent one — the same over-approximation, and the same direction, as [`lookup_names`] below.
    match index.definitions(class, path) {
        Known::Yes(found) => {
            let mut bases: Vec<String> = Vec::new();
            for declaration in &found.found {
                for base in lookup_names(&declaration.fact.bases) {
                    if !bases.contains(&base) {
                        bases.push(base);
                    }
                }
            }
            if bases.is_empty()
                && let Some(bare) = class.rsplit("::").next()
            {
                for (_, fact) in index.every_fact_named(bare) {
                    if fact.kind != crate::DeclKind::Type {
                        continue;
                    }
                    for base in lookup_names(&fact.bases) {
                        if !bases.contains(&base) {
                            bases.push(base);
                        }
                    }
                }
            }
            Known::Yes(bases)
        }
        Known::Unknown(reason) => Known::Unknown(reason),
        Known::No => Known::No,
    }
}

/// Base spellings as names a class can be looked up by, in the order they were written.
///
/// **A base clause is not always a class name**, and the names it *does* mention are what a member lookup has
/// to walk into. MSVC's `<xmemory>` writes
///
/// ```cpp
/// struct _NO_SPECIALIZATIONS_CITING("N5014 …") allocator_traits
///     : conditional_t<_Is_default_allocator<_Alloc>::value, _Default_allocator_traits<_Alloc>,
///           _Normal_allocator_traits<_Alloc>> {};
/// ```
///
/// (line 755), and the class it actually derives from is **one of the two named inside** — which one is a
/// question about `conditional_t`, and answering it is metaprogramming this layer does not do. Taking the
/// clause at its word would walk into `conditional_t`, which is an alias with no bases, and stop one step
/// short of every member the class actually has: measured, `members_of("std::allocator_traits")` returned
/// **zero** members while `pointer` and `difference_type` are in `_Normal_allocator_traits`.
///
/// So every class name the clause mentions is offered, which is an **over-approximation on purpose**: it can
/// only find a member one of the candidates really has, and the direction to err in is "found" rather than
/// "missing". A language server that reports a name as undeclared because it could not evaluate a
/// `conditional_t` is one that reports the standard library as broken.
fn lookup_names(bases: &[String]) -> Vec<String> {
    let mut names: Vec<String> = Vec::new();

    for base in bases {
        let parsed = crate::sema::types::parse_type_spelling(base);
        collect_class_names(&parsed, &mut names);
    }

    names
}

/// Every class name a parsed type mentions, outermost first, each kept once.
///
/// The walk is over the **parsed type** rather than its text, so `_Normal_allocator_traits<_Alloc>`
/// contributes `_Normal_allocator_traits` and not `_Alloc`, and a class named inside a nested template
/// argument is found at whatever depth it was written.
fn collect_class_names(ty: &crate::sema::types::Type, into: &mut Vec<String>) {
    if let Some(name) = ty.class_name()
        && !name.is_empty()
        && !into.iter().any(|kept| kept == name)
    {
        into.push(name.to_string());
    }

    for argument in ty.arguments() {
        collect_class_names(argument, into);
    }
}

/// The spelling a base-clause name resolves to, given the class it was written in.
///
/// A base name is looked up **from the scope enclosing the class**, outward — so `_Tree` written in
/// `namespace std { class map : _Tree<…> }` names `std::_Tree`, and a `_Tree` at file scope could not answer it
/// even if there were one. Both base walks used to look for the spelling exactly as written, and MSVC's `<map>`
/// inherits from `_Tree`, declared in `<xtree>` inside `_STD_BEGIN` (= `namespace std {`): the member list reported
/// `UnlistedBase { "_Tree", NotDeclaredHere }` while `std::_Tree` sat in the index with 126 members, four of them
/// `find` — which is what the last two queries of `examples/std_query.rs` were failing on (measured).
///
/// The enclosing scopes are tried innermost first and **the spelling as written is the last candidate**, which is
/// what the rule says (the global name space is the outermost scope) and also what keeps a base named at file
/// scope — `struct Derived : public Base` — answering as it always did.
///
/// A base that already carries a `::` is returned untouched: a qualified name is a claim about where the name
/// lives, and `std::_Tree` written in a class in `std` means that name and no other. A **leading** `::` is such a
/// claim too, and `base_type_name` has already taken it off; the name it leaves is the global one, which is what
/// the last candidate below is.
///
/// The same one step of the same rule is what [`resolve_aliases`] does for an alias's target and documents there;
/// both ask it through [`is_declared`], so "the buffer first, the index second" is not decided twice.
fn resolved_in_the_enclosing_scopes(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    path: &Path,
    owner: &str,
    base: &str,
) -> String {
    if base.contains("::") {
        return base.to_string();
    }

    let mut enclosing = owner;
    while let Some((outer, _)) = enclosing.rsplit_once("::") {
        let candidate = format!("{outer}::{base}");
        if is_declared(index, scopes, path, &candidate) {
            return candidate;
        }
        enclosing = outer;
    }

    base.to_string()
}

/// The class whose scope encloses `offset`, for `this`.
///
/// The nearest class-like scope on the chain, which is the same answer in a member function, in a nested class's
/// member function (the nested class wins, correctly) and in a default member initialiser.
fn enclosing_class(scopes: &crate::ScopeTree, offset: usize) -> Option<String> {
    let innermost = scopes.scope_at(offset)?;

    scopes.scope_chain(innermost).into_iter().find_map(|scope| {
        let data = scopes.scope(scope)?;
        // One variant for class, struct and union: the difference is access, which is a member's property
        // rather than the scope's. See `ScopeKind`.
        (data.kind == crate::ScopeKind::Class)
            .then(|| scopes.qualified_name_of(scope))
            .flatten()
    })
}

/// **The class a member function's body belongs to**, whether or not that class is declared in this file.
///
/// [`enclosing_class`] answers from the **scope chain**, which is this file's own tree — and for the ordinary layout of
/// C++ that is not enough. `void Widget::grow(int by) { … }` written in `widget.cpp` declares no class scope at all:
/// the class is in the header, so the chain runs from the function straight to the file, `this` had no type, and a
/// member list after `this->` answered `Unknown(UnparsableName)` — measured in
/// `tests/completion.rs::a_member_function_defined_in_another_file_sees_its_class`.
///
/// What the chain *does* say is the definition's **qualified name** — `Widget::grow` — and the class is its prefix.
/// That is the same spelling the index keys a class's members under, so the answer reaches the header through the
/// layer that already exists for exactly this: "the finding is about this file, the knowledge is the project's".
///
/// A free function's qualified name has no `::` and so names no class, which is the right answer for `this` there —
/// there is none.
pub(crate) fn class_of_the_enclosing_definition(
    scopes: &crate::ScopeTree,
    offset: usize,
) -> Option<String> {
    if let Some(class) = enclosing_class(scopes, offset) {
        return Some(class);
    }

    let innermost = scopes.scope_at(offset)?;
    let qualified = scopes.qualified_name_of(innermost)?;

    let (class, _member) = qualified.rsplit_once("::")?;

    (!class.is_empty()).then(|| class.to_string())
}

/// The name of the class a written type names, with the parts that do not affect *which* class it is removed.
///
/// `const Widget&` → `Widget`, `std::vector<int>` → `std::vector`, `struct Widget` → `Widget`, `::Widget` →
/// `Widget`. The goal is a spelling that can be looked up as a qualified name, and every one of those parts is
/// about the type's shape or about which name space it is in rather than about its name. `unsigned long` is left
/// alone: there the words *are* the type, and it names no class anyway.
///
/// # Why the leading `::` comes off
///
/// A leading `::` asks about the **global** name space — a real distinction for a *name* lookup, where dropping it
/// would also match `ns::Widget`, and [`matches`] honours it for exactly that reason. It is not a distinction for
/// this walk, because the walk does not ask "which name space"; it asks for the qualified spelling the index keys
/// on, and a global declaration's spelling is its bare name. Keeping the prefix made `::Widget w;` — the type
/// spelling a consumer hands over verbatim from `DeclFact.type_of` — fail to find a class sitting in the buffer.
/// **Where the `<` is that opens a template argument list running to the end of `written`.**
///
/// `None` for a spelling with no such group — `outer<int>::handle_type` ends with `type`, so its `<` belongs to a
/// *qualifier* and is not a list of the type's own. Nesting is counted backwards so `Box<Pair<int, int>>` answers the
/// `Box` opening and not the `Pair` one.
fn the_trailing_argument_list(written: &str) -> Option<usize> {
    if !written.ends_with('>') {
        return None;
    }
    let mut depth = 0usize;
    for (at, character) in written.char_indices().rev() {
        match character {
            '>' => depth += 1,
            '<' => {
                if depth == 0 {
                    return None;
                }
                depth -= 1;
                if depth == 0 {
                    return Some(at);
                }
            }
            _ => {}
        }
    }
    None
}

pub(crate) fn base_type_name(written: &str) -> &str {
    let mut name = written.trim();

    // **Template arguments, and only the ones at the END of the spelling.**
    //
    // The members of `std::vector<int>` are the members of `std::vector`'s primary template, which is the most useful
    // answer available without instantiating anything. But a **member** of a class template is spelled
    // `outer<int>::handle_type`, and cutting at the first `<` turns that into `outer` — the class, not the member —
    // so every question below was asked about the wrong type. Measured: `outer<int>::handle_type h; h.` offered
    // `outer`'s own typedefs, and a coroutine's `task<int>::handle_type` offered `await_ready`/`take` instead of
    // `resume`/`promise`. The declarators and the leading `::` are taken off first so that the group at the end is
    // really the end (`std::vector<int>*` and `::std::vector<int>` both arrive here).
    loop {
        let before = name;
        // Declarators written after the type: `Widget*`, `Widget&`, `Widget&&`.
        name = name.trim_end_matches(['*', '&']).trim();
        // The global name space, which for a qualified spelling is no prefix at all.
        name = name.strip_prefix("::").unwrap_or(name).trim();
        if let Some(opening) = the_trailing_argument_list(name) {
            name = name[..opening].trim();
        }
        if name == before {
            break;
        }
    }

    // An elaborated specifier: `struct Widget` and `Widget` name one class, and only the second is a spelling the
    // index matches.
    for keyword in ["struct ", "class ", "union ", "enum "] {
        if let Some(rest) = name.strip_prefix(keyword) {
            name = rest.trim();
            break;
        }
    }

    name
}

impl ProjectIndex {
    pub fn new() -> Self {
        ProjectIndex {
            // **Incomplete**, so that a name this index has not been told about is `Unknown` rather than "not
            // defined". An index built by hand has been told nothing, and the default has to be the answer that
            // claims nothing: `Marked::default()` on its own would decide every `#ifdef` in every file as false.
            macros: Marked::default().incomplete(),
            visibility_answers: std::sync::Mutex::new(HashMap::new()),
            type_answers: std::sync::Mutex::new(HashMap::new()),
            type_hits: std::sync::atomic::AtomicU64::new(0),
            type_misses: std::sync::atomic::AtomicU64::new(0),
            visibility: std::sync::Mutex::new(HashMap::new()),
            ..ProjectIndex::default()
        }
    }

    /// Tell the index what the **compilation** defines: the compiler's predefined names, then the command line's
    /// `-D`s.
    ///
    /// One environment for the whole index, which is an approximation the caller should know about: a project
    /// whose files are built with different `-D`s has one environment per *target*, and this models the one the
    /// caller supplies. Recorded rather than guessed at here.
    ///
    /// # Complete or not, and who decides
    ///
    /// The state's own [`Marked::incomplete`] flag is **kept as given**, and that flag is the difference between
    /// two answers to `#ifdef NAME` when nothing the index read defines `NAME`:
    ///
    /// ```text
    /// incomplete  → Unknown  — a file nobody read, or a `-D` nobody mentioned, could define it
    /// complete    → false    — within this compilation, nothing defines it, and the branch is not taken
    /// ```
    ///
    /// The second is what makes `#ifndef NT_INCLUDED / #include <winnt.h> / #endif` decide itself, and it is a
    /// claim about the **inputs**: the caller is saying "these are the compilation's own definitions, and every
    /// `#include` that matters resolved and was indexed". [`crate::Session`] says it when the compiler it discovered
    /// **answered with its predefined macros** — the table `-dM`/`/PD` prints, and the only place the compiler's own
    /// names exist — and a walk that runs into an `#include` it cannot read takes the claim back
    /// ([`Marked::mark_incomplete`]). See `Session::assemble` for what tying the claim to a compile database instead
    /// cost (MSVC's whole standard library, measured).
    ///
    /// A name a *conditional* might define is a smaller doubt and is handled per name: the walk records it with
    /// [`Marked::mark_uncertain`], so `#ifdef` on it is `Unknown` even in a complete environment.
    pub fn with_macros(mut self, macros: Marked) -> Self {
        self.macros = macros;
        self
    }

    /// The macros a compilation starts with — see [`ProjectIndex::with_macros`].
    pub fn macros(&self) -> &Marked {
        &self.macros
    }

    /// Add or replace one file's summary.
    ///
    /// The reverse edges are updated rather than rebuilt: an edit to one file changes only its own out-edges,
    /// and rebuilding the whole map on every keystroke is the cost the per-file design exists to avoid.
    pub fn insert(&mut self, summary: FileSummary) {
        let path = summary.path.clone();
        self.insert_at(&path, summary);
    }

    /// [`ProjectIndex::insert`] for a summary that was **read from the cache**.
    ///
    /// `path` is the file it is being filed under, and it has to be passed rather than taken from the summary
    /// because the two can legitimately differ: a cache entry is keyed on a file's *contents* and the directory it
    /// was compiled in, so two files with identical text side by side share an entry, and the entry's own `path`
    /// records whichever of them was written first. Filing the second under the first's name makes every fact in
    /// it point at the wrong file, and a definition jump into a file the user never mentioned.
    ///
    /// The facts themselves are right either way: a summary's contents are a function of the text *and its
    /// directory* — which is exactly what the key names, and the reason the directory is part of it. Two files
    /// whose keys match have the same declarations, at the same offsets, with the same ranges, *and* the same
    /// resolved includes.
    pub fn insert_at(&mut self, path: &Path, summary: FileSummary) {
        // A new summary can change any condition's answer, so the per-condition memo goes: an answer about
        // visibility can only change when what the index holds changes, and losing one costs a condition, not a
        // walk. See [`ProjectIndex::visibility_answers`].
        if let Ok(mut answers) = self.visibility_answers.lock() {
            answers.clear();
        }
        // **And the inference answers, for the same reason.** A summary that arrives can turn a type's `Unknown` into a
        // class, and nothing computed before it may answer after it.
        if let Ok(mut answers) = self.type_answers.lock() {
            answers.clear();
        }
        if let Ok(mut declared) = self.definition_answers.lock() {
            declared.clear();
        }
        // **The walk memo is dropped per contributor rather than whole** — see [`ProjectIndex::visibility`]. A
        // re-read of a file the index already knew can only change the walks that read it; a file it has never seen
        // can change how an `#include "x.h"` resolves for a closure that does not contain it, so that one clears the
        // map. Measured on `LuaSyntaxTree.cpp`: five walks per diagnostics pull, 33.5 ms, and every pull paid them
        // because a pull inserts before it checks.
        // **"Known" means "the index has filed this path at some point", not "it holds a summary right now".** An
        // edit is `forget` followed by a re-read, so the summary is absent at the moment the re-read inserts it —
        // testing the summaries map made every keystroke look like a brand-new file and cleared the whole walk memo
        // (measured: one keystroke left two walks where the targeted rule should leave one, and the survival this
        // change is for never happened). `known_paths` outlives a forget for exactly this reason.
        let rewritten = normalize(path);
        let known_to_the_index =
            self.known_paths.contains(&rewritten) || self.summaries.contains_key(&rewritten);
        self.known_paths.insert(rewritten.clone());
        if let Ok(mut walks) = self.visibility.lock() {
            if known_to_the_index {
                walks.retain(|_, cached| {
                    cached
                        .contributors
                        .binary_search_by(|file| file.as_str().cmp(rewritten.as_str()))
                        .is_err()
                });
            } else {
                walks.clear();
            }
        }
        // …and every member list this file contributed to, which is the narrow invalidation: a class whose members
        // live in another file keeps its answer. See [ProjectIndex::member_lists].
        self.forget_member_lists(path);
        self.forget_guard_answers(path);
        // …and every macro walk this file was part of, by the rule the visibility memo above states.
        self.forget_macro_walks(path, known_to_the_index);
        let mut summary = summary;
        summary.path = path.to_path_buf();

        let path = normalize(path);

        // Remove the edges the previous version of this file contributed, so that a deleted `#include` stops
        // making its target reachable. Without this, an edge would outlive the line that wrote it.
        let sequence = if let Some(previous) = self.summaries.get(&path) {
            let sequence = self.sequence[&path];

            for target in include_targets(previous) {
                if let Some(includers) = self.included_by.get_mut(&target) {
                    includers.remove(&path);
                }
            }

            // The names the previous text declared and the macros it defined stop being findable under this file.
            self.names
                .remove_declarations(sequence, 0, &previous.declarations);
            self.names.remove_macros(sequence, &previous.macros);

            // **The cooked reading describes the file *under the key it was built with***, so a summary filed under
            // a different key takes it with it. Both halves of the key are the reason: a different content hash means
            // the text changed, and a different context hash means the *compilation* did — the configuration or the
            // directory a relative include resolves against — and a rendering is a function of both.
            //
            // `forget` already drops the summary and the reading together, and that is the ordinary path (an edit, a
            // watched file, a close). This one covers the paths that have no `forget` in them: a re-read that found
            // different bytes, a cache entry replaced by a fresh index, and the whole-project re-read a changed
            // `compile_commands.json` causes. Leaving the reading there would answer for a file nobody has any more,
            // at offsets into words that are gone — a wrong answer rather than a missing one.
            if previous.key != summary.key {
                self.forget_the_readings_of(&path);
            }

            sequence
        } else {
            let sequence = self.next_sequence;
            self.next_sequence += 1;
            self.order.insert(sequence, path.clone());
            // **The key is normalized when it is written**, not when it is asked for. Two readers
            // arrive at this map with two spellings of the same file: the visibility walk hands
            // back the *normalized* paths it built the graph from (`e:/p/app.cpp`), and every query
            // arrives with the path a client or a summary used (`E:/p/app.cpp`). Storing only the
            // second spelling meant the first was dropped silently — the walk said the file was
            // visible, `visible_in_order_of` did not find it, and the query answered as if the file
            // had never been included.
            self.sequence.insert(path.clone(), sequence);
            self.sequence.insert(normalize(Path::new(&path)), sequence);

            // A reading filed before its summary (the contract says it should not be, but `insert_cooked` does not
            // refuse) is findable from the moment the file has a number to be found under — every reading of it,
            // under the id it was filed with.
            if let Some(readings) = self.cooked.get(&path) {
                for (id, reading) in readings.every() {
                    self.names
                        .add_declarations(sequence, id, &reading.declarations);
                }
            }

            sequence
        };

        for target in include_targets(&summary) {
            self.included_by
                .entry(target)
                .or_default()
                .insert(path.clone());
        }

        // **Which file an `import m;` reaches.** The visibility walk ([`ProjectIndex::visible_files`]) holds
        // summaries and nothing else, so this map is what turns a module *name* into the file that declares it —
        // built here, where every file's own reading arrives, and rebuilt for a file when its reading changes (an
        // implementation unit that stops being one takes its name with it).
        //
        // Only an **interface unit** is recorded: an implementation unit declares the module and is not what an
        // importer sees, so pointing `import m;` at one would attribute its declarations to a module that never
        // exported them. A file that declares no module, or declares one as an implementation, records nothing.

        self.module_interfaces
            .retain(|_, declaring| declaring != &path);
        if summary.modules.is_interface
            && let Some(module) = &summary.modules.module
            && summary.modules.partition.is_none()
        {
            // A partition interface unit exports to its own module only — nothing outside may `import m:part;` —
            // so it is not the file an `import m;` in another module reaches.
            self.module_interfaces
                .insert(module.to_string(), path.clone());
        }

        self.names
            .add_declarations(sequence, 0, &summary.declarations);
        self.names.add_macros(sequence, &summary.macros);
        self.summaries.insert(path, summary);
    }

    /// Forget the file at `path`, and the edges its summary contributed.
    ///
    /// The one operation that makes a *deleted* file stop answering. Without it a query would go on finding
    /// declarations in a file that is no longer on disk — the summary is in memory, and nothing about it is
    /// wrong except that it describes something that is gone. The reverse edges go with it, for the same reason
    /// they are removed when a file is re-indexed: an edge outliving the line that wrote it would keep a header
    /// reachable from a file that no longer includes it.
    ///
    /// Returns whether there was anything to forget, which is what lets a watcher report "this event changed
    /// nothing" rather than counting every ignored path as work.
    pub fn forget(&mut self, path: &Path) -> bool {
        let path = normalize(path);
        let Some(summary) = self.summaries.remove(&path) else {
            return false;
        };

        // **A file that is gone changes answers, so the memos go** — the per-condition answers and the declaration
        // answers whole, and the walks whose closure contained the file. A walk that never read it cannot answer
        // differently, and keeping those is what stopped a keystroke from paying for five closure walks: measured on
        // `LuaSyntaxTree.cpp`, 33.5 ms of a 200 ms pull. The contributor rule is also a correctness fix rather than
        // only bookkeeping — the test `name_index_agrees_with_the_scan::after_every_kind_of_edit` caught a query
        // between a forget and the next insert answering from a walk that still had the forgotten file in it.
        if let Ok(mut answers) = self.visibility_answers.lock() {
            answers.clear();
        }
        // **And the inference answers, for the same reason.** A summary that arrives can turn a type's `Unknown` into a
        // class, and nothing computed before it may answer after it.
        if let Ok(mut answers) = self.type_answers.lock() {
            answers.clear();
        }
        if let Ok(mut walks) = self.visibility.lock() {
            walks.retain(|_, cached| {
                cached
                    .contributors
                    .binary_search_by(|file| file.as_str().cmp(path.as_str()))
                    .is_err()
            });
        }
        if let Ok(mut declared) = self.definition_answers.lock() {
            declared.clear();
        }

        // A file that is gone is a contributor that changed: every member list it was made of is dropped.
        self.forget_member_lists(Path::new(&path));
        self.forget_guard_answers(Path::new(&path));
        // **And every macro walk that read it.** A walk that never did cannot answer differently, which is what keeps
        // a header's answers alive across an edit to the `.c` file that includes it.
        self.forget_macro_walks(Path::new(&path), true);

        for target in include_targets(&summary) {
            if let Some(includers) = self.included_by.get_mut(&target) {
                includers.remove(&path);
            }
        }
        // **The cooked readings go with it, and they need the sequence to be taken back from the name index** — so
        // they are dropped before the file loses its number. A file that is no longer indexed must not keep answering
        // declaration queries out of a rendering nobody has any more: the same rule as the summary, for the same
        // reason, because an answer about a file that is gone is worse than no answer.
        self.forget_the_readings_of(&path);
        let sequence = self.sequence.remove(&path).or_else(|| {
            // **Both spellings go**, for the reason the insert keeps both: a file forgotten under one spelling that
            // stayed findable under the other would answer with declarations the index no longer has.
            self.sequence.remove(&normalize(Path::new(&path)))
        });
        if let Some(sequence) = sequence {
            self.order.remove(&sequence);
            self.names
                .remove_declarations(sequence, 0, &summary.declarations);
            self.names.remove_macros(sequence, &summary.macros);
        }

        true
    }

    /// **The type of an expression, as a previous request answered it** — see [`ProjectIndex::type_answers`].
    pub(crate) fn a_remembered_type(
        &self,
        path: &Path,
        expression: &cpp_parser::CppSyntaxNode,
    ) -> Option<Known<(Type, PathBuf)>> {
        let key = the_type_key(path, expression);
        let remembered = self
            .type_answers
            .lock()
            .ok()
            .and_then(|answers| answers.get(&key).cloned());
        if remembered.is_some() {
            self.type_hits
                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        } else {
            self.type_misses
                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        }
        remembered
    }

    /// **How the inference memo has done**: `(answered from the memo, had to compute)`. The second number is what the
    /// memo exists to make small, and the pair is what a test or a probe can assert on.
    pub fn type_cache_stats(&self) -> (u64, u64) {
        (
            self.type_hits.load(std::sync::atomic::Ordering::Relaxed),
            self.type_misses.load(std::sync::atomic::Ordering::Relaxed),
        )
    }

    /// File one inference answer for the requests that follow.
    pub(crate) fn remember_a_type(
        &self,
        path: &Path,
        expression: &cpp_parser::CppSyntaxNode,
        answer: &Known<(Type, PathBuf)>,
    ) {
        let key = the_type_key(path, expression);
        if let Ok(mut answers) = self.type_answers.lock() {
            if answers.len() >= MAX_TYPE_ANSWERS {
                answers.clear();
            }
            answers.insert(key, answer.clone());
        }
    }

    pub fn len(&self) -> usize {
        self.summaries.len()
    }

    pub fn is_empty(&self) -> bool {
        self.summaries.is_empty()
    }

    /// The summary of the file at `path`, if it has been indexed.
    ///
    /// # Why the probe counter is on this line
    ///
    /// Whether that is worth 73 call sites changing their return type depends on the **working
    /// set** — how many distinct summaries a session actually touches — and that number can only be
    /// counted here, at the one place every reader goes through. `CPPLS_TRACE_SUMMARIES=1` turns it
    /// on.
    pub fn summary(&self, path: &Path) -> Option<&FileSummary> {
        if crate::probes::summaries() {
            crate::probes::a_summary_was_asked_for(path);
        }
        self.summaries.get(&normalize(path))
    }

    /// **The file that declares module `name` to its importers**, if the project took one in.
    ///
    /// The map `import m;` is resolved through when a query asks what a file's imports brought into view — see
    /// [`ProjectIndex::visible_files_with_modules`]. `None` is the honest answer for a module whose interface unit is
    /// not part of this project (`import std;`, a prebuilt BMI), and a caller that wants to do something about that
    /// reads the file in itself: [`crate::Session::read_the_modules_a_file_imports`].
    pub fn interface_unit_of(&self, name: &str) -> Option<&str> {
        self.module_interfaces.get(name).map(String::as_str)
    }

    /// **Record the files a module's unit was rendered from** — see [`ProjectIndex::unit_closures`].
    ///
    /// Called by the session when a unit's rendering is in hand: it is the only layer that has the rendering, and the
    /// rendering's `walked` list is what an importer's view of the module is made of.
    pub fn remember_the_unit_closure(&self, module: &str, mut files: Vec<String>) {
        files.sort();
        files.dedup();
        if let Ok(mut closures) = self.unit_closures.lock() {
            closures.insert(module.to_string(), files);
        }
        // **And every remembered answer about visibility goes.** The memos were built before this module had a
        // closure — a walk that ran during the index pass, when the unit had not been read yet — and they are exactly
        // the question this changes. Measured: without this line the closure was recorded (223 files, confirmed) and
        // the cached walk still answered 151.
        if let Ok(mut walks) = self.visibility.lock() {
            walks.clear();
        }
    }

    /// The files [`ProjectIndex::remember_the_unit_closure`] recorded, for a probe or a test.
    pub fn unit_closure_of(&self, module: &str) -> Option<Vec<String>> {
        self.unit_closures
            .lock()
            .ok()
            .and_then(|closures| closures.get(module).cloned())
    }

    /// **Every module the index can point at a file for** — `(name, interface unit)`, in name order.
    ///
    /// Sorted rather than left in the map's order, because this is a completion list: two identical requests must
    /// answer with the same order, and a [`std::collections::HashMap`] iteration order is not a promise.
    pub fn interface_units(&self) -> Vec<(String, String)> {
        let mut all: Vec<(String, String)> = self
            .module_interfaces
            .iter()
            .map(|(name, unit)| (name.clone(), unit.clone()))
            .collect();
        all.sort();
        all
    }

    /// Every summary, in insertion order.
    pub fn summaries(&self) -> impl Iterator<Item = &FileSummary> {
        self.order
            .values()
            .filter_map(|path| self.summaries.get(path))
    }

    /// The files that include `path`, directly.
    pub fn includers_of(&self, path: &Path) -> Vec<PathBuf> {
        self.included_by
            .get(&normalize(path))
            .map(|includers| includers.iter().map(PathBuf::from).collect())
            .unwrap_or_default()
    }

    /// **Add what a file's cooked reading found** — see the `cooked` field for what it is and why only declarations
    /// and diagnostics.
    ///
    /// The file must already be in the index ([`ProjectIndex::insert`]): a cooked reading is a *second* answer
    /// about a file the index knows, and its visibility is the file's own — working that out again per query would
    /// be a second include-graph walk for an answer already computed.
    ///
    /// Inserting **replaces** what was there: a file that was cooked again (its text changed, or its environment
    /// did) must not keep the old reading's declarations beside the new one's.
    pub fn insert_cooked(&mut self, path: &Path, reading: CookedFile) {
        self.insert_a_reading(path, None, reading);
    }

    /// **Add the reading a whole program produced for one of its files** — the same insert, filed under the program
    /// that read it.
    ///
    /// `program` is the hash of that program's rendering
    /// ([`crate::RenderedUnit::text`](crate::session::UnitReading)), which is what makes two translation units that
    /// read one header differently keep two readings of it ([`Readings`]). The session passes the one it just read;
    /// [`ProjectIndex::the_reading_for`] is what looks it up per query.
    pub fn insert_cooked_in_a_program(&mut self, path: &Path, program: u64, reading: CookedFile) {
        self.insert_a_reading(path, Some(program), reading);
    }

    fn insert_a_reading(&mut self, path: &Path, program: Option<u64>, reading: CookedFile) {
        let path = normalize(path);

        // **Which id this reading is filed under, and whether it changed** — decided before anything is touched,
        // because the answer is a fact about the map and the effects below are on other fields of `self`.
        let (id, changed) = {
            let readings = self.cooked.get(&path);
            let existing = match program {
                None => Some(Readings::ON_ITS_OWN),
                Some(program) => readings.and_then(|readings| readings.id_for(program)),
            };
            match existing {
                Some(id) => (
                    id,
                    readings
                        .and_then(|readings| readings.reading(id))
                        .is_none_or(|previous| previous.declarations != reading.declarations),
                ),
                // A program that has not read this file yet gets the next id.
                None => (
                    readings.map_or(2, |readings| readings.in_a_program.len() as u32 + 2),
                    true,
                ),
            }
        };

        // **A cooked reading is a second set of facts, and member lists union both — but only a *changed* one can
        // change a list.** A file is cooked again with the same text and the same environment on every pump slice
        // (the edited file, and the closure want_the_closure_cooked asks for), and invalidating on every insert
        // made the cross-request member cache useless: measured on LuaSyntaxTree.cpp, 15 hits against 59
        // computations over three keystrokes — and 37/37 once this comparison was in place.
        if changed {
            self.forget_member_lists(Path::new(&path));
        }
        // **What a cooked reading can change is the declaration answers, and nothing else here.** A walk reads
        // includes and their conditions — facts of the file's *own text*, which the cooked reading does not rewrite
        // — so clearing the walk memo for a cook was over-invalidation of the most expensive kind: the second pass
        // cooks ~1 200 files back to back, and every one of them threw away every closure the queries had built.
        // Measured: it was the reason a keystroke right after a cold start walked five closures again (33.5 ms).
        self.definition_answers
            .lock()
            .expect("the definition memo is not poisoned")
            .clear();

        // The name index holds this file's *other* reading of the same id, if any, and then this one.
        let tracing = std::env::var("CPPLS_TRACE_NAMES").is_ok()
            && (path.ends_with("stl_map.h") || path.ends_with("iostream"));
        if tracing {
            eprintln!(
                "[names] insert_a_reading {}: sequence {:?} id {id} declarations {} diagnostics {:?}",
                path,
                self.sequence.get(&path),
                reading.declarations.len(),
                reading
                    .diagnostics
                    .iter()
                    .take(3)
                    .map(|diagnostic| &diagnostic.message)
                    .collect::<Vec<_>>()
            );
        }
        if let Some(&sequence) = self.sequence.get(&path) {
            let previous = self
                .cooked
                .get(&path)
                .and_then(|readings| readings.reading(id))
                .map(|previous| &previous.declarations);
            if let Some(previous) = previous {
                self.names.remove_declarations(sequence, id, previous);
            }
            self.names
                .add_declarations(sequence, id, &reading.declarations);
        }

        // **Filed, in place of whatever that program (or the file itself) read before.**
        let readings = self.cooked.entry(path.clone()).or_default();
        match program {
            None => readings.on_its_own = Some(reading),
            Some(program) => {
                // A program's id is `2 + its position`, so the position is the id minus two.
                match readings.id_for(program) {
                    Some(id) => readings.in_a_program[id as usize - 2] = (program, reading),
                    None => readings.in_a_program.push((program, reading)),
                }
                readings.last = Some(program);
            }
        }
        debug_assert!(
            readings.reading(id).is_some(),
            "the id an insert decided on is the id it filled"
        );

        // **Bounded**: cooking runs for the closure of every open file — a thousand headers on a project that
        // includes the standard library — and each reading is a declaration list as large as the file`s own
        // summary. The map is *sparse by design* ("a file with no entry here is one nobody cooked", so a miss falls
        // back to the file`s own reading), which is what makes evicting the oldest sound.
        self.cooked_order.push_back(path);
        while self.cooked.len() > MAX_COOKED_FILES {
            let Some(oldest) = self.cooked_order.pop_front() else {
                break;
            };
            self.forget_the_readings_of(&oldest);
        }
    }

    /// **Drop every reading of one path, and the name entries they made** — the one place that has to know a reading
    /// is a list of lists.
    fn forget_the_readings_of(&mut self, path: &str) {
        let Some(readings) = self.cooked.remove(path) else {
            return;
        };
        if let Some(&sequence) = self.sequence.get(path) {
            for (id, reading) in readings.every() {
                self.names
                    .remove_declarations(sequence, id, &reading.declarations);
            }
        }
    }

    /// The declarations the file at `path` was **cooked** into, when it was cooked at all.
    /// **How much the cooked readings are holding** — files and declarations, what a memory report asks.
    pub fn cooked_size(&self) -> (usize, usize) {
        let declarations = self
            .cooked
            .values()
            .flat_map(|readings| readings.every())
            .map(|(_, reading)| reading.declarations.len())
            .sum();
        (self.cooked.len(), declarations)
    }

    /// **What the index is holding** — `(summaries, summary bytes, cooked files, cooked bytes)`.
    ///
    /// The per-entry estimate is [`FileSummary::heap_bytes`], which counts the facts and the strings they own; a
    /// map's spare capacity is not counted, so this is a lower bound on what the index costs. See
    /// [`crate::MemoryReport`] for why an estimate with a stated method beats a total with none.
    pub fn accounting(&self) -> (usize, usize, usize, usize) {
        let summary_bytes = self
            .summaries
            .values()
            .map(FileSummary::heap_bytes)
            .sum::<usize>();
        let mut cooked_bytes = 0usize;
        for readings in self.cooked.values() {
            for (_, reading) in readings.every() {
                cooked_bytes += std::mem::size_of::<CookedFile>()
                    + reading
                        .declarations
                        .iter()
                        .map(DeclFact::heap_bytes)
                        .sum::<usize>()
                    + reading
                        .macros
                        .iter()
                        .map(MacroFact::heap_bytes)
                        .sum::<usize>()
                    + reading.diagnostics.len() * std::mem::size_of::<crate::CookedDiagnostic>();
            }
        }
        (
            self.summaries.len(),
            summary_bytes,
            self.cooked.len(),
            cooked_bytes,
        )
    }

    /// **What the index's own tables cost**, which [`ProjectIndex::accounting`] does not answer.
    ///
    /// `accounting` counts the *facts* — the summaries and the cooked readings — and those are what the index is
    /// *about*. This counts the structure built around them, and it is not small: the inverted index holds one
    /// posting per declaration under two keys (its name and its scope), the include graph holds one set of includers
    /// per file, and four memos hold answers that outlive the request that asked for them.
    ///
    /// The gap this closes was measurable and unexplained: on a 103-source project the session's own report said
    /// **112.4 MB** while the process held **263 MB** after the index, and "the index's own tables are not in it" was
    /// one of the three candidates the audit could not rule out. See [`crate::MemoryReport`].
    ///
    /// Every number here is an estimate with the same stated method as the rest of that report: the entries' keys,
    /// the payloads they point at, and one container header each. Spare capacity and the maps' own tables are not
    /// counted, so this is a lower bound.
    pub fn table_accounting(&self) -> TableCost {
        let names = self.names.accounting();
        // **The include graph**: one set of includers per file, and the file names again as set members. A project's
        // `included_by` is where "which files does this header affect" is answered, so it grows with the edges rather
        // than with the files.
        let mut edges = 0usize;
        let mut edge_bytes = 0usize;
        for (included, includers) in &self.included_by {
            edges += includers.len();
            edge_bytes += included.len() + std::mem::size_of::<BTreeSet<String>>();
            edge_bytes += includers
                .iter()
                .map(|includer| includer.len() + std::mem::size_of::<String>())
                .sum::<usize>();
        }
        edge_bytes += self
            .included_by
            .keys()
            .map(|key| key.len() + std::mem::size_of::<String>())
            .sum::<usize>();
        let modules: usize = self
            .module_interfaces
            .iter()
            .map(|(name, path)| name.len() + path.len() + 2 * std::mem::size_of::<String>())
            .sum();
        // **The three memos that outlive a request.** `member_lists` is the big one — a list is hundreds of
        // `ProjectMember`s, each carrying a `DeclFact` — and it is bounded at `MAX_CACHED_MEMBER_LISTS`.
        let (member_list_entries, member_lists, member_list_bytes) = self
            .member_lists
            .lock()
            .map(|lists| {
                let members: usize = lists.values().map(|held| held.list.members.len()).sum();
                let bytes: usize = lists
                    .values()
                    .map(|held| {
                        let members: usize = held
                            .list
                            .members
                            .iter()
                            .map(|member| {
                                std::mem::size_of::<crate::ProjectMember>()
                                    + DeclFact::heap_bytes(&member.fact)
                            })
                            .sum();
                        let unlisted =
                            held.list.unlisted.len() * std::mem::size_of::<crate::UnlistedBase>();
                        members
                            + unlisted
                            + held.contributors.len() * std::mem::size_of::<PathBuf>()
                            + held
                                .contributors
                                .iter()
                                .map(|path| path.to_string_lossy().len())
                                .sum::<usize>()
                    })
                    .sum();
                (lists.len(), members, bytes)
            })
            .unwrap_or_default();
        let (guard_entries, guard_bytes) = self
            .guard_answers
            .lock()
            .map(|answers| {
                (
                    answers.len(),
                    answers.len()
                        * (std::mem::size_of::<(PathBuf, usize, u32)>()
                            + std::mem::size_of::<crate::Visibility>()),
                )
            })
            .unwrap_or_default();
        let (visibility_entries, visibility_bytes) = self
            .visibility
            .lock()
            .map(|walks| {
                let bytes: usize = walks
                    .values()
                    .map(|walk| {
                        // A walk's answer is one entry per file it reached, plus that file's name twice.
                        let reached = walk.seen.visibility.len();
                        let names: usize = walk
                            .seen
                            .visibility
                            .keys()
                            .map(|path| path.len() * 2 + 48)
                            .sum();
                        names
                            + reached * std::mem::size_of::<IncludeVisibility>()
                            + walk.contributors.len() * std::mem::size_of::<String>()
                    })
                    .sum();
                (walks.len(), bytes)
            })
            .unwrap_or_default();
        let (condition_entries, condition_bytes) = self
            .visibility_answers
            .lock()
            .map(|answers| {
                (
                    answers.len(),
                    answers.len()
                        * (std::mem::size_of::<(String, u32)>()
                            + std::mem::size_of::<crate::Visibility>()
                            + 24),
                )
            })
            .unwrap_or_default();
        // **The paths, twice**: `order` for iteration, `sequence` for identity. Both hold the file's own spelling.
        let path_bytes: usize = self
            .order
            .values()
            .map(|path| path.len() + std::mem::size_of::<String>())
            .sum::<usize>()
            + self
                .sequence
                .keys()
                .map(|path| path.len() + std::mem::size_of::<String>())
                .sum::<usize>();

        TableCost {
            names,
            edges,
            edge_bytes: edge_bytes + modules,
            member_list_entries,
            member_lists,
            member_list_bytes,
            guard_entries,
            guard_bytes,
            visibility_entries,
            visibility_bytes,
            condition_entries,
            condition_bytes,
            path_bytes,
        }
    }

    pub fn cooked_declarations(&self, path: &Path) -> Option<&[DeclFact]> {
        Some(self.cooked_reading(path)?.declarations.as_slice())
    }

    /// **The whole cooked reading** of the file at `path`: what a compiler sees declared there, what the parse of
    /// that text reported, and how much of it this file cannot show — see [`crate::CookedFile`].
    ///
    /// `None` when the file has no cooked reading, which is not the same as "nothing to say": it means *this
    /// reading* has not been made, and a caller that needs an answer falls back to the file's own text
    /// ([`crate::Session::diagnostics`] does exactly that).
    pub fn cooked_reading(&self, path: &Path) -> Option<&CookedFile> {
        self.cooked.get(&normalize(path))?.any()
    }

    /// **Which of a file's readings a lookup uses** — the file's own, or the one the asking program made of it.
    ///
    /// `asking` is the program that read the file the *question* is about
    /// ([`ProjectIndex::the_program_that_read`]), because that is the translation unit the reader is looking at:
    /// `a.cpp` that defines `_GNU_SOURCE` and `b.cpp` that does not must each see the header they compiled. A file
    /// that program has not read falls back to its own reading, and a file nobody read as a program has no cooked
    /// reading at all — the caller then uses the file's summary.
    ///
    /// Answers the reading's id, which is what a [`Posting`] carries, so the narrowing and the facts agree.
    fn the_reading_for(&self, file: u32, asking: Option<u64>) -> u32 {
        let Some(readings) = self.order.get(&file).and_then(|key| self.cooked.get(key)) else {
            return 0;
        };
        if let Some(id) = asking.and_then(|program| readings.id_for(program)) {
            return id;
        }
        if readings.on_its_own.is_some() {
            return Readings::ON_ITS_OWN;
        }
        // **Nothing read on its own, and not this program either**: the last program's reading, which is what a
        // caller with no environment has always got.
        readings
            .last
            .and_then(|program| readings.id_for(program))
            .unwrap_or(0)
    }

    /// **The program that read `path`**, if one did — the environment a question asked *from* that file is in.
    ///
    /// The last program to read it, because a file's own text does not say which of its includers is being compiled:
    /// a `.cpp` has exactly one program and the answer is exact, while a header that two programs read answers with
    /// the one read most recently. That is the honest limit of a lookup that is not told the translation unit, and
    /// it is written down here rather than guessed at the call sites.
    ///
    /// # The module's build comes first, and the own program second
    ///
    /// The order is the difference between `std::format` resolving and not. An importing file's own program — when it
    /// has one at all — is a reading of *its own text*, which cannot contain a single declaration the module exports:
    /// `import std;` is not an `#include`, and `main.cpp` compiles to nothing but an import-declaration. The module's
    /// translation unit is the one that read the headers, so its program is the environment every lookup from this
    /// file has to use. The other order lets the own program win whenever it exists, and every query from the
    /// importing file then falls back to raw readings — where MSVC's `_STD_BEGIN` is an unexpanded macro and nothing
    /// is in scope `std`. Measured on the modules fixture, with the own program winning: `std::format`,
    /// `std::to_string`, `std::vformat` and `std::make_format_args` all resolved to nothing from a file that imports
    /// `std`, while 2 734 names *were* in scope `std` from the headers some other program had read.
    pub fn the_program_that_read(&self, path: &Path) -> Option<u64> {
        if let Some(summary) = self.summaries.get(&normalize(path)) {
            for name in &summary.modules.imports {
                let Some(interface) = self.module_interfaces.get(name.as_ref()) else {
                    continue;
                };
                if let Some(program) = self
                    .cooked
                    .get(&normalize(Path::new(interface.as_str())))
                    .and_then(|readings| readings.last)
                {
                    return Some(program);
                }
            }
        }
        self.cooked
            .get(&normalize(path))
            .and_then(|readings| readings.last)
    }

    /// Forget what a file **was read as**, keeping its summary.
    ///
    /// The invalidation a cooked reading needs and a summary does not: a file's summary is a reading of its own text
    /// (so it changes when the text does — [`ProjectIndex::forget`]), while its cooked reading is a reading of its
    /// text **and of its environment**, so it also changes when something the file includes changes — and nothing
    /// about this file's text says so.
    ///
    /// Dropping rather than marking: between the change and the next cook, a query that found the old declarations
    /// would answer with a declaration whose range points into text that no longer describes it. Not found is the
    /// honest answer there, and the reading comes back one drain later.
    pub fn forget_cooked(&mut self, path: &Path) {
        let path = normalize(path);
        self.forget_member_lists(Path::new(&path));
        self.forget_guard_answers(Path::new(&path));
        // A cooked reading names things the raw one does not (`_STD_BEGIN` is `namespace std {` to it), so an
        // answer given while it was held can stop being true when it goes — the same rule as `forget`, see there.
        if let Ok(mut declared) = self.definition_answers.lock() {
            declared.clear();
        }
        self.forget_the_readings_of(&path);
    }

    /// **The project's symbols matching `query`**, best first — what a `workspace/symbol` search shows.
    ///
    /// # What is searched, and what is not
    ///
    /// Every declaration in every summary the index holds, **plus the names only the cooked reading declares**: the
    /// same two readings every other declaration query unions, asked here **without the visibility walk**, because a
    /// workspace search is about the project and not about what one file can see. A name a macro declared
    /// (`DECLARE_HANDLE(HWND)`'s `HWND__`) is a symbol a compiler knows, so a search finds it; a declaration both
    /// readings found is one answer, deduplicated the same way (`(qualified name, kind)` per file).
    ///
    /// **Locals are left out** ([`DeclFact::local`]): a variable inside a function body is not a project symbol, and
    /// a summary cannot even place it in the function it belongs to.
    ///
    /// # The match, and what the cap means
    ///
    /// Case-insensitive **substring of the name**, so `wid` finds `ns::Widget`. The ranking is exact name, then a
    /// prefix of the name, then anything — and within a rank, alphabetical **by name** and then by qualified name,
    /// because two runs over one project have to answer in the same order or a diff of two answers is noise.
    ///
    /// # Why the order is by name, and what that buys
    ///
    /// The names are kept sorted ([`crate::index::names`]), so an answer in name order is one the search can stop
    /// producing as soon as it has `limit` of them: the cost is the size of the answer, not the size of the project.
    /// (Ordering by the *qualified* name — which puts `a::widget` before `widget` before `b::widget` — would need
    /// every candidate's scope before the first could be placed.) Two declarations of one name are still adjacent,
    /// ordered by where they are.
    ///
    /// `limit` caps the answer, and hitting it is **not** an error: a search box is not a claim about the project
    /// the way a reference list is — the user narrows the query, and every editor's symbol search truncates. That is
    /// the opposite of the decision [`crate::macro_references`] makes, where a partial answer would be a false one.
    pub fn symbols_matching(&self, query: &str, limit: usize) -> Vec<ProjectSymbol> {
        let wanted = query.trim().to_lowercase();
        let bare = wanted.trim_start_matches("::");
        if bare.is_empty() || limit == 0 {
            return Vec::new();
        }

        let mut hits: Vec<Hit<'_>> = Vec::new();

        if !bare.contains("::") {
            // **One word is about the name.** The names are kept sorted by their lowercase form, which is the order
            // the answer is reported in, so the search opens them best rank first and *stops when it has enough*:
            //
            // ```text
            // exact      the one key equal to the query
            // prefix     the keys from the query on, while they begin with it        (a range, not a scan)
            // substring  the remaining keys that contain it                          (a scan that stops early)
            // ```
            if let Some(spellings) = self.names.spellings_of(bare) {
                self.open_group(spellings, Some(0), bare, limit, &mut hits);
            }

            if hits.len() < limit {
                for (key, spellings) in self.names.lowered_from(bare) {
                    if !key.starts_with(bare) {
                        break;
                    }
                    if key == bare {
                        continue;
                    }
                    self.open_group(spellings, Some(1), bare, limit, &mut hits);
                    if hits.len() >= limit {
                        break;
                    }
                }
            }

            if hits.len() < limit {
                for (key, spellings) in self.names.lowered_from("") {
                    if key.starts_with(bare) || !key.contains(bare) {
                        continue;
                    }
                    self.open_group(spellings, Some(2), bare, limit, &mut hits);
                    if hits.len() >= limit {
                        break;
                    }
                }
            }
        } else {
            // **A qualified query is about the last segment's prefix**, so only the names that begin with it are
            // opened — in name order, and the rank (exact last segment, or a prefix of it) is decided per fact by
            // the tail of its qualified name.
            let last_asked = bare.rsplit("::").next().unwrap_or_default();

            for (key, spellings) in self.names.lowered_from(last_asked) {
                if !key.starts_with(last_asked) {
                    break;
                }
                self.open_group(spellings, None, bare, limit, &mut hits);
                if hits.len() >= limit {
                    break;
                }
            }

            // A fact with no name has its scope's last segment for one, so it is not where the name order looks.
            // There are few of them, and the rank decides; whatever the ordered walk left out is later than the
            // `limit` it already has, so adding these to it cannot push out an answer that belongs.
            if !last_asked.is_empty() {
                self.open_group(&[Box::from("")], None, bare, limit, &mut hits);
            }
        }

        sort_hits(&mut hits);
        hits.into_iter()
            .take(limit)
            .map(|hit| ProjectSymbol {
                file: hit.file.to_path_buf(),
                fact: hit.fact.clone(),
            })
            .collect()
    }

    /// Open every spelling of one lowercase name: their hits, in the order [`sort_hits`] defines.
    ///
    /// **A name declared more than [`POPULAR_NAME`] times is cut at `limit` hits, in file order.** `size`, `begin` and
    /// `run` are declared once per class that has one, and ordering *all* of them by qualified name to show the first
    /// hundred would cost a project's worth of work for an answer no reader can tell from any other hundred. The cut
    /// is deterministic (postings are in insertion order), and a name below the threshold is ordered exactly.
    fn open_group<'a>(
        &'a self,
        spellings: &[Box<str>],
        rank: Option<usize>,
        wanted: &str,
        limit: usize,
        into: &mut Vec<Hit<'a>>,
    ) {
        let start = into.len();
        for spelling in spellings {
            let postings = self.names.named(spelling);
            let stop_at = match postings.len() > POPULAR_NAME {
                true => start + limit,
                false => usize::MAX,
            };
            self.hits_in(postings, rank, wanted, stop_at, into);
        }
        into[start..].sort_by(hit_order);
    }

    /// The hits among one name's postings, **one reading per file** — see [`ProjectIndex::visible_declarations_upto`].
    ///
    /// A file can carry two declaration lists: its summary (the file read on its own) and its cooked reading (the file
    /// read in a program). Only one of them is the file's reading, and which one is
    /// [`ProjectIndex::the_reading_is_cooked`] — so a posting that belongs to the other list is not a candidate. The
    /// deduplication this used to do (raw first, cooked shadowed by it) is gone with the union: two readings of one
    /// file are not two halves of one answer, they are two answers about two translation units.
    ///
    /// `rank` is the rank the caller already knows (a whole bucket of names shares one), or `None` when the rank has
    /// to be worked out from the declaration's qualified name.
    fn hits_in<'a>(
        &'a self,
        postings: &[Posting],
        rank: Option<usize>,
        wanted: &str,
        stop_at: usize,
        into: &mut Vec<Hit<'a>>,
    ) {
        for posting in postings.iter() {
            if into.len() >= stop_at {
                break;
            }
            // **One reading per file**, and a posting from another of that file's readings is not a candidate — see
            // [`ProjectIndex::the_reading_for`]. A symbol search has no translation unit to ask from, so every file
            // answers with the reading it has by default.
            if posting.reading != self.the_reading_for(posting.file, None) {
                continue;
            }
            let Some((summary, fact)) = self.resolve(*posting) else {
                continue;
            };

            let qualified = fact.qualified_name();
            let Some(rank) = rank.or_else(|| rank_of(&qualified, &fact.name, wanted)) else {
                continue;
            };

            let qualified = qualified.to_lowercase();
            // What the fact is called for ordering: its name, or — with none — the last segment of its scope.
            let name = match fact.name.is_empty() {
                false => crate::index::names::lowercase(&fact.name),
                true => qualified
                    .rsplit("::")
                    .next()
                    .unwrap_or_default()
                    .to_string(),
            };

            into.push(Hit {
                rank,
                name,
                qualified,
                file: &summary.path,
                posting: *posting,
                fact,
            });
        }
    }

    /// The fact a posting points at, and the summary of the file it is in.
    fn resolve(&self, posting: Posting) -> Option<(&FileSummary, &DeclFact)> {
        let key = self.order.get(&posting.file)?;
        let summary = self.summaries.get(key)?;
        let fact = match posting.reading {
            0 => summary.declarations.get(posting.index())?,
            reading => self
                .cooked
                .get(key)?
                .reading(reading)?
                .declarations
                .get(posting.index())?,
        };
        Some((summary, fact))
    }

    /// **Forget the answers this index gave about names** — for a probe that must ask the same questions twice
    /// (`tests/patch_probe.rs`, which measures what the lookup-time guard patch still removes). Nothing a session does
    /// calls this: the memos are dropped by the changes that make them wrong, and dropping them at another moment would
    /// only cost a re-walk.
    pub fn forget_the_name_answers(&self) {
        if let Ok(mut answers) = self.definition_answers.lock() {
            answers.clear();
        }
        if let Ok(mut guards) = self.guard_answers.lock() {
            guards.clear();
        }
    }
    /// The files that **define** the macro `name`, in insertion order — one lookup, where the question used to be a
    /// scan of every file's macro facts.
    pub fn files_defining_macro(&self, name: &str) -> Vec<PathBuf> {
        self.names
            .definers_of(name)
            .iter()
            .filter_map(|sequence| self.order.get(sequence))
            .filter_map(|key| self.summaries.get(key))
            .map(|summary| summary.path.clone())
            .collect()
    }

    /// The summaries of the files that define **any** of these macros, in insertion order.
    ///
    /// The set form of [`ProjectIndex::files_defining_macro`], for a caller that holds a whole vocabulary — the
    /// words a file mentions — and wants the files that could matter to it, without visiting the ones that cannot.
    pub fn files_defining_any_macro<'a>(
        &self,
        names: impl IntoIterator<Item = &'a str>,
    ) -> Vec<&FileSummary> {
        let mut sequences: BTreeSet<u32> = BTreeSet::new();
        for name in names {
            sequences.extend(self.names.definers_of(name).iter().copied());
        }

        sequences
            .into_iter()
            .filter_map(|sequence| self.order.get(&sequence))
            .filter_map(|key| self.summaries.get(key))
            .collect()
    }

    /// How many distinct declared names the index holds.
    pub fn distinct_names(&self) -> usize {
        self.names.distinct_names()
    }

    /// **The parameters of a class template**, in declaration order, as the names its members' types are written
    /// with — `["_Ty", "_Alloc"]` for `std::vector`.
    ///
    /// The half of substitution that is a *lookup*: the arguments are written at the use (`std::vector<int>`, which
    /// is the `Type` a caller has), and the names are written at the declaration, once. Pairing them is
    /// [`crate::Type::substituted`], and this is where the names come from.
    ///
    /// # Why this reads a fact rather than a tree
    ///
    /// Because the declaration is usually in **another file**. A member query is asked about
    /// `std::vector<int>::reference` from a `.cpp` that includes `<vector>`, and the index holds summaries rather
    /// than the text it read them from — so the parameter names travel with the fact
    /// ([`DeclFact::parameters`]), which is the same reason every other thing a cross-file answer needs is stored.
    ///
    /// # The first declaration that **is a template**, not the first declaration
    ///
    /// A class template is normally declared several times: a forward declaration (`template <class T> class
    /// vector;`), the definition, and possibly a partial specialization or two. The first may have no parameter
    /// list that says anything, and a partial specialization has one that says the *wrong* thing — so the search is
    /// for the first fact that actually records parameters. That is a heuristic, and the honest version of it is:
    /// a partial specialization's list is indistinguishable from a primary template's in a `DeclFact`, because
    /// both are just names. It is the right answer whenever the first such declaration is the primary template,
    /// which is the ordinary case, and it is never a *made-up* answer — a name paired with an argument it does not
    /// belong to is still a name that appears in the class.
    /// **The parameters of the declaration that this use of the class is an instance of.**
    ///
    /// [`ProjectIndex::template_parameters_of`] answers "the first declaration of this class that has a parameter
    /// list", and for a class template with partial specializations that is not the same question: `std::vector` is
    /// declared three ways in MSVC's `<vector>` — the primary with `["_Ty", "_Alloc"]`, and two specializations whose
    /// lists are `["_Alloc"]` — and taking the first one that has *any* parameters substitutes the use's arguments
    /// into the wrong slots. Measured: `std::vector<MarkEvent>::operator[]` answered `_Ty&`, because `_Ty` is the
    /// primary's first parameter and the list in hand was a specialization's.
    ///
    /// The choice is the one [`direct_member`] already makes for members: [`a_pattern_matches`] compares the
    /// declaration's own pattern against the arguments the use wrote, and a pattern argument that is one of the class's
    /// own parameters is a slot. The first declaration that matches wins, and one that has no parameters at all is
    /// only the fallback.
    pub fn template_parameters_for(
        &self,
        class: &str,
        visible_from: &Path,
        arguments: &[String],
    ) -> Vec<String> {
        self.the_template_for(class, visible_from, arguments)
            .map(|(parameters, _)| parameters)
            .unwrap_or_default()
    }

    /// **What the same parameters default to**, in the same order — `["", "allocator<_Ty>"]` for
    /// `template <class _Ty, class _Alloc = allocator<_Ty>>`.
    ///
    /// The other half of [`ProjectIndex::template_parameters_for`], and the one a use that writes *fewer* arguments
    /// needs: see [`crate::substituted_spelling_with_defaults`] for the three-hop chain that needs it and the
    /// measurement behind it.
    pub fn template_parameter_defaults_for(
        &self,
        class: &str,
        visible_from: &Path,
        arguments: &[String],
    ) -> Vec<String> {
        self.the_template_for(class, visible_from, arguments)
            .map(|(_, defaults)| defaults)
            .unwrap_or_default()
    }

    /// **The declaration whose parameter list a use of `class` is read against**, as `(names, defaults)`.
    ///
    /// One selection for both answers: the names and the defaults have to come from the *same* declaration, or a
    /// partial specialization's names would be paired with its primary's defaults.
    fn the_template_for(
        &self,
        class: &str,
        visible_from: &Path,
        arguments: &[String],
    ) -> Option<(Vec<String>, Vec<String>)> {
        let bare = class.strip_prefix("::").unwrap_or(class);
        let last = bare.rsplit("::").next().unwrap_or(bare);

        let mut candidates = self.files_declaring(class, visible_from);
        if candidates.is_empty() {
            candidates = self.files_declaring(last, visible_from);
        }
        // **A declaration whose pattern has a different number of arguments is not an instance of this use**, which is
        // the one place this cannot lean on `a_pattern_matches`: that function answers `true` for a length mismatch on
        // purpose (a use that wrote fewer arguments — defaulted template parameters — keeps its candidates), and here a
        // mismatch is exactly what tells `vector<bool, _Alloc>` from `vector<_Ty, _Alloc>`.
        let of_the_same_arity = |found: &&VisibleDeclaration<'_>| {
            let pattern = found.fact.pattern.as_deref().unwrap_or_default();
            let slots = arguments_in_a_spelling(pattern).unwrap_or_default();
            slots.len() == arguments.len() && lists_usable_parameter_names(&found.fact.parameters)
        };
        candidates
            .iter()
            .filter(of_the_same_arity)
            .find(|found| {
                a_pattern_matches(
                    found.fact.pattern.as_deref(),
                    &found.fact.parameters,
                    Some(arguments),
                )
            })
            // The declaration with the **longest** parameter list is the primary template: a specialization names
            // some of its arguments concretely and therefore has fewer parameters to describe them with.
            .or_else(|| {
                candidates
                    .iter()
                    .filter(|found| lists_usable_parameter_names(&found.fact.parameters))
                    .max_by_key(|found| found.fact.parameters.len())
            })
            .map(|found| {
                (
                    found.fact.parameters.clone(),
                    found.fact.parameter_defaults.clone(),
                )
            })
    }

    pub fn template_parameters_of(&self, class: &str, visible_from: &Path) -> Vec<String> {
        let bare = class.strip_prefix("::").unwrap_or(class);
        let last = bare.rsplit("::").next().unwrap_or(bare);

        let mut candidates = self.files_declaring(class, visible_from);
        if candidates.is_empty() {
            candidates = self.files_declaring(last, visible_from);
        }

        candidates
            .iter()
            .map(|found| &found.fact.parameters)
            .find(|parameters| !parameters.is_empty())
            .cloned()
            .unwrap_or_default()
    }
    /// The files in which `name` is visible, in insertion order.
    ///
    /// `name` is matched against a declaration's **qualified** name first — `ns::Widget` — and against its bare
    /// name only as a fallback, because a qualified spelling is a much stronger claim than a name that happens to
    /// appear in some scope. A caller that gets one answer from the qualified match should prefer it to any
    /// number from the bare one.
    pub fn files_declaring(&self, name: &str, visible_from: &Path) -> Vec<VisibleDeclaration<'_>> {
        // The name is looked up under the two spellings a fact can answer to: the whole thing (a bare name) and its
        // last segment (`ns::Widget` is `Widget` declared in `ns`). `matches` then decides between them.
        let bare = name.strip_prefix("::").unwrap_or(name);
        let last = bare.rsplit("::").next().unwrap_or(bare);
        self.visible_declarations(
            visible_from,
            |fact| matches(fact, name),
            Narrow::Named(&[bare, last]),
        )
    }

    /// Every declaration written **directly in** the scope `scope`, visible from `visible_from`.
    ///
    /// The whole-scope counterpart of [`ProjectIndex::definition`]: that asks about one name, this asks about
    /// every name one scope holds, which is what a member list is made of. `scope` is a **qualified** spelling —
    /// `Widget`, `ns::Widget` — because that is what a [`DeclFact`] records; see [`DeclFact::scope`].
    ///
    /// Note what "directly in" excludes, because it is the whole reason this is not a name search: a local
    /// variable inside a member function is a fact whose scope is `None` — a function body contributes no segment
    /// to a qualified name — so `C`'s members are `C`'s bindings and not everything written between its braces.
    pub fn declarations_in(&self, scope: &str, visible_from: &Path) -> Vec<VisibleDeclaration<'_>> {
        self.visible_declarations(
            visible_from,
            |fact| fact.scope.as_deref() == Some(scope),
            Narrow::Scoped(scope),
        )
    }

    /// [`ProjectIndex::declarations_in`] with a **second** condition, applied while the facts are still borrowed.
    ///
    /// The second predicate exists for one caller and one reason: a completion has a prefix, and on a file that
    /// includes `<string>` the scope it is listing holds over a thousand declarations. A caller that collected them
    /// and then kept the ones beginning with `w` would do a `DeclFact` clone, a provenance lookup and a `Vec` push
    /// per name to throw 99% of them away — on every keystroke. The two conditions are asked together because
    /// there is no useful notion of order between them: both are filters, and a fact that fails either is not
    /// collected.
    ///
    /// A method rather than a parameter on [`ProjectIndex::declarations_in`] because that one's callers do not have
    /// a second condition, and a query with an optional filter it never uses is a query whose filter is untested.
    pub fn declarations_in_where(
        &self,
        scope: &str,
        visible_from: &Path,
        accepts: impl Fn(&DeclFact) -> bool,
    ) -> Vec<VisibleDeclaration<'_>> {
        self.visible_declarations_upto(
            visible_from,
            &|fact: &DeclFact| fact.scope.as_deref() == Some(scope) && accepts(fact),
            MAX_COLLECTED_IN_A_SCOPE,
            Narrow::Scoped(scope),
        )
    }

    /// The visibility walk over the declaration list, with the door open for a caller outside this module and
    /// capped at `MAX_COLLECTED_NAMES`.
    ///
    /// The cap and not the whole set, because the one caller is a completion and the names this drops could not
    /// have reached the top of its list — see `MAX_COLLECTED_NAMES`, which states the argument. A caller that wants
    /// **every** visible declaration asks [`ProjectIndex::files_declaring`] or [`ProjectIndex::declarations_in`],
    /// which have no cap because their answers are about one name rather than a list.
    pub fn visible_declarations_where(
        &self,
        visible_from: &Path,
        accepts: impl Fn(&DeclFact) -> bool,
    ) -> Vec<VisibleDeclaration<'_>> {
        self.visible_declarations_upto(visible_from, &accepts, MAX_COLLECTED_NAMES, Narrow::Nothing)
    }

    /// **Every file `from` reaches through its `#include`s, transitively** — the cheap half of visibility.
    ///
    /// A graph question only: the summaries record where each include resolved, so this is a breadth-first walk over
    /// hash lookups, with **no guard evaluation**. That is exactly what a rule suggesting "include this header" needs
    /// and nothing more: a name declared in a file this set already holds is treated as visible (so no finding is ever
    /// made about a header the file reaches), and the answer is conservative in the direction that matters — it can
    /// miss a name behind an inactive guard, never invent one.
    ///
    /// The cost is the closure's size in `HashSet` probes, which is what lets it be asked on every keystroke: on a
    /// project whose closure is 600 files the whole walk is under a millisecond, against **1.2 s** for the full
    /// visibility walk that evaluates every condition on the way.
    pub fn include_closure(&self, from: &Path) -> std::collections::HashSet<String> {
        let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
        let mut pending: Vec<String> = vec![normalize(from)];
        while let Some(path) = pending.pop() {
            if !seen.insert(path.clone()) {
                continue;
            }
            let Some(summary) = self.summaries.get(&path) else {
                continue;
            };
            for include in &summary.includes {
                if let Some(target) = &include.resolved {
                    let next = normalize(target);
                    if !seen.contains(&next) {
                        pending.push(next);
                    }
                }
            }
        }
        seen
    }

    /// **Every name visible from `from`, as one set** — what a rule that asks about many names needs.
    ///
    /// [`ProjectIndex::definition`] answers one name at a time and pays the visibility walk per call (memoised, but
    /// still a walk plus a `Vec` of candidates). A check that asks about *every type a file spells* wants the walk
    /// once and hash lookups after that: measured on a real project, per-name asks were **0.7 s each** on a file whose
    /// closure is large, and the whole set is one walk.
    pub fn visible_names(&self, from: &Path) -> std::collections::HashSet<String> {
        self.visible_declarations_upto(from, &|_| true, usize::MAX, Narrow::Nothing)
            .into_iter()
            .map(|declaration| declaration.fact.name.to_string())
            .collect()
    }

    /// Every fact in the index whose **bare** name is `name`, with the file it was written in.
    ///
    /// A diagnostic, for asking "is the declaration I am looking for in the index at all, and under which scope" —
    /// the question that separates "the walk did not find it" from "it was never filed where the walk looks".
    pub fn name_postings(&self, name: &str) -> usize {
        self.names.named(name).len()
    }

    /// See [`ProjectIndex::name_postings`].
    pub fn scope_postings(&self, scope: &str) -> usize {
        self.names.scoped(scope).len()
    }

    /// See [`ProjectIndex::name_postings`].
    pub fn all_summaries(&self) -> Vec<(std::path::PathBuf, &FileSummary)> {
        self.summaries
            .values()
            .map(|summary| (summary.path.clone(), summary))
            .collect()
    }

    /// See [`ProjectIndex::name_postings`].
    pub fn summaries_named_like(&self, needle: &str) -> Vec<std::path::PathBuf> {
        self.summaries
            .values()
            .map(|summary| summary.path.clone())
            .filter(|path| {
                path.to_string_lossy()
                    .to_ascii_lowercase()
                    .contains(&needle.to_ascii_lowercase())
            })
            .collect()
    }

    /// See [`ProjectIndex::name_postings`].
    pub fn every_fact_named(&self, name: &str) -> Vec<(std::path::PathBuf, &DeclFact)> {
        let mut found = Vec::new();
        for posting in self.names.named(name) {
            let Some(key) = self.order.get(&posting.file) else {
                continue;
            };
            let Some(summary) = self.summaries.get(key) else {
                continue;
            };
            if let Some(fact) = summary.declarations.get(posting.index())
                && fact.name == name
            {
                found.push((summary.path.clone(), fact));
                continue;
            }
            if let Some((_, fact)) = self.resolve(*posting)
                && fact.name == name
            {
                found.push((summary.path.clone(), fact));
            }
        }
        found
    }

    /// The declarations some predicate accepts, in the files `visible_from` can see.
    ///
    /// The one place the visibility walk is applied to the declaration list, so that a new query over facts
    /// cannot forget it and quietly answer with a declaration in a file the querying file does not include —
    /// which is a jump to something it cannot compile against. `includers_of` and [`ProjectIndex::visible_files`]
    /// are the graph; this is the graph applied to a question.
    ///
    /// # Two readings, one candidate list
    ///
    /// Each visible file contributes its **raw** declarations and, when it has been cooked, its **cooked** ones
    /// (see the `cooked` field). They are unioned rather than chosen between, and the reason is that the query
    /// already carries the discriminator: a caller asking for `std::to_string` cannot be answered by the raw
    /// reading's file-scope `to_string`, and one asking for `to_string` gets both — which is honestly *ambiguous*,
    /// because which one it means depends on the scope the caller is in. What the union must not do is count the
    /// same declaration twice: a declaration both readings found (`(qualified name, kind)`) is one candidate, or
    /// every ordinary declaration would come back as two and every lookup would answer `Ambiguous`.
    ///
    /// # Why the graph is walked once, and not once per file
    ///
    /// This used to ask `visibility_of` for **each summary** in the index, and each of those answers walked the
    /// include graph from scratch: a query over a standard-library closure therefore did three hundred
    /// breadth-first searches to answer one question. Measured, on a closure of 308 files: **573 ms** for a
    /// completion at `std::`, which is a query a client asks on every keystroke. One walk and a map lookup is the
    /// same answer in under a millisecond.
    fn visible_declarations<'a>(
        &'a self,
        visible_from: &Path,
        accepts: impl Fn(&DeclFact) -> bool,
        narrow: Narrow<'_>,
    ) -> Vec<VisibleDeclaration<'a>> {
        self.visible_declarations_upto(visible_from, &accepts, usize::MAX, narrow)
    }

    /// [`ProjectIndex::visible_declarations`] with a **cap** on how many are collected.
    ///
    /// The cap is what makes a completion over a standard-library closure cheap, and it is safe for the same
    /// reason the collection is: a caller that wants at most `n` names and ranks them by **how near the cursor
    /// their declaration is** cannot be affected by the `n + 1`-th, because every name this walk produces is from
    /// a file reached through an include — the tier that ranks last. See [`MAX_COLLECTED_NAMES`].
    ///
    /// `usize::MAX` is the honest spelling of "no cap" rather than an `Option`, because the two callers that pass
    /// it are asking a question about a *name* rather than a list — a jump, a rename — and their answers are
    /// allowed to be as many as there are.
    fn visible_declarations_upto<'a>(
        &'a self,
        visible_from: &Path,
        accepts: &impl Fn(&DeclFact) -> bool,
        limit: usize,
        narrow: Narrow<'_>,
    ) -> Vec<VisibleDeclaration<'a>> {
        // **Only the files the cursor's file can see are looked at**, and in insertion order. The walk answers with
        // a handful of hundreds even when the project holds a hundred thousand files, so the cost of the question is
        // the size of the closure and not the size of the project.
        //
        // …and **which of them are in view only through a module import**: those are the files
        // where a declaration counts only if it is exported, and the distinction is per file rather
        // than per fact because a file reached by `#include` has no such restriction at all. **The
        // translation unit this question is asked from** — the reading every file's answer is
        // chosen by.
        let asking = self.the_program_that_read(visible_from);
        let walk_started = std::time::Instant::now();
        let asks_before = CONDITION_ASKS.load(std::sync::atomic::Ordering::Relaxed);
        let nanos_before = CONDITION_NANOS.load(std::sync::atomic::Ordering::Relaxed);
        let (visible_files, through_an_import) = self.visible_files_with_modules(visible_from);
        let files = self.visible_in_order_of(visible_files);
        if crate::probes::visibility() {
            eprintln!(
                "[visibility] {} file(s) after the order step, from {}",
                files.len(),
                visible_from.display()
            );
        }
        if crate::probes::timing() && walk_started.elapsed().as_micros() >= 500 {
            let asks = CONDITION_ASKS.load(std::sync::atomic::Ordering::Relaxed) - asks_before;
            let nanos = CONDITION_NANOS.load(std::sync::atomic::Ordering::Relaxed) - nanos_before;
            eprintln!(
                "[visibility] {:>5.1} ms, {} file(s), from {} — {asks} condition(s)/{} ms",
                walk_started.elapsed().as_secs_f64() * 1000.0,
                files.len(),
                visible_from
                    .file_name()
                    .map(|name| name.to_string_lossy().to_string())
                    .unwrap_or_else(|| visible_from.display().to_string()),
                nanos / 1_000_000,
            );
        }
        // Everything below this line is reading facts out of files that are already known to be visible: the
        // filtering, the `DeclFact` clones, and the cooked-vs-raw deduplication. Timed apart from the walk because
        // the two have nothing in common — the walk is a question about the graph and this is a question about the
        // declarations — and because a completion that is slow with a *fast* walk is a different defect.

        let mut found = Vec::new();

        // **A name or a scope narrows further**: the postings say which files hold a candidate at all, so a file
        // that has none is never opened. Without a narrowing every visible file's declarations are the candidates.
        let postings: Option<std::borrow::Cow<'_, [Posting]>> = match narrow {
            Narrow::Nothing => None,
            Narrow::Scoped(scope) => Some(std::borrow::Cow::Borrowed(self.names.scoped(scope))),
            Narrow::Named(names) => {
                let mut keys: Vec<&str> = names.to_vec();
                keys.dedup();
                match keys.as_slice() {
                    [one] => Some(std::borrow::Cow::Borrowed(self.names.named(one))),
                    _ => {
                        let mut merged: Vec<Posting> = keys
                            .iter()
                            .flat_map(|key| self.names.named(key).iter().copied())
                            .collect();
                        merged.sort_unstable();
                        merged.dedup();
                        Some(std::borrow::Cow::Owned(merged))
                    }
                }
            }
        };

        if std::env::var("CPPLS_TRACE_NAMES").is_ok()
            && let Narrow::Named(names) = narrow
            && names.iter().any(|name| *name == "cout" || *name == "map")
        {
            let postings = match &postings {
                Some(postings) => postings
                    .iter()
                    .map(|posting| {
                        format!(
                            "file {} id {} index {}",
                            posting.file,
                            posting.reading,
                            posting.index()
                        )
                    })
                    .collect::<Vec<_>>(),
                None => vec!["no narrow".to_string()],
            };
            eprintln!(
                "[names] visible_declarations {:?}: {} posting(s) — {postings:?}",
                names,
                postings.len()
            );
        }

        // One `(file, its candidates)` group at a time, in file order. Without postings a file's candidates are all of
        // its facts, which is what the empty group range stands for.
        let mut next = 0;
        let mut visible = files.iter();

        loop {
            // **The cap is checked before a file is read, not while it is.** A file is one declaration list, and
            // the only thing worth stopping on is a whole one: taking half of a file's facts would leave the
            // cooked-vs-raw deduplication below comparing against a `raw` list that is itself half a file, and
            // `(name, kind)` identity is per file. So a query takes files until it has enough, and "enough" is a
            // number no answer can reach past — see [`MAX_COLLECTED_NAMES`].
            if found.len() >= limit {
                break;
            }

            let (file, visibility, group): (u32, IncludeVisibility, Option<&[Posting]>) =
                match &postings {
                    None => {
                        let Some(&(file, visibility)) = visible.next() else {
                            break;
                        };
                        (file, visibility, None)
                    }
                    Some(postings) => {
                        let Some(first) = postings.get(next) else {
                            break;
                        };
                        let file = first.file;
                        let end = next + postings[next..].partition_point(|held| held.file == file);
                        let group = &postings[next..end];
                        next = end;

                        let Ok(at) = files.binary_search_by_key(&file, |visible| visible.0) else {
                            continue;
                        };
                        (file, files[at].1, Some(group))
                    }
                };

            let Some(key) = self.order.get(&file) else {
                continue;
            };
            let Some(summary) = self.summaries.get(key) else {
                continue;
            };

            // **A file in view only through an `import` contributes only what it exports.** The rule is per *file*
            // rather than per fact because it is about how the file became visible: `import m;` brings what the
            // module interface exported and nothing else, while an `#include` brings the whole file — and a file
            // that is both is include-visible, so this is false for it (see `visible_files_with_modules`).
            //
            // `DeclFact::exported` is the reading; on a file that declares no module it is `false` throughout, and
            // the walk never asks a file like that this question because it cannot be in `through_an_import` — only
            // a module *interface unit* is.
            let only_what_is_exported = through_an_import.contains(key);
            let contributes =
                |fact: &DeclFact| accepts(fact) && (!only_what_is_exported || fact.exported);

            // **One reading per file, and which one is the asking translation unit's answer.** The file read *on its
            // own* and the file read **inside a program** are not two views of one thing: measured on a real project,
            // **1 095 declarations over 177 files** are in one and not the other (`tests/unit_read_probe.rs`), because
            // `_CRT_…` and `_GLIBCXX_…` decide differently in the two. Offering both at once answers for two
            // translation units with one question, and offering the *wrong* one answers `b.cpp` with what `a.cpp`
            // compiled.
            //
            // So the reading is chosen per file — [`ProjectIndex::the_reading_for`], which prefers the program that
            // read **the file this question is about** (the reader's own translation unit) and falls back to the
            // file's own reading. Its id is what a posting carries, so the narrowing below stays exact.
            let reading = self.the_reading_for(file, asking);
            let cooked = self
                .cooked
                .get(key)
                .and_then(|readings| readings.reading(reading));

            // **A reading that does not hold the name cannot answer for it, and the summary is the file's own text.**
            // The choice above is the right default — it is the asking program's reading — but a program's reading is a
            // rendering, and a name can be missing from it for a reason that is about *that cook* rather than about the
            // file: `print`'s whole body sits under `#ifdef __cpp_lib_print`, and a module's cook that lost the
            // feature-test macro contributed a reading of `print` with **no** `println` while the summary had all
            // four — and that reading shadowed the summary for every query, which is what a hover on `std::println`
            // answered `null` for. So the chosen reading is used when it has something to say about this question, and
            // the summary when it does not.
            // **A reading that does not hold the name cannot answer for it, and the summary is the file's own text.**
            // The choice above is the right default — it is the asking program's reading — but a program's reading is a
            // rendering, and a name can be missing from it for a reason that is about *that cook* rather than about the
            // file: `print`'s whole body sits under `#ifdef __cpp_lib_print`, and a module's cook contributed a
            // reading of `print` with **no** `println` while the summary had all four — that reading shadowed the
            // summary for every query, which is what a hover on `std::println` answered `null` for. So the chosen
            // reading is used when it has something to say about this question, and the summary when it does not.
            // **The asking program's own reading answers alone.** A name it does not hold is a name that program did
            // not compile — `#if 0 struct Dead` is in the file's environment-free summary and in no rendering — so the
            // summary may not speak for it. The fallback below stays for the other case, which is a real one: a cook
            // that went wrong (a module's cook losing a feature-test macro) must not shadow a declaration the file does
            // hold unconditionally elsewhere.
            let the_askers_own = asking.is_some_and(|program| {
                self.order
                    .get(&file)
                    .and_then(|key| self.cooked.get(key))
                    .and_then(|readings| readings.id_for(program))
                    .is_some()
            });
            let (facts, reading): (&[DeclFact], u32) = match cooked {
                Some(cooked) if cooked.declarations.iter().any(&accepts) => {
                    (cooked.declarations.as_slice(), reading)
                }
                // **The summary's postings carry reading `0`** — measured, not guessed: `[names]` printed
                // `file 172 id 0 index 2` for `iostream`'s `cout`, while `Readings::ON_ITS_OWN` is `1`, so a fallback
                // that claimed `1` matched no posting and answered nothing. `0` is what `insert_at` files a summary's
                // declarations under. The policy itself is unchanged: the asking program's own reading answers alone,
                // because a name it does not hold is a name that program did not compile.
                Some(_) if !the_askers_own && summary.declarations.iter().any(&accepts) => {
                    (summary.declarations.as_slice(), 0)
                }
                Some(cooked) => (cooked.declarations.as_slice(), reading),
                None => (summary.declarations.as_slice(), 0),
            };

            let candidates: Box<dyn Iterator<Item = &DeclFact> + '_> = match group {
                None => Box::new(facts.iter()),
                Some(group) => Box::new(
                    group
                        .iter()
                        .filter(|posting| posting.reading == reading)
                        .filter_map(|posting| facts.get(posting.index())),
                ),
            };

            for fact in candidates.filter(|fact| contributes(fact)) {
                found.push(VisibleDeclaration {
                    file: summary.path.clone(),
                    fact,
                    visibility,
                });
            }
        }

        found
    }
    /// every declaration query reports in.
    ///
    /// [`ProjectIndex::visible_in_order_of`] is the same thing for a caller that has **already walked**: the
    /// declaration queries need both halves of the walk's answer (the files, and which of them are in view only
    /// through an `import`) from one walk, and calling this and `visible_files_with_modules` would walk the graph
    /// twice per question.
    fn visible_in_order_of(
        &self,
        visible: Vec<(String, IncludeVisibility)>,
    ) -> Vec<(u32, IncludeVisibility)> {
        // **The lookup below is a suspect, and it is left as it was until the effect of fixing it is understood.**
        //
        // The walk's keys are normalized (`e:/p/app.cpp`) and `sequence` is keyed by the path the summary was filed
        // under, so a file whose two spellings differ is dropped **silently** — the walk says it is visible and this
        // step removes it. That is a bug, and *fixing it alone makes the answers worse*, which is the finding:
        //
        // * a normalized fallback **here**, and
        // * normalizing the key when it is **written** (both spellings inserted, both removed),
        //
        // were each measured on the same cold store and each moved the scoreboard the same way — 4637 (77.1%) →
        // 4609 (76.7%), **+28 `NotDeclaredHere` and not one `Ambiguous`**. And the scoreboard now splits those
        // refusals: of the 77 that had a receiver type, **47 had no visible declaration of the class and 30 had a
        // member list built from no visible declaration** — not one was "the list does not hold the member". So the
        // loss is not a different declaration being chosen; it is the same file becoming visible **twice**, under
        // both spellings, which doubles its summary in the name index and changes what the member walk reads.
        //
        // The next step is therefore to make the **identity** unique — one file, one summary, one sequence number, one
        // set of postings — and only then to stop dropping the spelling. Either half alone is a regression.
        //
        // **That was the hypothesis, and it has been counted: it is false.** The index holds 1581
        // summaries for 1581 distinct identities and **not one file twice**, so the loss is not a
        // duplicate summary. What is left is the only other thing a wider view changes: which
        // declarations exist *at all* for a name — and the scoreboard says every refusal with a
        // receiver type had **no visible declaration of the class** (47) or a list built from none
        // (30), so the 28 lost questions are ones where one visible declaration used to be enough
        // and two now are not. Neither experiment is in the tree; the next round starts from this
        // number, not from a theory.
        let mut files: Vec<(u32, IncludeVisibility)> = visible
            .into_iter()
            .filter_map(|(key, visibility)| Some((*self.sequence.get(&key)?, visibility)))
            .collect();

        files.sort_unstable_by_key(|(sequence, _)| *sequence);
        files.dedup_by_key(|(sequence, _)| *sequence);
        files
    }

    /// Every file `from` can see, and how — one walk of the include graph.
    ///
    /// The whole-graph answer to what used to be a per-file question: "can this file see that one" was asked once
    /// per summary, and each answer walked the include graph. This returns the answer for every file at once, so
    /// one walk serves a whole query — measured on a closure of 308 files, that turned a 573 ms completion into a
    /// 3 ms one, and every cross-file query over declarations goes through it.
    ///
    /// **Every file that can see `path`** — its transitive includers, nearest first.
    ///
    /// The reverse of [`ProjectIndex::visible_files`], and the question a *change* to a file asks: whose reading was
    /// built while this file said what it used to say? A cooked reading is a reading of its environment as well as of
    /// its text, so a file that defines a macro is read differently by everything that includes it, at any depth.
    ///
    /// Breadth-first over the reverse edges, deduplicated and bounded by the same depth the forward walk uses: an
    /// include graph is not a tree — every header guard makes it a diamond — so "included by, transitively, without
    /// asking about a file twice" is the whole job. The order is the walk's, which is deterministic because the
    /// reverse edges are a `BTreeSet`.
    ///
    /// The **file itself is not in the answer**: a caller dropping that file's own reading has its own reason to, and
    /// one list that means two things is how a caller ends up dropping something twice or not at all.
    pub fn dependents_of(&self, path: &Path) -> Vec<PathBuf> {
        let start = normalize(path);

        let mut seen: HashSet<String> = HashSet::from([start.clone()]);
        let mut pending: VecDeque<(String, usize)> = VecDeque::from([(start, 0)]);
        let mut dependents = Vec::new();

        while let Some((current, depth)) = pending.pop_front() {
            if depth >= MAX_VISIBILITY_DEPTH {
                continue;
            }

            let Some(includers) = self.included_by.get(&current) else {
                continue;
            };

            for includer in includers {
                if !seen.insert(includer.clone()) {
                    continue;
                }
                dependents.push(PathBuf::from(includer));
                pending.push_back((includer.clone(), depth + 1));
            }
        }

        dependents
    }

    /// The visibility recorded is the **best** one found: a file reached both unconditionally and through a
    /// guarded `#include` is unconditional, because the unconditional path is the one that is always there. That
    /// is why a file may be relaxed rather than only visited — the first path found is not necessarily the best,
    /// and a graph with a diamond in it (which every header guard produces) has exactly that shape.
    pub fn visible_files(&self, from: &Path) -> Vec<(String, IncludeVisibility)> {
        self.visible_files_with_modules(from).0
    }

    /// [`ProjectIndex::visible_files`], and **which of those files are in view only because of an `import`**.
    ///
    /// The second half is what the exported bit is applied against: a declaration written in a module interface
    /// unit is visible to an importer **only if it is exported** ([`DeclFact::exported`]), while a file reached
    /// through `#include` has no such restriction — so a query that did not know *how* a file became visible could
    /// only choose between offering names that do not compile and hiding names that do.
    ///
    /// A file that is both included and imported is **not** in the second list: the include makes all of it visible,
    /// and the narrower rule would hide what the wider one grants.
    pub fn visible_files_with_modules(
        &self,
        from: &Path,
    ) -> (Vec<(String, IncludeVisibility)>, HashSet<String>) {
        let from = normalize(from);

        // **The walk's answer, remembered under the rule the per-condition memo uses.** A completion asks this
        // question on every keystroke and the answer cannot change until the index does, which is exactly what
        // `visibility` is cleared by. Measured on the latency fixture in release: **4–5 ms** with the memo and
        // **84–90 ms** without it, against a 50 ms steady-state budget.
        if let Some(known) = self.visibility.lock().ok().and_then(|walks| {
            walks
                .get(&from)
                .map(|cached| std::sync::Arc::clone(&cached.seen))
        }) {
            let mut order: Vec<(String, IncludeVisibility)> =
                Vec::with_capacity(known.visibility.len());
            order.push((from.clone(), IncludeVisibility::Unconditional));
            order.extend(
                known
                    .visibility
                    .iter()
                    .filter(|(path, _)| **path != from)
                    .map(|(path, visibility)| (path.clone(), *visibility)),
            );
            return (order, known.through_an_import.clone());
        }

        // **One traversal, and the state it carries is what answers the conditions.** The version this replaced
        // asked `environment::visibility_at` per guarded edge, and that call builds the file's whole closure state
        // — one walk of the include graph *per condition in the closure*. Measured on the MSVC standard library at
        // the latency fixture's cursor: 114 conditions, 1428 ms of a 1431 ms query, 12.5 ms each.
        //
        // `macro_candidates` is the same traversal that already answers "what is in force at this point", and it
        // evaluates a guarded edge as it crosses it, against the state the route has built. So the question this
        // function asks is not a second implementation of the walk — it is the same walk, told to report the files
        // it enters. That is the rule the module keeps being bitten by: one question, one implementation.
        let mut seen = Seen::new(&from);
        let macros_started = std::time::Instant::now();
        let mut state = self.macros.clone();
        let macros_cloned = macros_started.elapsed();
        let certain = self.certainly_in_the_translation_unit(Path::new(&from));
        if crate::probes::timing() && macros_started.elapsed().as_micros() >= 300 {
            eprintln!(
                "[visibility] the state: macro table cloned in {macros_cloned:?} ({} entry(ies)), \
                 the translation unit's certain set in {:?}",
                self.macros.len(),
                macros_started.elapsed() - macros_cloned
            );
        }

        self.macro_candidates(
            Path::new(&from),
            &mut Vec::new(),
            false,
            &mut HashSet::new(),
            &certain,
            &mut Collecting::Visibility(&mut seen),
            &mut state,
            None,
        );

        // **And then the module frontier**, which is a different edge with a different rule: an `import` is not
        // textual, so the walk above could not descend through one without putting another module's macros into a
        // macro environment. What the *visibility* question still owes is everything behind those edges — the
        // imported interface's own includes, its partitions, the partitions' includes — so this is a second walk,
        // over the same summaries, that carries no macro state because nothing on this side of an `import` is a
        // macro fact.
        //
        // It shares `visited`'s *purpose* and not its set: the walk above has already entered the include closure,
        // and re-entering a file it reached would evaluate conditions with a state that has drifted. `module_seen`
        // is what keeps this walk to the files the first one could not reach.
        //
        // **The unit's own closure comes first, for the asking file and for every file the frontier reaches.** A
        // module is not a header: what an importer sees is the unit's whole translation unit, and walking the
        // interface's `#include` edges answers a weaker question — each guard evaluated against a state that is not the
        // unit's, so a header the unit included behind `_HAS_CXX20` is dropped. Measured on the reader's project:
        // `report.cppm` importing `std` saw **151 files and no `std::string`**, while `main.cpp` saw 173 only because
        // its own `#include "extra/widget.h"` pulled the same tree in textually. The rendering has already decided
        // every one of those guards, once, for the module — see [`ProjectIndex::unit_closures`].
        let mut module_seen: HashSet<String> = HashSet::new();
        self.add_the_closures_behind_the_imports(Path::new(&from), &mut seen);
        while let Some(reached) = seen.module_work.pop() {
            if !module_seen.insert(reached.clone()) {
                continue;
            }
            self.add_the_closures_behind_the_imports(Path::new(&reached), &mut seen);

            let mut state = self.macros.clone();
            self.walk_the_module_edges(
                Path::new(&reached),
                &mut seen,
                &mut state,
                &mut module_seen,
            );
        }

        // The order the per-edge version produced: the root first, then the walk's crossing order. Rebuilt from the
        // map rather than recorded during the walk because a file can be crossed more than once and only the first
        // *crossing* is its place in the answer — the better visibility may arrive later, from another route.
        let mut order: Vec<(String, IncludeVisibility)> = Vec::with_capacity(seen.visibility.len());
        order.push((from.clone(), IncludeVisibility::Unconditional));
        order.extend(
            seen.visibility
                .iter()
                .filter(|(path, _)| **path != from)
                .map(|(path, visibility)| (path.clone(), *visibility)),
        );

        // Remembered before it is handed out, and `through_an_import` is cloned out of the shared copy: the caller
        // owns its set, and the memo has to be immutable to be shared.
        //
        // **The contributor list is the closure, normalized once here** so that [`ProjectIndex::insert_at`] can
        // drop precisely the walks a re-read invalidates without normalizing a closure per insert.
        let through_an_import = seen.through_an_import.clone();
        let mut contributors: Vec<String> = Vec::with_capacity(seen.visibility.len() + 1);
        contributors.push(from.clone());
        contributors.extend(
            seen.visibility
                .keys()
                .filter(|path| **path != from)
                .map(|path| normalize(Path::new(path))),
        );
        contributors.sort_unstable();
        contributors.dedup();
        if let Ok(mut walks) = self.visibility.lock() {
            walks.insert(
                from,
                CachedWalk {
                    seen: std::sync::Arc::new(seen),
                    contributors: std::sync::Arc::new(contributors),
                },
            );
        }

        (order, through_an_import)
    }

    /// **Everything behind one module edge**: the target's includes, its own module edges, and theirs.
    ///
    /// The second half of [`ProjectIndex::visible_files_with_modules`], and a separate walk because the first one
    /// carries a macro environment and a macro does not cross an `import`. What crosses is *visibility*: a header
    /// a module's interface includes is visible to whoever imports the module — measured on the fixture where
    /// `std.ixx` is `export module std;` plus two `#include`s and a file that writes `import std;` must be offered
    /// `std::string`.
    ///
    /// The guards on the includes it crosses are evaluated against the compilation's own environment and the
    /// target's facts, which is the same state the first walk starts from — a module unit's macros are its own, and
    /// nothing outside it reaches them.
    fn walk_the_module_edges(
        &self,
        path: &Path,
        seen: &mut Seen,
        state: &mut Marked,
        module_seen: &mut HashSet<String>,
    ) {
        let path = normalize(path);
        let Some(summary) = self.summaries.get(&path) else {
            return;
        };

        // **The unit's own definitions, folded in before its includes are judged.** A module interface unit is a
        // *translation unit*: a header it includes can define what a later `#if` in the same unit asks about, and a
        // walk that only recorded *where* each include leads — as this one did — judged those questions with an
        // environment that never learned anything.
        //
        // Measured on `import std;` with MinGW GCC 15: `bits/std.cc` includes `bits/stdc++.h`, whose standard-header
        // block is guarded by `#if _GLIBCXX_HOSTED`; `_GLIBCXX_HOSTED` is `#define`d in `bits/c++config.h`, which the
        // headers *above* that block include. The guard therefore read as undefined, the verdict was `Inactive`, and
        // the block — `#include <vector>` among a hundred others — was dropped: `include/c++/vector` was not in the
        // visible set, `std::vector` had only the `using std::vector;` re-export as its fact, and the member list was
        // empty.
        //
        // Only the **unconditional** facts are folded: a definition inside a condition this walk has not decided is a
        // value it cannot stand behind, and leaving it out is the honest reading.
        for fact in &summary.macros {
            if fact.guard == FactGuard::Unconditional {
                apply_fact(state, fact, false, FactReach::Active);
            }
        }

        let mut verdicts: HashMap<(u32, usize), Option<bool>> = HashMap::new();

        for unit in &summary.modules.header_units {
            let next = normalize(unit);
            seen.visibility
                .entry(next.clone())
                .or_insert(IncludeVisibility::Unconditional);
            if module_seen.insert(next.clone()) {
                seen.module_work.push(next);
            }
        }
        for unit in &summary.modules.partitions {
            let next = normalize(unit);
            seen.visibility
                .entry(next.clone())
                .or_insert(IncludeVisibility::Unconditional);
            if module_seen.insert(next.clone()) {
                self.walk_the_module_edges(Path::new(&next), seen, state, module_seen);
            }
        }
        for imported in &summary.modules.imports {
            let Some(interface) = self.module_interfaces.get(imported.as_ref()) else {
                continue;
            };
            seen.visibility
                .entry(interface.clone())
                .or_insert(IncludeVisibility::Unconditional);
            seen.through_an_import.insert(interface.clone());
            if module_seen.insert(interface.clone()) {
                self.walk_the_module_edges(Path::new(interface), seen, state, module_seen);
            }
        }

        // The includes, each edge's own guard decided against the state the module unit reached it with.
        for include in &summary.includes {
            let visibility = self.include_visibility(
                summary,
                &mut verdicts,
                state,
                &mut Collecting::Visibility(&mut *seen),
                include.guard,
                include.range.start_offset,
            );
            if visibility == Visibility::Inactive {
                continue;
            }

            let Some(target) = &include.resolved else {
                continue;
            };
            let next = normalize(target);
            let step = match visibility {
                Visibility::Active => IncludeVisibility::Unconditional,
                Visibility::Unknown => IncludeVisibility::Conditional,
                Visibility::Inactive => continue,
            };

            match seen.visibility.get(&next) {
                Some(known) if *known <= step => {}
                _ => {
                    seen.visibility.insert(next.clone(), step);
                }
            }
            // An `#include` makes the whole file visible, however it was reached before.
            seen.through_an_import.remove(&next);

            if module_seen.insert(next.clone()) {
                self.walk_the_module_edges(Path::new(&next), seen, state, module_seen);
            }
        }
    }

    /// **Every file behind the `import`s a file writes** — the unit's own closure, when it is known.
    ///
    /// The closure is the unit's **rendering** (`RenderedUnit::walked`, recorded by
    /// [`ProjectIndex::remember_the_unit_closure`]): every file that contributed to what an importer compiles. A file
    /// in it is visible unconditionally and is **not** subject to the exported-bit rule — the module exported it, that
    /// is what being in the unit's translation unit means — so it is also removed from `through_an_import`.
    fn add_the_closures_behind_the_imports(&self, of: &Path, seen: &mut Seen) {
        let Some(summary) = self.summaries.get(&normalize(of)) else {
            return;
        };
        if summary.modules.imports.is_empty() {
            return;
        }
        let Ok(closures) = self.unit_closures.lock() else {
            return;
        };
        for imported in &summary.modules.imports {
            let Some(files) = closures.get(imported.as_ref()) else {
                continue;
            };
            for file in files {
                seen.visibility
                    .entry(file.clone())
                    .or_insert(IncludeVisibility::Unconditional);
                seen.through_an_import.remove(file);
            }
        }
    }

    /// [`ProjectIndex::visible_files`] the way this query computed it **before** the walk carried its state.
    ///
    /// Kept as the transition's other side, and for one reason: the visibility set is what a completion list is
    /// built from, so a walk that produces a *different* set is a different answer rather than a slower one. The
    /// cost is the thing being replaced — it asks `environment::visibility_at` per guarded edge, and that call
    /// rebuilds the file's closure state from scratch. Measured on the latency fixture's cursor before the change:
    /// **114 conditions, 1428 ms of a 1431 ms query, 12.5 ms each.**
    ///
    /// `examples/completion_latency.rs` prints both sets and their differences, which is how the replacement was
    /// checked rather than argued for.
    pub fn visible_files_by_asking_each_condition(
        &self,
        from: &Path,
    ) -> Vec<(String, IncludeVisibility)> {
        let from = normalize(from);

        // The file itself is visible to itself, and unconditionally: a question asked in a file is about what
        // that file says before anything it includes.
        let mut best: HashMap<String, IncludeVisibility> =
            HashMap::from([(from.clone(), IncludeVisibility::Unconditional)]);
        let mut order: Vec<String> = vec![from.clone()];
        let mut pending: Vec<(String, IncludeVisibility, usize)> =
            vec![(from, IncludeVisibility::Unconditional, 0)];
        // The files in view **only** through an `import`, which is where the exported bit applies.
        let mut through_an_import: HashSet<String> = HashSet::new();

        while let Some((current, so_far, depth)) = pending.pop() {
            if depth > MAX_VISIBILITY_DEPTH {
                continue;
            }

            let Some(summary) = self.summaries.get(&current) else {
                continue;
            };

            // **Header units are followed exactly like `#include`s** — `import <vector>;` names a header, and a header
            // unit exports what the header declares, so nothing about the declarations it brings in is restricted. The
            // path was resolved when the file was read (the walk can search nothing), and one that could not be resolved
            // is simply absent.
            for unit in &summary.modules.header_units {
                let next = normalize(unit);

                if let std::collections::hash_map::Entry::Vacant(slot) = best.entry(next.clone()) {
                    slot.insert(IncludeVisibility::Unconditional);
                    order.push(next.clone());
                    pending.push((next, IncludeVisibility::Unconditional, depth + 1));
                }
            }

            // **…and so is a partition of this file's own module.** `export import :area;` makes the partition's
            // declarations part of *this* module's interface, so a file that imports the module has to see them — and
            // the file that declares them is reached by exactly the same kind of resolved path. Not following it is a
            // false negative, which is the direction this project refuses everywhere else: measured on the partition
            // fixture (`target/build_partitions.bat`), `definition("perimeter")` resolved to the interface unit while
            // `rectangle` and `square`, declared in the partition it re-exports, answered "nothing declares it".
            //
            // `Unconditional`, and for a reason that is *not* the same as the import note below: a partition import is
            // not conditional in practice — the grammar does not allow `import :part;` inside a conditional region of a
            // module unit, because the module's interface has to be known in full before anything is compiled against
            // it.
            for unit in &summary.modules.partitions {
                let next = normalize(unit);

                if let std::collections::hash_map::Entry::Vacant(slot) = best.entry(next.clone()) {
                    slot.insert(IncludeVisibility::Unconditional);
                    order.push(next.clone());
                    pending.push((next, IncludeVisibility::Unconditional, depth + 1));
                }
            }

            // **A module import is the other visibility edge**, and it is not an `#include` with another spelling:
            // an import is not textual (no macro travels along it) and it names a *module* rather than a file, so
            // the file behind it is found through the module the project declares. That is what makes
            // `import mathlib;` bring `mathlib::add` into view — measured on the module fixture, where the answer
            // was `None` from a file that imports `mathlib` and whose sibling `mathlib.ixx` exports it.
            //
            // `Unconditional`, and that is a simplification with a direction: an `import` inside an `#if` is
            // recorded here like any other, so a module reached only through a condition the compilation does not
            // satisfy is offered. The `#include` path above is careful about exactly this (see its own note on
            // guards); making imports as careful needs the same per-condition machinery and is registered rather
            // than guessed at — see `plan-units.md` §35.
            for imported in &summary.modules.imports {
                let Some(interface) = self.module_interfaces.get(imported.as_ref()) else {
                    // No file in this project declares it: `import std;` and prebuilt modules land here, and the
                    // honest reading is "unknown", never "nothing" — a name that cannot be seen is not a name that
                    // does not exist. Nothing is added, and nothing is claimed.
                    continue;
                };

                if best.contains_key(interface) {
                    continue;
                }

                best.insert(interface.clone(), IncludeVisibility::Unconditional);
                order.push(interface.clone());
                through_an_import.insert(interface.clone());
                pending.push((
                    interface.clone(),
                    IncludeVisibility::Unconditional,
                    depth + 1,
                ));
            }

            for include in &summary.includes {
                let Some(resolved) = &include.resolved else {
                    continue;
                };
                let next = normalize(resolved);

                // **A guarded `#include` stays `Conditional` here, and the reason is now cost**.
                //
                // The conditions *are* answerable — `crate::index::environment::visibility_at` answers
                // `#if _STL_COMPILER_PREPROCESSOR` correctly once its two upstream bugs are fixed (`own_guard` not
                // recognising `#pragma once` + `#ifndef`, and a fact in an `#else` judged by the `#if`'s verdict) —
                // and wiring it in here is what finally resolved MSVC's `std::string`: the probe went 2/9 → 7/9.
                //
                // What it also did is make the pinned probe run for **minutes**: `visible_files` walks the whole
                // include graph, and asking the evaluator per guarded include builds a closure state per include
                // (`macros_at`). The libstdc++ closure has hundreds of them. So the rule is right and the
                // *implementation* is not: it needs the incremental state `ProjectIndex::macro_environment` builds
                // (one walk per file, conditions answered as they are reached) before it can be used here — and
                // until then this line stays, because a query that takes minutes is not an answer.
                let step = match include.guard {
                    FactGuard::Unconditional => so_far,
                    // **The condition is asked, and the answer is remembered**. Asking costs the file's
                    // whole closure state; the same question is asked by every query and every walk over hundreds of
                    // edges, and the answer cannot change until a summary is inserted — so it is memoised on the
                    // index (`visibility_answers`), which `insert_at` clears.
                    //
                    // Only `Active` is *used*: a condition that holds makes the include unconditional, and one
                    // nobody can decide leaves the answer exactly where it was (`Conditional`). What `Inactive`
                    // does — dropping the edge — is decided below, where the visibility is turned into a step.
                    FactGuard::Region(region) => {
                        let key = (current.clone(), region);
                        let answer = match self
                            .visibility_answers
                            .lock()
                            .ok()
                            .and_then(|answers| answers.get(&key).copied())
                        {
                            Some(answer) => answer,
                            None => {
                                // **What a condition costs, counted** — the probe that says whether a warm walk is
                                // warm because the memo works or because there was nothing to ask.
                                let started = std::time::Instant::now();
                                let answer = crate::index::environment::visibility_at(
                                    self,
                                    Path::new(&current),
                                    include.guard,
                                    include.range.start_offset,
                                );
                                if crate::probes::timing() {
                                    CONDITION_NANOS.fetch_add(
                                        started.elapsed().as_nanos() as u64,
                                        std::sync::atomic::Ordering::Relaxed,
                                    );
                                    CONDITION_ASKS
                                        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                                }
                                if let Ok(mut answers) = self.visibility_answers.lock() {
                                    answers.insert(key, answer);
                                }
                                answer
                            }
                        };

                        match answer {
                            crate::Visibility::Active => so_far,
                            // **A condition that was decided, and not taken**: the file is not part of this
                            // translation unit at all, so nothing in it is visible — the edge is dropped rather
                            // than downgraded, and so is everything only reachable through it.
                            //
                            // This rule was written twice and reverted twice, and the comment that stood here said
                            // why: the *evaluator* was wrong on two corpora (an unrecognised own guard, a fact in an
                            // `#else`), and a rule that can only add facts is the safe direction while that is true.
                            // Both bugs are fixed, so it was re-measured, and the number it is worth is large:
                            // measured on one real file, `#include <arm_neon.h>` and `#include <zmmintrin.h>` —
                            // ARM and AVX-512 intrinsics, gated on `_M_ARM64`/`_M_AVX512`, both decidable and both
                            // **false** for this compilation — were in the visibility list as `Conditional`, and
                            // their names were **8 of every 10 completion items**: 14351 items, 4.5 MB of JSON, for
                            // a cursor in a 78-line file (`zmmintrin.h` 5256, `arm64_neon.h` 2852, `arm_neon.h` 2117).
                            crate::Visibility::Inactive => continue,
                            // A condition nobody can decide: the file may or may not be there, which is exactly what
                            // `Conditional` means to every consumer.
                            crate::Visibility::Unknown => IncludeVisibility::Conditional,
                        }
                    }
                };
                match best.get(&next) {
                    // Already known, and no worse: nothing new to explore through it.
                    Some(known) if *known <= step => continue,
                    Some(_) => {}
                    None => order.push(next.clone()),
                }

                // **An `#include` makes the whole file visible**, however the file was reached before: a file that
                // is both included and imported is not subject to the narrower rule, because the wider one already
                // grants what it would hide.
                through_an_import.remove(&next);

                best.insert(next.clone(), step);
                pending.push((next, step, depth + 1));
            }
        }

        order
            .into_iter()
            .filter_map(|path| {
                best.get(&path)
                    .map(|visibility| (path.clone(), *visibility))
            })
            .collect()
    }

    /// Which declaration a name written in `visible_from` refers to, across the project.
    ///
    /// The cross-file half of [`crate::sema::resolve::definition_at`], and the answer to the
    /// the single-file query returns when a name is somewhere else.
    ///
    /// # The four answers
    ///
    /// * `Yes` — exactly one visible declaration, unconditionally reachable.
    /// * `Unknown(NotDeclaredHere)` — nothing in the project declares it, or nothing that is visible. **Not**
    ///   `No`: the project's index is a subset of what a compiler would see (the standard library, a header
    ///   outside every include path), so "not here" and "nowhere" are still different claims.
    /// * `Unknown(Ambiguous)` — several declarations are visible and nothing chooses between them. Overloads, a
    ///   name declared in two headers the file includes, a bare name declared in two namespaces.
    /// * `Unknown(ConditionalCompilation)` — the only match is reached through an `#include` inside an `#if`, so
    ///   whether it is in scope depends on macros this layer does not have.
    ///
    /// # It is the *one* projection of a plural answer
    ///
    /// [`ProjectIndex::definitions`] is the query; this is the same answer restricted to the names that have
    /// exactly one declaration. A consumer that can show a list — `textDocument/definition` is one — should ask
    /// that instead, because `Ambiguous` is a dead end there: measured on one real file, **46** of its identifiers
    /// answered `Ambiguous`, and every one of them had a perfectly good list behind it (an overload set, a
    /// redeclaration, a namespace).
    pub fn definition(&self, name: &str, visible_from: &Path) -> Known<ProjectDefinition> {
        match self.definitions(name, visible_from) {
            Known::Yes(mut found) if found.found.len() == 1 => Known::Yes(found.found.remove(0)),
            // **A `using`-declaration is a synonym, not a second entity.** C++ says so in as many words: a
            // using-declaration "does not introduce a new declaration; it introduces a synonym". The index stores a
            // fact for it anyway (kind `Other`, the coarsest thing this vocabulary has), so a name that one file
            // *declares* and another *uses* arrives here as two declarations and this query refused with
            // `Ambiguous` — measured on `using std::IsTriviallyCopyConstructible;` over an `enum class` in a header:
            // every hover on the enumerator's qualifier answered `Ambiguous`, and the enumerator itself could then
            // not be looked up at all.
            //
            // Dropping the synonyms is not a guess about which declaration is meant: after the drop either exactly
            // one entity remains (the answer) or the name really does have several, and `Ambiguous` stays honest.
            Known::Yes(mut found) => {
                found
                    .found
                    .retain(|declaration| declaration.fact.kind != DeclKind::Other);
                // **Which *entity* the spelling names.** A class template asked without arguments is the fact with no
                // pattern; `vector<bool>` is a partial specialization with one. Mixing the two is what made a hover on
                // `std::vector` answer `Ambiguous` with four candidates listed: two forward declarations, the primary
                // definition, and `vector<bool, _Alloc>`.
                let group: Vec<usize> = if !name.contains('<') {
                    let plain: Vec<usize> = found
                        .found
                        .iter()
                        .enumerate()
                        .filter(|(_, declaration)| declaration.fact.pattern.is_none())
                        .map(|(at, _)| at)
                        .collect();
                    if plain.is_empty() {
                        (0..found.found.len()).collect()
                    } else {
                        plain
                    }
                } else {
                    (0..found.found.len()).collect()
                };

                // **And a definition beats a forward declaration inside that group** — `struct _Ty;` beside
                // `struct _Ty { … };` are two facts of one entity, and a reader sent to the first sees an empty class
                // where the index holds the whole one. Only one definition in the group chooses; two are two entities.
                let definitions: Vec<usize> = group
                    .iter()
                    .copied()
                    .filter(|at| found.found[*at].fact.definition)
                    .collect();
                if definitions.len() == 1 {
                    return Known::Yes(found.found.remove(definitions[0]));
                }
                if group.len() == 1 {
                    return Known::Yes(found.found.remove(group[0]));
                }
                match found.found.len() {
                    1 => Known::Yes(found.found.remove(0)),
                    _ => Known::Unknown(UnknownReason::Ambiguous(Box::from(name))),
                }
            }
            Known::Unknown(reason) => Known::Unknown(reason),
            Known::No => Known::No,
        }
    }

    /// **A type name resolved where it was written** — the lookup C++ does and a plain name lookup does not.
    ///
    /// A declaration's type is written in the scope the declaration is in, and C++ looks for an **unqualified**
    /// name there first — in the class, then in what encloses it — before it looks anywhere else. Every other
    /// query in this type is handed a name and a file, and `std::_Allocation_guard::_Alloc_ptr_t` is not what
    /// the header wrote: it wrote `_Alloc_ptr_t`, a **member alias** of the class the declaration sits in.
    ///
    /// Measured on the closure of one file that includes `<format>`, `<vector>` and `<string>`: of 2129 type
    /// spellings the reader could name, 185 named something no lookup answered, and the largest group by far was
    /// this shape — `_Alloc_ptr_t`, `_Alty_traits::pointer`, `_Alloc_size_t`. Not one was a name that is not
    /// there; every one is a member of the class whose member wrote it.
    ///
    /// # Why this is a separate query rather than a change to [`ProjectIndex::definition`]
    ///
    /// Because it *qualifies* the name, and `definition`'s callers ask about names a user wrote at a cursor —
    /// where the enclosing class is already part of the spelling, or is a member access the caller resolved. A
    /// caller that has a written type and the scope it was written in is the caller that wants this, and there
    /// is one way to get it wrong: qualifying a name that is already absolute.
    ///
    /// # Why this walks outward rather than trying one scope
    ///
    /// An unqualified name is looked for **in the innermost scope first and then in each scope around it**, and
    /// the standard library is why one step is not enough: `_Alloc_ptr_t` is used inside `std::_Allocation_guard`
    /// and declared as a free alias template at **namespace scope in `std`** (`xmemory`, "`template <class
    /// _Alloc> using _Alloc_ptr_t = …`"). Asking only the use's own scope answers
    /// `std::_Allocation_guard::_Alloc_ptr_t` — a spelling nothing declares — for a name that is written two
    /// lines up in the same namespace.
    ///
    /// # What it does not do
    ///
    /// It does not substitute template arguments and it does not instantiate: `_Alloc_ptr_t` is
    /// `typename allocator_traits<_Alloc>::pointer`, and **finding the alias is not the same as finishing its
    /// type** — the answer here is the alias's own declaration, which is what a caller needs to say where the
    /// name comes from. Substitution is [`crate::Type::substituted`], driven by a caller that has the arguments,
    /// and nothing drives it yet. Nor does it follow a **base class**: a name inherited from a base is written
    /// unqualified too, and finding it means walking the bases of every class on the chain.
    pub fn definition_where_written(
        &self,
        written: &str,
        in_scope: Option<&str>,
        visible_from: &Path,
    ) -> Known<ProjectDefinition> {
        // The name as written, first. A qualified name, and a name declared at file scope, both answer here —
        // and a name that answers must not be re-asked under a different spelling, because the two answers are
        // different declarations whenever a class has a member of the same name.
        let direct = self.definition(written, visible_from);
        if !matches!(direct, Known::Unknown(UnknownReason::NotDeclaredHere(_))) {
            return direct;
        }

        // `::name` is absolute and takes no scope — that is what the leading `::` is for.
        let Some(scope) = in_scope.filter(|_| !written.starts_with("::")) else {
            return direct;
        };

        // **Outward, one segment at a time.** `std::a::b::name`, then `std::a::name`, then `std::name`, and the
        // bare name has already been tried — which is the order C++ looks in, and the reason a name declared in
        // an enclosing namespace is found from a class nested two deep inside it.
        let segments: Vec<&str> = scope.split("::").collect();
        for take in (1..=segments.len()).rev() {
            let enclosing = segments[..take].join("::");
            if enclosing.is_empty() {
                continue;
            }

            let through_the_scope =
                self.definition(&format!("{enclosing}::{written}"), visible_from);
            if !matches!(
                through_the_scope,
                Known::Unknown(UnknownReason::NotDeclaredHere(_))
            ) {
                return through_the_scope;
            }
        }

        // **The original reason, not the last attempt's.** Returning `NotDeclaredHere` for a spelling the caller
        // never wrote would have a consumer explaining a name the user cannot find in their file.
        direct
    }

    /// **Every declaration a name refers to** — the plural answer, for a consumer that can show a list.
    ///
    /// # Why a list, and why it is not a preference
    ///
    /// One name covering several entities is ordinary C++, and the language says what they are: `find` in
    /// `std::basic_string` is one **overload set** (seventeen declarations in MSVC's library, every one of them an
    /// answer to "where is this declared"), `std::char_traits` is a class template and its specializations, and
    /// `cin` is written twice in `<iostream>` — one variable, declared twice, which the language calls the same
    /// entity. `Ambiguous` is the honest answer to *which one*, and it is a dead end for a client; the protocol
    /// has a shape for the honest answer, so this is it.
    ///
    /// # The one case that is collapsed, and why that is not taste
    ///
    /// When **every** candidate is a namespace, there is exactly one entity: a namespace is reopened by every file
    /// that writes `namespace std { … }`, and the language says all of those are the same namespace. Measured on
    /// the file that motivated this query: `std` has **58** declarations in the index, so a peek list of
    /// fifty-eight entries answers a question nobody asked — while `size`'s seventeen and `cin`'s two are exactly
    /// what a reader wants to see. The collapse is therefore about the *kind* of entity, not about the count.
    ///
    /// # The order, which is part of the answer
    ///
    /// Unconditional first, then by file and offset. Imposed rather than inherited: `summaries()` is a map, so
    /// leaving the order alone would make the list depend on hashing, and a client's peek list would reorder
    /// itself between two identical requests.
    pub fn definitions(&self, name: &str, visible_from: &Path) -> Known<ProjectDefinitions> {
        // **A measurement switch, not a behaviour**: what a diagnostics pull costs *without* the
        // index lookups — the sibling of `CPPLS_NO_INFERENCE`, and it exists to tell "the engine"
        // from "the index" before either is optimised.
        if crate::probes::no_index_lookup() {
            return Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(name)));
        }
        // **One answer per spelling per pull** — see [`ProjectIndex::definition_answers`]. Measured on
        // `LuaSource.cpp`: 95 of one pull's 99 slow lookups were the same name (`std`), at 0.6–1.3 ms each.
        let key = (name.to_string(), normalize(visible_from));
        if let Some(known) = self
            .definition_answers
            .lock()
            .ok()
            .and_then(|memo| memo.get(&key).cloned())
        {
            return known;
        }
        let started = std::time::Instant::now();
        let answer = self.definitions_inner(name, visible_from);
        if crate::probes::timing() && started.elapsed().as_micros() >= 200 {
            eprintln!(
                "[lookup] {:>5.1} ms  {name}  ({} answer(s))",
                started.elapsed().as_secs_f64() * 1000.0,
                match &answer {
                    Known::Yes(found) => found.found.len(),
                    _ => 0,
                }
            );
        }
        if let Ok(mut memo) = self.definition_answers.lock() {
            if memo.len() >= MAX_DEFINITION_ANSWERS {
                memo.clear();
            }
            memo.insert(key, answer.clone());
        }
        answer
    }

    fn definitions_inner(&self, name: &str, visible_from: &Path) -> Known<ProjectDefinitions> {
        let (mut certain, conditional) = match self.certain_declarations(name, visible_from) {
            Ok(candidates) => candidates,
            Err(reason) => return Known::Unknown(reason),
        };

        // **A namespace is asked about more than any other name, and it is the cheapest question in the index.**
        // `std` is written in the spelling of every qualified name in a file: measured on `LuaSource.cpp`, **95 of
        // the 99 slow declaration lookups in one diagnostics pull were `std`**, at 1.3 ms each — because the
        // deduplication below is quadratic in the candidates, and MSVC declares `namespace std` in a hundred
        // headers. The namespace rule collapses all of them to one answer *whatever* their identity, so apply it
        // first and skip the quadratic pass: same answer, 1.3 ms → 0.03 ms.
        let all_namespaces = certain
            .iter()
            .all(|found| found.fact.kind == DeclKind::Namespace);
        if all_namespaces {
            certain.truncate(1);
        }

        // **One entity, or two answers?** The measurement this rests on — 19 ambiguous identifiers in one real
        // file, their candidates paired up — produced **97 pairs that stand in the same file and agree on every
        // field a consumer can read**, against **0 across files**: the duplicates are *inside* one header (MSVC's
        // `<iostream>` writes `cin` plain and again behind `_EXPORT_STD`), while two files declaring one name are
        // two places a reader may want to go. See [`the_same_declaration_in_one_file`] for the conditions.
        let mut distinct: Vec<ProjectDeclaration> = Vec::new();
        for found in certain {
            if let Some(at) = distinct
                .iter()
                .position(|kept| the_same_declaration_in_one_file(kept, &found))
            {
                // **A definition beats a forward declaration written earlier in the same file** — the shape MSVC's
                // standard library uses: `struct _Ty;` near the top of a header and `struct _Ty { … };` further down.
                // Keeping the first sent a reader, and every query built on `definition`, to the empty one.
                if found.fact.definition && !distinct[at].fact.definition {
                    distinct[at] = found;
                }
                continue;
            }
            distinct.push(found);
        }
        let mut certain = distinct;

        // **A `using`-declaration is a synonym, not a second entity.** C++ says so in as many words: it "does not
        // introduce a new declaration". The index stores a fact for it anyway (kind `Other`, the coarsest thing this
        // vocabulary has), so a name that one file declares and another uses arrives as two declarations — measured
        // on `using std::IsTriviallyCopyConstructible;` over an `enum class` in a header, where every hover on the
        // enum's name answered `Ambiguous` and the enumerator's qualified lookup died behind it.
        //
        // The synonyms go **only when a real declaration remains**: a name that is nothing but a using-declaration
        // still points a reader at that line, which is better than "not declared".
        if certain
            .iter()
            .any(|found| found.fact.kind != DeclKind::Other)
        {
            certain.retain(|found| found.fact.kind != DeclKind::Other);
        }

        Known::Yes(ProjectDefinitions {
            found: certain
                .into_iter()
                .map(|found| ProjectDefinition {
                    file: found.file,
                    fact: found.fact,
                })
                .collect(),
            conditional,
        })
    }

    /// **Every declaration a spelling can denote where it is written** — [`ProjectIndex::definitions`] narrowed by
    /// the one rule the index cannot put in its key: **a bare name does not reach into a class**.
    ///
    /// # The defect this answers
    ///
    /// Measured on a two-file project — a header declaring `struct Name { void printf(int); };` and
    /// `void Name::printf(int i) { … }`, and a `.cpp` that includes it and calls `printf("…")` — go-to-definition on
    /// `printf` in the `.cpp` answered **three** declarations: the member's declaration, its out-of-class definition,
    /// and `stdio.h`'s `printf`. The first two are a function the `.cpp` cannot name: `printf` written unqualified at
    /// file scope denotes the one at file scope, and a member is denoted by a member access or by a qualified name.
    ///
    /// The index keys a fact by its **name** ([`DeclFact::name`]), so every `printf` in every included header is a
    /// candidate; C++ keys it by the **scope it is written in**. This query is the second half of the key.
    ///
    /// # The rule, and the two directions it must not go
    ///
    /// * A fact whose [`DeclFact::scope`] is a **class** is dropped from a **bare** spelling's answer. A qualified
    ///   spelling (`Name::printf`) keeps it — that is how a member is named from outside — and so does a caller that
    ///   already knows it is looking at a member ([`ProjectIndex::definitions`], which this one is a filter over).
    /// * A scope **nothing in the index declares as a class** keeps its members: `false` there means "I cannot
    ///   tell", and a lookup that cannot tell must not become a lookup that says there is nothing.
    ///
    /// `Unknown(NotDeclaredHere)` when the scope rule leaves nothing, which is the same answer as a name that is not
    /// declared here — and it is the honest one, because no declaration the caller can write reaches the name.
    pub fn definitions_in_scope(
        &self,
        name: &str,
        visible_from: &Path,
    ) -> Known<ProjectDefinitions> {
        // The reason is passed through as it stands: this method has nothing to add to `NotDeclaredHere`,
        // `Ambiguous` or `ConditionalCompilation`, and re-asking the query to keep the value would run a visibility
        // walk twice for an answer that is already in hand.
        let mut found = match self.definitions(name, visible_from) {
            Known::Yes(found) => found,
            other => return other,
        };

        // A qualified spelling names the scope it writes, so the key is already as narrow as the language's.
        if name.contains("::") {
            return Known::Yes(found);
        }

        // **One lookup per distinct scope**, not per fact: an overload set is several facts in one scope, and a
        // visibility walk per candidate would be paid once per overload rather than once per class.
        let mut decided: Vec<(String, bool)> = Vec::new();
        let mut kept = Vec::with_capacity(found.found.len());

        for declaration in found.found {
            let Some(scope) = declaration.fact.scope.clone() else {
                // File scope: exactly where a bare name looks.
                kept.push(declaration);
                continue;
            };

            let a_class = match decided.iter().find(|(known, _)| *known == scope) {
                Some((_, answer)) => *answer,
                None => {
                    let answer = self.scope_names_a_class(&scope, visible_from);
                    decided.push((scope.clone(), answer));
                    answer
                }
            };

            if !a_class {
                kept.push(declaration);
            }
        }

        if kept.is_empty() {
            return Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(name)));
        }

        found.found = kept;
        Known::Yes(found)
    }

    /// **Does the scope a qualified spelling names hold declarations as a class?** — the question
    /// [`ProjectIndex::definitions_in_scope`] asks before it drops a member.
    ///
    /// The scope's own declaration is what answers it, and the comparison is on the **qualified** name rather than
    /// on [`matches`]'s looser rule: `files_declaring("Name")` also answers a *nested* class called `Name` (its
    /// fact's `name` is `Name` and its scope is `Outer`), and taking that for a class called `Name` would hide the
    /// members of a namespace that happens to have a same-named class somewhere inside it.
    fn scope_names_a_class(&self, scope: &str, visible_from: &Path) -> bool {
        self.files_declaring(scope, visible_from)
            .iter()
            .any(|declaration| {
                declaration.fact.kind == DeclKind::Type
                    && declaration.fact.qualified_name() == scope
            })
    }

    /// **What kind of thing a name is, when every declaration the index holds for it agrees** — and
    /// [`UnknownReason::Ambiguous`] when they do not.
    ///
    /// The question a semantic highlighter asks about a name it cannot resolve to one declaration: it has to draw a
    /// colour, and a colour is a claim about the *kind*. An overload set is one kind (`pick(int)` and `pick(double)`
    /// are both functions, and a reader who sees both drawn as functions has been told the truth about both), while
    /// `size` as a member of one class and a free function somewhere else is genuinely two answers, and a client
    /// shown either one of them has been told something false about the other.
    ///
    /// This is not [`ProjectIndex::definition`] with a looser rule — it is the same candidate set, read for the two
    /// fields a highlighter needs instead of cloned whole into an answer a jump would use. See
    /// [`crate::semantic::classified_names`], which is its only caller.
    pub fn kind_of(&self, name: &str, visible_from: &Path) -> Known<IndexedKind> {
        let (certain, _) = match self.certain_declarations(name, visible_from) {
            Ok(candidates) => candidates,
            Err(reason) => return Known::Unknown(reason),
        };

        // **A member's declaration cannot be what a bare spelling means.** `class TextRange { TextRange(); … }` files
        // three facts whose bare name is `TextRange` — the class, and its two constructors — so this question came
        // back `Ambiguous`, and the *token* `TextRange` then got no colour at all.
        //
        // Measured on EmmyLuaCodeStyle's `LuaParser/include/LuaParser/Ast/LuaSyntaxNode.h`: `LuaSyntaxTree` was
        // classified `Type` and `TextRange` was not, and the difference was exactly this — `LuaSyntaxTree` is only
        // forward-declared in that header, while `TextRange`'s class declares constructors. `files_declaring` takes
        // the **bare** name, so the constructors — whose qualified name is `TextRange::TextRange` — were counted as
        // other meanings of it.
        //
        // A fact whose own qualified name is longer than the one asked about is a member, and a qualified request
        // (`TextRange::StartOffset`) still matches: its qualified name is the name asked for.
        let certain: Vec<_> = certain
            .into_iter()
            .filter(|found| found.fact.scope.is_none() || found.fact.qualified_name() == name)
            .collect();

        let mut kinds: Vec<IndexedKind> = certain
            .into_iter()
            .map(|found| IndexedKind::of(&found.fact))
            .collect();
        kinds.sort_unstable();
        kinds.dedup();

        match kinds.as_slice() {
            [only] => Known::Yes(only.clone()),
            [] => Known::Unknown(UnknownReason::ConditionalCompilation),
            _ => Known::Unknown(UnknownReason::Ambiguous(Box::from(name))),
        }
    }

    /// The declarations the index holds for `name` and `visible_from` can see: the ones that are certainly in scope,
    /// in the order every declaration answer reports in, plus a **count** of the ones reachable only through a
    /// conditional `#include`.
    ///
    /// The walk [`ProjectIndex::definitions`] and [`ProjectIndex::kind_of`] share. It is a function rather than two
    /// copies because the rule it applies — a declaration the file writes itself wins over one it includes, ordered
    /// by file then offset, with the conditional ones counted rather than offered — is the part of a definition
    /// answer that is easy to get subtly different in two places.
    /// **Are these two declarations one entity** — a function declared in a header and defined in the file that includes
    /// it — rather than two things that share a spelling?
    ///
    /// Only a function, and only when the parameter list agrees: `f(void)` in a header and `f(void)` in the file are one
    /// function, while `Widget` in a header and `Widget` in the file are two types. The comparison is of what the facts
    /// record, so it is an answer about spellings rather than about types — a parameter list written differently
    /// (`(int n)` against `(int)`) reads as two entities, which keeps the previous behaviour for that case.
    fn one_entity_declared_twice(
        left: &VisibleDeclaration<'_>,
        right: &VisibleDeclaration<'_>,
    ) -> bool {
        left.fact.kind == DeclKind::Function
            && right.fact.kind == DeclKind::Function
            && left.fact.name == right.fact.name
            && left.fact.scope == right.fact.scope
            && left.fact.parameter_list == right.fact.parameter_list
            // **Only across files.** The rule this serves is "a header declares, the `.cpp` defines" — and inside one file
            // two declarations with the same parameter list can be two *overloads*: the two `describe`s differ only in
            // their `enable_if` condition, which is in the return type and therefore in no field this compares.
            // Measured: `describe(1.5)` answered the first declaration, because the second had been folded into it.
            && left.file != right.file
    }

    fn certain_declarations(
        &self,
        name: &str,
        visible_from: &Path,
    ) -> Result<(Vec<ProjectDeclaration>, usize), UnknownReason> {
        let mut candidates = self.files_declaring(name, visible_from);

        // **A member spelled through an alias.** `std::string::size_type` is not the qualified name of anything
        // the index holds — `size_type` is a member of `basic_string`, and `std::string` is a `using`
        // declaration for it — so the literal lookup finds nothing while the declaration is right there.
        // Measured as a pair, which is what says this is the missing half rather than member resolution being
        // absent altogether:
        //
        // ```text
        // std::basic_string::size_type   -> Yes            member resolution works
        // std::string::size_type         -> NotDeclaredHere   the alias is what does not
        // ```
        //
        // Tried **only after the literal name found nothing**, so a name that resolves today cannot change its
        // answer — the whole change is additive, which matters for a query this many callers share.
        if candidates.is_empty()
            && let Some(rewritten) = self.through_an_alias(name, visible_from)
        {
            candidates = self.files_declaring(&rewritten, visible_from);
        }

        if candidates.is_empty() {
            return Err(UnknownReason::NotDeclaredHere(Box::from(name)));
        }

        // A declaration the file itself writes wins over one it includes, and is the one a reader means: a
        // header's `Widget` and this file's `Widget` are different entities, and C++ resolves to the local one.
        // Overloads of one name written *here* are still several declarations, and they are all answers.
        let own = normalize(visible_from);
        if candidates.iter().any(|found| normalize(&found.file) == own) {
            // **Except one function the header declares and this file defines.** Those are one *entity*, and the
            // header's declaration is the one that makes a use **above** the definition legal — the shape a C file has
            // when its declarations live in a header: `corpus.h` declares `functions_selector` at the top, the call is
            // at line 61, the definition at line 182. Dropping the header's fact left the call with no declaration
            // before it, and `undefined-name` reported it. Measured on a nine-file C corpus: two findings, and
            // reproduced in `tests/checks.rs` with the declaration in a header.
            //
            // The rule above still holds for everything else: a header's `Widget` and this file's `Widget` are two
            // entities, and only a *function* whose parameter list agrees is the same one written twice.
            let local: Vec<VisibleDeclaration<'_>> = candidates
                .iter()
                .filter(|found| normalize(&found.file) == own)
                .cloned()
                .collect();
            candidates.retain(|found| {
                normalize(&found.file) == own
                    || local
                        .iter()
                        .any(|kept| Self::one_entity_declared_twice(kept, found))
                    // **A name in another scope is another entity.** The rule above is about one name written in one
                    // scope in two files; applied to every scope at once, a *member* declared here hid the *class* of
                    // the same name declared in the header. Measured on `LSPHandle.cpp`: `definition("LSPHandle")`
                    // answered `Ambiguous` between two constructors — the header's and this file's own
                    // `LSPHandle::LSPHandle(LanguageServer *)` — while the class's `Type` fact, which the index holds
                    // (`every_fact_named` finds it at `LSPHandle.h:300`), was dropped as "not local". A reader's
                    // `LSPHandle::RefreshDiagnostic` then resolved its qualifier to a constructor, which is the
                    // report "`LSPHandle` was read as the constructor itself rather than the class".
                    //
                    // The class is at file scope (`scope: None`) and the local constructor is at `LSPHandle`'s, so
                    // the two are not competing declarations of one entity; keeping the out-of-scope candidate is the
                    // paragraph above's argument, one level in.
                    || !local
                        .iter()
                        .any(|kept| kept.fact.scope == found.fact.scope)
            });
        }

        // **A declaration in a branch this compilation does not take is not an answer.** libstdc++ declares
        // `_M_data_ptr` twice — `value_type*` under `#else` and `pointer_traits<_Ptr>::element_type*` under
        // `#if __cplusplus >= 201103L` — and `insert` the same way, so both branches arrived as answers and a hover could
        // name the one a compiler never reads (measured: `facts_vs_rendering` counted five such duplicates over
        // `stl_vector.h` and `stl_bvector.h`).
        //
        // The question is not the file's own `#if` but the macros **at that offset**: `visibility_at` walks them, and
        // `Unknown` keeps the declaration — a guard this layer cannot decide must not become a lookup that says the name
        // is not declared.
        //
        // **Skippable by a probe switch, and that is how its remaining work is measured.** `CPPLS_NO_GUARD_FILTER`
        // answers without this step, so the two answers can be compared over the same questions: with a rendering for
        // most files (⑱ makes the rendering the reading) this filter should have almost nothing left to remove, and
        // "almost nothing" is a number this crate's style asks for rather than a claim. See `tests/patch_probe.rs`.
        if !crate::probes::no_guard_filter() {
            candidates.retain(|found| {
                self.a_guard_is_taken(&found.file, found.fact.guard, found.fact.range.start_offset)
            });
        }
        // scope depends on macros this layer does not have, and a jump to a declaration that may not be there is a
        // wrong answer rather than a missing one. The count is what keeps the answer from claiming there is
        // nothing else — "one declaration, and two that might be" is not "one declaration".
        let conditional = candidates
            .iter()
            .filter(|found| found.visibility == IncludeVisibility::Conditional)
            .count();

        let mut certain: Vec<ProjectDeclaration> = candidates
            .into_iter()
            .filter(|found| found.visibility == IncludeVisibility::Unconditional)
            .map(|found| ProjectDeclaration::of(&found))
            .collect();

        if certain.is_empty() {
            return Err(UnknownReason::ConditionalCompilation);
        }

        certain.sort_by(|one, other| {
            one.file
                .cmp(&other.file)
                .then_with(|| one.start_offset.cmp(&other.start_offset))
        });

        Ok((certain, conditional))
    }

    /// **The qualified name a member has when it was spelled through an alias** — see
    /// [`ProjectIndex::certain_declarations`], which asks this only when the literal name found nothing.
    ///
    /// `std::string::size_type` becomes `std::basic_string::size_type`, and the lookup is tried again. The walk
    /// is over the name's **prefixes, longest first**: the alias may be at any position (`a::b::c::d` where `b`
    /// is the alias), the last segment is the name being looked for and replacing *it* is what the caller has
    /// already tried, and an inner alias is the one that decides what the outer name means.
    ///
    /// The target is spelled **relative to the scope the alias was written in**, which is where C++ looks for
    /// it: `using string = basic_string<char, …>` inside `namespace std` names `std::basic_string`. A target the
    /// alias spelled with a qualification of its own (`::other::Thing`) is already absolute and is used as it
    /// stands.
    ///
    /// `None` when no prefix is an alias, or when the chain does not settle — an alias that leads back to
    /// itself is not legal C++, but a bound is cheaper than proving there is none, and a query that loops is an
    /// editor that stops answering.
    fn through_an_alias(&self, name: &str, visible_from: &Path) -> Option<String> {
        /// How many substitutions one name may go through before the answer is "not this way".
        const ALIAS_DEPTH: usize = 4;

        let mut rewritten = name.to_string();
        let tracing = std::env::var("CPPLS_TRACE_ALIAS").is_ok();

        for _ in 0..ALIAS_DEPTH {
            let segments: Vec<&str> = rewritten.split("::").collect();
            if tracing {
                eprintln!("[alias] trying {rewritten}");
            }

            // The last segment is excluded: it is the name being looked for, and substituting it would be
            // answering a different question from the one the caller asked.
            let substituted = (1..segments.len()).rev().find_map(|take| {
                let prefix = segments[..take].join("::");
                // **The entity the prefix names**, preferring a declaration over a synonym: a file that writes both
                // `using std::E;` and (through the header) the `enum class E` has two facts for `E`, and the
                // synonym is the one that says nothing about where `E` really lives.
                let mut candidates = self.files_declaring(&prefix, visible_from);
                candidates.sort_by_key(|found| found.fact.kind == DeclKind::Other);
                if tracing {
                    eprintln!(
                        "[alias] prefix {prefix}: {:?}",
                        candidates
                            .iter()
                            .map(|found| format!(
                                "{} {:?} scope {:?} type {:?}",
                                found.fact.name,
                                found.fact.kind,
                                found.fact.scope,
                                found.fact.type_of
                            ))
                            .collect::<Vec<_>>()
                    );
                }
                let alias = candidates.into_iter().next()?;

                // A prefix that names the entity **itself** — an `enum class` reached through a `using`, a class
                // reached through a typedef from a namespace — is rewritten to the entity's own qualified name, so
                // the member is looked for in the scope that actually declares it. This is the half that was
                // missing: only *aliases* were followed (`type_of` is an alias's target), while a `using`-declared
                // enum has no target at all and its `qualified_name` is the only spelling its members are stored
                // under.
                if let Some(qualified) = self.qualified_name_of_the_entity(alias.fact, &prefix)
                    // **A rewrite that changes nothing is not a rewrite.** The entity's own qualified name *is*
                    // the prefix for an ordinary **type alias** — `using json = basic_json<>;` in `namespace
                    // nlohmann` gives `nlohmann::json` back unchanged — and returning it here skipped the alias arm
                    // below, so `nlohmann::json::object` was retried as `nlohmann::json::object` and answered
                    // `NotDeclaredHere` while `members_of(nlohmann::json)` listed the member. Measured on
                    // `EmmyLuaCodeStyle`'s `LSP.cpp:12`, `auto object = nlohmann::json::object();`: the call's type
                    // was `UnknownType`, and both the hover and go-to-definition stopped at the alias.
                    && qualified != prefix
                {
                    return Some(format!("{qualified}::{}", segments[take..].join("::")));
                }

                // **A namespace alias** — `namespace views = ranges::views;`, which is how libstdc++ spells
                // `std::views`. Its fact is a `Namespace` whose `type_of` is the target, so it is neither a type alias
                // (the case below) nor an entity with a qualified name of its own (the case above): the target is the
                // rewrite. Measured: `std::views::filter` answered `NotDeclaredHere` while `std::ranges::views::filter`
                // was declared in `<ranges>` all along.
                if alias.fact.kind == DeclKind::Namespace
                    && let Some(written_target) = alias.fact.type_of.as_deref()
                {
                    let qualified = if written_target.contains("::") {
                        written_target.to_string()
                    } else {
                        match &alias.fact.scope {
                            Some(scope) => format!("{scope}::{written_target}"),
                            None => written_target.to_string(),
                        }
                    };
                    if qualified != prefix {
                        return Some(format!("{qualified}::{}", segments[take..].join("::")));
                    }
                }

                if alias.fact.kind != DeclKind::Type {
                    return None;
                }
                let target =
                    crate::sema::types::parse_type_spelling(alias.fact.type_of.as_deref()?);
                let class = target.class_name()?;

                let qualified = if class.contains("::") {
                    class.to_string()
                } else {
                    match &alias.fact.scope {
                        Some(scope) => format!("{scope}::{class}"),
                        None => class.to_string(),
                    }
                };

                Some(format!("{qualified}::{}", segments[take..].join("::")))
            });

            let next = substituted?;
            if next == rewritten {
                return None;
            }
            rewritten = next;

            if !self.files_declaring(&rewritten, visible_from).is_empty() {
                return Some(rewritten);
            }
        }

        None
    }

    /// **The qualified name of the entity a spelling names**, when that is not the spelling itself.
    ///
    /// `E` for an `enum class` declared in `std` and reached through `using std::E;` is the measured case: the
    /// spelling the file writes has no `std::`, while every member of the enum is stored under
    /// `std::E::…`. `None` when the fact's own qualified name *is* the spelling (an ordinary name, which is most
    /// of them) — the caller has nothing to rewrite then, and rewriting to the same string only costs a lookup.
    ///
    /// Only a declaration that can **own** members is rewritten: a type or a namespace. A variable or a function
    /// reached through a `using` names no scope, and a rewrite built from it would be a spelling nothing declares.
    fn qualified_name_of_the_entity(&self, fact: &DeclFact, prefix: &str) -> Option<String> {
        if !matches!(fact.kind, DeclKind::Type | DeclKind::Namespace) {
            return None;
        }

        let qualified = fact.qualified_name();
        if qualified == prefix || qualified.is_empty() {
            return None;
        }
        // **The tail has to be the same name.** `using std::E;` introduces `E`, and the entity's trailing segment is
        // `E`; a fact whose tail differs is a rewrite that changes what is being looked for.
        let tail = qualified.rsplit("::").next().unwrap_or_default();
        let written = prefix.rsplit("::").next().unwrap_or_default();
        (tail == written).then_some(qualified)
    }

    /// What the macro name `name` is at `offset` in the file at `visible_from`.
    ///
    /// # Translation order is the whole answer
    ///
    /// A preprocessor reads a translation unit as one stream: the file's own lines, with each `#include` replaced
    /// by the whole of the file it names — recursively — and the macros in force at a point are decided by the
    /// **last** `#define` or `#undef` of that name to have gone past. So the position of a fact is not an offset
    /// but a **chain** of them: the `#include` that pulled its file in, then the `#include` inside *that* file, and
    /// so on, ending with the fact's own offset. Comparing two chains lexicographically *is* comparing where they
    /// came in the stream, which is why this needs no separate rules for "written here" and "written in a header":
    ///
    /// ```text
    /// a.cpp:   #define MAX 1        position [0]         -> the header's wins
    /// a.cpp:   #include "x.h"       position [10, 4]
    /// a.cpp:   #include "x.h"                          -> the local one wins
    /// a.cpp:   #define MAX 1         position [0]
    /// ```
    ///
    /// # The four answers
    ///
    /// * `Yes` — the last fact in that order is a `#define`.
    /// * `Unknown(UndefinedHere)` — it is an `#undef`. Not `No`, and not a pointer at the `#define` it used to
    ///   have: a name that was undefined above the cursor is an ordinary identifier, and a jump to a definition
    ///   that is no longer in force would be a wrong answer rather than a missing one.
    /// * `Unknown(ConditionalCompilation)` — every fact that could decide it is inside an `#if`, or reached
    ///   through an `#include` that is. See below for the rule that keeps this from swallowing the common case.
    /// * `Unknown(NotDeclaredHere)` — nothing in the index touches the name. **Not** "there is no such macro":
    ///   the index holds the files it has been asked about, and a macro defined in a header nobody indexed looks
    ///   exactly like a name that is not a macro at all.
    ///
    /// # Why the answer prefers the unconditional fact
    ///
    /// The same rule [`ProjectIndex::definition`] uses, for the same reason. An unconditional `#define` above a
    /// *guarded* one is what the name certainly is; reporting `ConditionalCompilation` instead would refuse to
    /// answer a question that has an answer. Only when nothing unconditional is in the running does the answer
    /// become `Unknown` — and the residual uncertainty is stated rather than hidden: a guarded `#undef` *after* an
    /// unconditional `#define` is treated as not having happened.
    pub fn macro_definition(
        &self,
        name: &str,
        visible_from: &Path,
        offset: usize,
    ) -> Known<ProjectMacro> {
        match self.macro_environment(name, visible_from).at(offset) {
            Known::Yes(found) => Known::Yes(ProjectMacro {
                file: found.file.clone(),
                fact: found.fact.clone(),
            }),
            Known::Unknown(reason) => Known::Unknown(reason),
            Known::No => Known::No,
        }
    }

    /// Everything this file can know about one macro name, **computed once** and then asked about any offset.
    ///
    /// [`ProjectIndex::macro_definition`] is one walk of the include graph per call, which is the right shape for a
    /// query about one cursor. It is the wrong shape for a query about **thousands** of positions in the same file,
    /// and that is not a hypothetical: `macro_references` asked it once per hit and took **3.8 s** on
    /// `STDMETHODCALLTYPE` in the standard-library closure — 4 079 hits, each walking the same graph, to produce an
    /// answer whose every input was identical. This is that walk, done once per file, with the offset applied to the
    /// result instead of to the search.
    ///
    /// The cost is one traversal of the reachable files per caller, so a caller that asks about one position should
    /// use [`ProjectIndex::macro_definition`] and one that asks about many should hold this.
    pub fn macro_environment(&self, name: &str, visible_from: &Path) -> MacroEnvironment {
        // **The walk is remembered, because it is the whole cost and it is asked again.** Measured on neovim:
        // 1.19 s per walk, three identical walks in a row, and every repeated question paid it again — see
        // [`ProjectIndex::macro_environments`] for the numbers and for the invalidation rule.
        let key = (normalize(visible_from), name.to_string());
        if let Ok(memo) = self.macro_environments.lock()
            && let Some(cached) = memo.get(&key)
        {
            return cached.environment.clone();
        }

        let mut candidates = Vec::new();
        let certain = self.certainly_in_the_translation_unit(visible_from);
        // The walk's own visited set is the contributor list — the same evidence [`ProjectIndex::visibility`] keeps.
        let mut visited = HashSet::new();

        self.macro_candidates(
            visible_from,
            &mut Vec::new(),
            false,
            &mut visited,
            &certain,
            &mut Collecting::Name(name, &mut candidates),
            &mut self.macros.clone(),
            None,
        );

        let environment = MacroEnvironment {
            name: name.to_string(),
            candidates,
        };

        let mut contributors: Vec<String> = visited.into_iter().collect();
        contributors.sort();
        if let Ok(mut memo) = self.macro_environments.lock() {
            if memo.len() >= MAX_CACHED_MACRO_WALKS {
                memo.clear();
            }
            memo.insert(
                key,
                CachedMacroWalk {
                    contributors,
                    environment: environment.clone(),
                },
            );
        }

        environment
    }

    /// **Every macro name this file's environment defines**, from **one** walk of the include graph.
    ///
    /// # The measurement this exists for
    ///
    /// The colouring pass asks "is this spelling a macro" once per identifier it cannot otherwise classify, and it
    /// used to ask [`ProjectIndex::macro_environment`] — one whole walk of the graph — **per distinct spelling**.
    /// Measured on this repository's own `codeformat.h`: `semanticTokens` answered **521 tokens in 526 ms**, and the
    /// walk was essentially all of it (a header mentions a few hundred names nothing in the file declares). One walk
    /// that collects the names answers every one of them from a hash lookup.
    ///
    /// The precision is the same as the per-name form for the case that reaches here: a macro an `#include` brought in
    /// is in force for the whole file, and a `#define` the file writes itself is answered by
    /// [`crate::semantic`]'s own step 2, which is already whole-file. An `#undef` of an *included* macro is the one
    /// shape this cannot express, and it is not expressible in step 2 either.
    pub fn macro_names_in_force(&self, visible_from: &Path) -> HashSet<String> {
        // The same memo as [`ProjectIndex::macro_environment`], keyed by the file alone: the colouring pass asks for
        // the whole set once per file and it is the one question that needs the closure.
        let key = normalize(visible_from);
        if let Ok(memo) = self.macro_names.lock()
            && let Some(cached) = memo.get(&key)
        {
            return cached.names.clone();
        }

        let mut names = HashSet::new();
        let certain = self.certainly_in_the_translation_unit(visible_from);
        let mut visited = HashSet::new();

        self.macro_candidates(
            visible_from,
            &mut Vec::new(),
            false,
            &mut visited,
            &certain,
            &mut Collecting::Names(&mut names),
            &mut self.macros.clone(),
            None,
        );

        let mut contributors: Vec<String> = visited.into_iter().collect();
        contributors.sort();
        if let Ok(mut memo) = self.macro_names.lock() {
            if memo.len() >= MAX_CACHED_MACRO_WALKS {
                memo.clear();
            }
            memo.insert(
                key,
                CachedMacroNames {
                    contributors,
                    names: names.clone(),
                },
            );
        }

        names
    }

    /// **The macros in force at one point**, as a walk from that file computes them.
    ///
    /// The compilation's own environment (what the compiler predefines and the command line says) plus every fact
    /// the walk passes on the way to `offset`, applied in the order a preprocessor applies them — which is the only
    /// order that is right: a `#define` written below the point is not in force, one written in a header that comes
    /// later is not either, and a header that comes earlier is.
    ///
    /// Two things this is *not*: it is not a claim that the answer is complete (a header outside the index, or a
    /// `-D` nobody mentioned, is simply not in it — see [`crate::index::environment`]), and it is not a summary of
    /// the whole translation unit (the walk stops at `offset`, which is what makes it a question about a point).
    ///
    /// Costs one traversal of the files that precede the point, so a caller asking about **one** position should use
    /// this and a caller asking about thousands of them should use the incremental state
    /// [`ProjectIndex::macro_environment`] builds while it walks.
    pub fn macros_at(&self, path: &Path, offset: usize) -> Marked {
        let mut state = self.macros.clone();
        let certain = self.certainly_in_the_translation_unit(path);

        self.macro_candidates(
            path,
            &mut Vec::new(),
            false,
            &mut HashSet::new(),
            &certain,
            &mut Collecting::Nothing,
            &mut state,
            Some(offset),
        );

        state
    }

    /// The files this query reaches through **unguarded includes only** — no `#if` anywhere on the way.
    ///
    /// This is the answer to "is this file part of the translation unit whatever the macros are", and it is asked
    /// once per walk instead of being inferred from the route the walk happened to take: `visited` enters a
    /// file once, so the first route to reach it decides how everything it defines is filed, and that first route
    /// can be a conditional include while an unguarded one exists elsewhere in the same translation unit.
    ///
    /// # Why not ask `visible_files`
    ///
    /// It answers the same question and answers it *better* — its `Unconditional` also counts an `#include` whose
    /// condition was evaluated and found taken. It cannot be used here: that walk evaluates conditions, evaluating
    /// one calls [`ProjectIndex::macros_at`], and `macros_at` is what builds this set. Written that way it was a
    /// stack overflow on the first run (`macros_at` → `visible_files` → `visibility_at` → `macros_at` → …, with the
    /// memo unable to break the cycle because an answer is only recorded once it has been computed). So what is
    /// taken from that idea is the part that needs **nothing evaluated**, and a guarded include that *is* taken
    /// still counts for the walk through its own route: `visibility == Active` already keeps a route certain, see
    /// `macro_candidates`.
    fn certainly_in_the_translation_unit(&self, from: &Path) -> HashSet<String> {
        let from = normalize(from);

        // The file itself, always: a question asked in a file is about what that file says.
        let mut certain = HashSet::from([from.clone()]);
        let mut pending = vec![from];

        while let Some(current) = pending.pop() {
            let Some(summary) = self.summaries.get(&current) else {
                continue;
            };

            for include in &summary.includes {
                if include.guard != FactGuard::Unconditional {
                    continue;
                }

                let Some(resolved) = &include.resolved else {
                    continue;
                };

                let next = normalize(resolved);
                if certain.insert(next.clone()) {
                    pending.push(next);
                }
            }
        }

        certain
    }

    /// Every fact about `name` in this file and everything it includes, with where each one sits.
    ///
    /// A file is expanded once per query. That is enough for the answer — the facts are the same however many
    /// paths reach them — and it is what makes a cycle of includes terminate. What it costs is the ordering *among
    /// facts reached through the same top-level include*, which is the one case where a header reached twice by
    /// different routes could be placed at the earlier of its two positions rather than the later; the fact it
    /// reports is the same either way.
    ///
    /// No offset is applied here: where a fact *is* in the stream is the fact, and which of them is in force at a
    /// particular cursor is [`MacroEnvironment::at`]'s question. That split is what lets one walk answer thousands
    /// of positions.
    ///
    /// # The stream is one stream
    ///
    /// A file's `#define`s and its `#include`s are read **in offset order**, and the state in `state` is brought up
    /// to each point before anything is asked about that point. That is not an implementation detail: it is what
    /// makes `#ifdef X` decidable in a header whose *includer* defined `X`, and it is why the file's own directives
    /// and the ones its includes bring in are **one** stream rather than two lists. Two lists walked separately
    /// would decide every condition against the environment as it was before the file was read.
    ///
    /// # What the state is allowed to take from a fact
    ///
    /// Only what is **certain**, because the state decides later conditions and a wrong entry would make them
    /// decided wrongly rather than undecided:
    ///
    /// ```text
    /// the file is certainly in the translation unit, and the fact's region is taken → the name, with its value
    /// the fact settles the name whatever the branch                                  → definedness alone, never the value
    /// anything else (the region is unknown, or the file may not be included)         → nothing
    /// ```
    ///
    /// The second line is [`MacroFact::settles_the_name`] doing the same job it does for references: `#ifndef NAME /
    /// #define NAME` says the name *is* a macro afterwards whichever branch ran, and it does **not** say which body
    /// it has — so the name is defined and its value stays unknown.
    ///
    /// The first line used to read "the whole **path** is unconditional", where the path meant the route this walk
    /// took — see `certain`.
    #[allow(clippy::too_many_arguments)]
    fn macro_candidates(
        &self,
        path: &Path,
        chain: &mut Vec<usize>,
        path_conditional: bool,
        visited: &mut HashSet<String>,
        certain: &HashSet<String>,
        collecting: &mut Collecting<'_>,
        state: &mut Marked,
        upto: Option<usize>,
    ) {
        let path = normalize(path);
        if !visited.insert(path.clone()) {
            return;
        }

        // **A file this query reaches unconditionally is certainly part of the translation unit**, whatever route
        // this particular walk took to get here. The flag above is about *this* path — `visited` means a file
        // is entered once, so the first route to reach it decided everything below — and the first route can be a
        // conditional include while an unconditional one exists elsewhere in the same translation unit. Asking the
        // graph instead of the route is what lets the certain path be used: `windef.h` includes `winnt.h`
        // unconditionally, so `winnt.h`'s macros are in force, whatever `minwindef.h` did earlier.
        let path_conditional = path_conditional && !certain.contains(&path);

        let Some(summary) = self.summaries.get(&path) else {
            // A file the walk cannot read is a hole in what this state knows: it may define anything, so from here
            // on a name nothing mentions is unknown rather than undefined.
            state.mark_incomplete();
            return;
        };

        // **The module edges, before the `#include`s and before the file's own text.** `import m;` is not an
        // `#include` with another spelling: it is not textual (no macro travels along it) and it names a *module*
        // rather than a file, so the file behind it is found through the module the project declares. All three
        // paths — a header unit, a partition of this file's own module, and an imported module's interface — are
        // `Unconditional`, which is the simplification `visible_files_by_asking_each_condition` documents: an
        // `import` inside an `#if` is recorded like any other, so a module reached only through a condition the
        // compilation does not satisfy is offered rather than hidden.
        //
        // **Recorded for a collector that is walking for visibility, and for no other one.** A module edge is not
        // an `#include`: it brings declarations into view and carries no `#define`, so a walk whose job is a macro
        // environment must not descend through one — which is what `crossed_a_module` says by queueing the target
        // for a second pass rather than recursing. See [`Seen::module_work`].
        for unit in &summary.modules.header_units {
            collecting.crossed_a_module(&normalize(unit));
        }
        for unit in &summary.modules.partitions {
            collecting.crossed_a_module(&normalize(unit));
        }
        for imported in &summary.modules.imports {
            let Some(interface) = self.module_interfaces.get(imported.as_ref()) else {
                // No file in this project declares it: `import std;` and prebuilt modules land here, and the
                // honest reading is "unknown", never "nothing" — a name that cannot be seen is not a name that
                // does not exist. Nothing is added, and nothing is claimed.
                continue;
            };
            collecting.crossed(interface, IncludeVisibility::Unconditional, true);
            collecting.crossed_a_module(&normalize(Path::new(interface)));
        }

        // **A module implementation unit implicitly imports its own interface unit** — `module math;` in a file that
        // is not `export module math;` gives that unit every name the interface declares, without an `import`
        // anywhere. A compiler relies on it: `math.cpp` defines `Vec2::length` and reads `x_`, which only
        // `math.cppm` declares.
        //
        // Measured on `test_module/src/math.cpp` before this existed: `x_` and `square(x_)` in the bodies resolved to
        // nothing, the hover was empty, and the completion inside a member function listed 200 names — every one of
        // them a macro or a function from the headers `math.cpp` includes, and not one member of `Vec2`.
        //
        // Only the *primary* module is crossed into: a partition implementation unit (`module m:part;`) is a
        // different question with its own rules, and `partition.is_none()` keeps this from answering it wrongly.
        if !summary.modules.is_interface
            && summary.modules.partition.is_none()
            && let Some(module) = &summary.modules.module
            && let Some(interface) = self.module_interfaces.get(module.as_ref())
        {
            collecting.crossed(interface, IncludeVisibility::Unconditional, true);
            collecting.crossed_a_module(&normalize(Path::new(interface)));
        }

        // What this walk made of this file's regions, recorded the first time each is asked about. The answer is
        // the one the *condition's own point* gives, and the first fact or include inside a region is the first
        // point at which the walk can ask — before anything inside the region has been applied. Asking again later
        // would read the region's own body as evidence about its condition, which is backwards for exactly the
        // shape that matters: `#ifndef NAME / #define NAME / #include <a.h> / #endif` has to include `a.h` on the
        // first pass, and a fresh look at the same condition after the `#define` would say it does not.
        //
        // **Keyed by the region *and the branch asked about***, which is the pair the answer is actually a function
        // of: "is branch *b* of region *r* the one that gets compiled" depends on the branches before *b* and on
        // nothing else, so it does not move as the walk advances. Keyed by the region alone it did move — the
        // branch asked about is the one the **fact** sits in, which is a position, so a verdict recorded for a fact
        // inside the `#if` was reused for a fact inside the `#else`. Measured on `vcruntime.h`: `_STL_LANG`'s live
        // definition at 7124 put `Region(32) → Some(true)` (7124 is in the `#if`) in this map, and the dead
        // `#define _STL_LANG 0L` at 7422 (in the `#else`) read that verdict back, so a `#define` no compiler reads
        // was applied and `_HAS_CXX17` came out `0`.
        let mut verdicts: HashMap<(u32, usize), Option<bool>> = HashMap::new();

        // The two lists are each in offset order (the indexer sorts them), so one merge of them *is* the order a
        // preprocessor reads in. A fact and an include can never start at the same offset.
        let mut facts = summary.macros.iter().peekable();
        let mut includes = summary.includes.iter().peekable();

        loop {
            let next_fact = facts.peek().map(|fact| fact.range.start_offset);
            let next_include = includes.peek().map(|include| include.range.start_offset);

            let (at, take_fact) = match (next_fact, next_include) {
                (Some(fact), Some(include)) => (fact.min(include), fact <= include),
                (Some(fact), None) => (fact, true),
                (None, Some(include)) => (include, false),
                (None, None) => break,
            };

            if upto.is_some_and(|upto| at >= upto) {
                break;
            }

            if take_fact {
                let fact = facts.next().expect("peeked");
                let reach = self.fact_reach(
                    summary,
                    &mut verdicts,
                    state,
                    &mut *collecting,
                    fact.guard,
                    at,
                );
                if reach == FactReach::Inactive {
                    continue;
                }

                collecting.fact(summary, chain, fact, path_conditional, reach);

                // …and then the name is in force for everything below this point. After the fact was read for its
                // own guard, which is the order a preprocessor reads in: `#ifndef NAME / #define NAME` is taken
                // *because* the name is not defined yet.
                apply_fact(state, fact, path_conditional, reach);

                continue;
            }

            let include = includes.next().expect("peeked");

            let visibility = self.include_visibility(
                summary,
                &mut verdicts,
                state,
                &mut *collecting,
                include.guard,
                at,
            );

            if visibility == Visibility::Inactive {
                continue;
            }

            let Some(target) = &include.resolved else {
                // An `#include` that did not resolve is the one gap the walk cannot make smaller: the file it
                // names may define anything at all, so every later "nothing defines this name" answer is off.
                state.mark_incomplete();
                continue;
            };

            // **The edge, recorded where it is crossed.** A collector that is walking for the *visibility* of the
            // root's closure wants this and nothing else, and this is the only point at which the truth about how
            // a file became visible is still available — see [`Collecting::crossed`]. Recorded *before* the
            // descent, because a file the walk cannot read still became visible by being named here: the old walk
            // recorded the edge and then failed to enter, and a conditional include of a header nobody indexed is
            // exactly the `Conditional` a "there may be more" answer is about.
            let step = match visibility {
                Visibility::Active => IncludeVisibility::Unconditional,
                Visibility::Unknown => IncludeVisibility::Conditional,
                // Unreachable: the branch above skips an inactive edge, and dropping it is the rule that makes a
                // decidable `#if` worth deciding at all.
                Visibility::Inactive => continue,
            };
            collecting.crossed(&normalize_path(target, cfg!(windows)), step, false);
            // **An `#include` makes the whole file visible**, however it was reached before: a file that is both
            // included and imported is not subject to the narrower exported-only rule, because the wider one
            // already grants what it would hide.
            collecting.reached_by_include(&normalize_path(target, cfg!(windows)));

            chain.push(include.range.start_offset);
            self.macro_candidates(
                target,
                chain,
                path_conditional || visibility == Visibility::Unknown,
                visited,
                certain,
                &mut collecting.reborrow(),
                state,
                // An included file is pasted *at* the include, so all of it is read before the caller's next line.
                None,
            );
            chain.pop();
        }
    }

    /// What the walk makes of one fact's region, recorded per file so that every condition in it is decided the
    /// same way.
    fn fact_reach(
        &self,
        summary: &FileSummary,
        verdicts: &mut HashMap<(u32, usize), Option<bool>>,
        state: &Marked,
        collecting: &mut Collecting<'_>,
        guard: FactGuard,
        offset: usize,
    ) -> FactReach {
        // A reborrow, so that the caller keeps its own use of `collecting` — a `&mut` is moved by default and the
        // walk needs the collector again on the next line of the file.
        match self.include_visibility(summary, verdicts, state, &mut *collecting, guard, offset) {
            Visibility::Active => FactReach::Active,
            Visibility::Inactive => FactReach::Inactive,
            Visibility::Unknown => FactReach::Unknown,
        }
    }

    /// Was the code the guard names compiled, with the state the walk has built and the verdicts it has recorded?
    fn include_visibility(
        &self,
        summary: &FileSummary,
        verdicts: &mut HashMap<(u32, usize), Option<bool>>,
        state: &Marked,
        collecting: &mut Collecting<'_>,
        guard: FactGuard,
        offset: usize,
    ) -> Visibility {
        let FactGuard::Region(region) = guard else {
            return Visibility::Active;
        };

        // **The file's own include guard is not a condition**. `#ifndef _STRING_ / #define _STRING_`
        // followed by the file's includes is how every header is written, and by the time the walk reaches an
        // include the name has been defined *by the line above it* — so evaluating that region says "not taken"
        // and the walk skips **every include of the file**. The visible consequence was MSVC's whole library:
        // `_STL_COMPILER_PREPROCESSOR`, defined by `<yvals_core.h>`, came out `defined = Some(false)` in the state
        // at `<string>`'s own `#include <xstring>`, so `#if _STL_COMPILER_PREPROCESSOR` — a condition that holds —
        // was answered `Inactive`, and every fact behind it read as `Conditional`.
        //
        // The index already treats the facts guarded by exactly this region as unconditional
        // (`deguard_the_files_own_guard`), and `SummaryGuards::own_guard` exists so that a **walk** can apply the
        // same rule — which is what this is. Entering the file at all is what the guard means.
        if summary.guards.own_guard == Some(region) {
            return Visibility::Active;
        }

        let mut unknown = false;

        for at in summary.guards.conditions_of(region) {
            // The branch this position sits in, which is what the verdict below is *about* — and half of the key it
            // is remembered under, because "is this branch compiled" does not depend on where the fact stands.
            let Some(branch) = summary
                .guards
                .region_at(at.region, offset)
                .map(|region| region.active_branch)
            else {
                // A guard naming a region this summary does not describe — a summary written before the regions
                // carried their conditions, or one whose bytes were produced by something else. Nothing can be said
                // about it, and `Unknown` is what every query said about every region before this existed.
                unknown = true;
                continue;
            };

            // **The walk answering its own question answers it here**, which is the difference between one
            // traversal of the closure and one per condition. `None` is every other collector, and then the state
            // below is the one this walk was handed rather than the one it built.
            let holds = match verdicts.get(&(at.region, branch)) {
                Some(recorded) => *recorded,
                None => {
                    let decided = match collecting.decided_at(
                        summary,
                        state,
                        at.region,
                        at.condition_at,
                        offset,
                    ) {
                        Some(verdict) => verdict,
                        None => summary
                            .guards
                            .region_at(at.region, offset)
                            .and_then(|region| {
                                region.visibility(
                                    &crate::index::environment::MacrosHere::from_walk(
                                        state,
                                        at.condition_at,
                                    ),
                                )
                            }),
                    };

                    verdicts.insert((at.region, branch), decided);
                    decided
                }
            };

            match holds {
                Some(true) => {}
                Some(false) => {
                    // **An `#else` is taken precisely when the condition is *not*.** The verdict above
                    // answers "did this region's `#if` hold", which is the right question for the branch the
                    // condition guards and the wrong one for the `#else`, whose whole meaning is "nothing before me
                    // was taken". One of those decides MSVC's entire STL: `yvals_core.h` writes
                    //
                    // ```cpp
                    // #if defined(RC_INVOKED) || defined(Q_MOC_RUN) || defined(__midl)
                    // #define _STL_COMPILER_PREPROCESSOR 0
                    // #else
                    // #define _STL_COMPILER_PREPROCESSOR 1     // <- this is the definition that is in force
                    // #endif
                    // ```
                    //
                    // so the definition that *is* compiled was judged "not taken" (measured: `reach = Inactive`
                    // for both facts), `#if _STL_COMPILER_PREPROCESSOR` then had no value, and every query in the
                    // library answered `ConditionalCompilation`.
                    //
                    // # The inversion compensated for the memo, and the memo is fixed
                    //
                    // Removing it is the *obvious* correction — `region_at` chooses a branch by offset, so
                    // `Region::visibility` already answers "is the branch in force here the one compiled", and one
                    // inversion on top of that turns a dead `#else` into a live one.
                    //
                    // It was tried once and reverted: **eight MSVC headers went from 319 deduced to 251, refused
                    // 312 → 380**. That measurement was taken **before** `verdicts` was keyed by `(region, branch)`.
                    // With the memo keyed by region alone, a `Some(false)` for a position inside an `#else` was
                    // almost unreachable — the verdict read back was the one recorded for a fact inside the `#if` —
                    // so this rule was load-bearing for a reason that was itself a bug. The numbers above are a
                    // measurement of that bug, not of this rule.
                    return Visibility::Inactive;
                }
                None => unknown = true,
            }
        }

        if unknown {
            Visibility::Unknown
        } else {
            Visibility::Active
        }
    }
}

/// What a walk is collecting as it goes: the facts about one name, the visibility of every file it enters, or
/// nothing.
///
/// The same walk answers all three questions — "where is this name a macro"
/// ([`ProjectIndex::macro_environment`]), "what is in force at this point" ([`ProjectIndex::macros_at`]) and "what
/// can this file see" ([`ProjectIndex::visible_files_with_modules`]) — because they are the same traversal and the
/// rules that make it right are the ones that must not be written twice. The second caller wants the *state* and no
/// candidates, which is what `Nothing` says, rather than a name no macro has.
enum Collecting<'a> {
    Name(&'a str, &'a mut Vec<MacroCandidate>),
    /// **Every macro name the walk applies**, for a caller that has to ask about many of them — the colouring pass
    /// asks "is this spelling a macro" once per identifier, and asking the graph once per spelling was 526 ms on a
    /// real header. See [`Collecting::fact`].
    Names(&'a mut HashSet<String>),
    /// **Which files this root can see, and how** — filled in as the walk crosses each `#include`.
    ///
    /// This variant is the whole of why the visibility walk is affordable. Asking the same question per *edge* —
    /// `visible_files_with_modules` as it was written — evaluates each guarded include against a state built for
    /// that one file (`environment::visibility_at`, which is a closure walk), so a query over the standard library
    /// pays one walk per condition in the closure. Carried this way the state is already in hand when the edge is
    /// crossed, which is what [`crate::index::environment::MacrosHere::from_walk`] exists for.
    Visibility(&'a mut Seen),
    Nothing,
}

/// The files one root can see, and which of them are in view only through an `import`.
///
/// One memoised visibility walk: what it found, and **the files it was made of**.
///
/// The contributors are the normalized paths of the closure (the root and every file [`Seen::visibility`] records),
/// so a re-read of one of them drops exactly the walks that could have answered differently. See
/// [`ProjectIndex::visibility`] for the measurement that made this worth carrying.
#[derive(Debug)]
struct CachedWalk {
    seen: std::sync::Arc<Seen>,
    contributors: std::sync::Arc<Vec<String>>,
}

/// Two outputs from one walk because the second is a property of *how* a file was reached, and a walk that has
/// already crossed the edge is the only thing that knows. See [`ProjectIndex::visible_files_with_modules`].
#[derive(Default, Debug)]
struct Seen {
    visibility: HashMap<String, IncludeVisibility>,
    through_an_import: HashSet<String>,
    /// **The files whose module edges still have to be followed.**
    ///
    /// A module edge is not an `#include`, and the difference is why this frontier exists rather than another
    /// recursive descent: an `import` brings *declarations* into view and carries no `#define`, so
    /// `macro_candidates` — whose whole job is a macro environment — must not walk through one. But the
    /// *visibility* of a partition's declarations is asked the same question, so this collector keeps its own list
    /// and works it after the walk. Measured: without it, `rectangle` and `square` — declared in the partition
    /// `shapes.cppm` re-exports — answered `NotDeclaredHere`.
    module_work: Vec<String>,
}

impl Seen {
    fn new(root: &str) -> Seen {
        Seen {
            visibility: HashMap::from([(root.to_string(), IncludeVisibility::Unconditional)]),
            through_an_import: HashSet::new(),
            module_work: Vec::new(),
        }
    }
}

impl Collecting<'_> {
    /// **One** fact, if the caller is collecting facts about that name — or **every** name, when it is collecting
    /// the environment ([`Collecting::Names`]).
    fn fact(
        &mut self,
        summary: &FileSummary,
        chain: &[usize],
        fact: &MacroFact,
        path_conditional: bool,
        region: FactReach,
    ) {
        // **The name-collecting arm, and the reason it exists**: the colouring pass used to ask
        // `macro_environment(name, file)` once per *spelling* not declared in the file, and each of those is a whole
        // walk of the include graph. Measured on this project's `codeformat.h` — **526 ms** for 521 tokens, because a
        // header mentions a few hundred names and each one paid the walk. Collecting every name in one walk answers
        // all of them from one pass, and the question "is this spelling a macro here" is the same question.
        if let Collecting::Names(out) = self {
            out.insert(fact.name.clone());
            return;
        }

        let Collecting::Name(name, out) = self else {
            return;
        };

        if fact.name != *name {
            return;
        }

        let mut position = chain.to_vec();
        position.push(fact.range.start_offset);

        out.push(MacroCandidate {
            position,
            file: summary.path.clone(),
            fact: fact.clone(),
            path_conditional,
            region,
        });
    }

    /// The same collection, for a recursive call.
    fn reborrow(&mut self) -> Collecting<'_> {
        match self {
            Collecting::Name(name, out) => Collecting::Name(name, out),
            Collecting::Names(out) => Collecting::Names(out),
            Collecting::Visibility(seen) => Collecting::Visibility(seen),
            Collecting::Nothing => Collecting::Nothing,
        }
    }

    /// **A file has just become visible through an `#include`**, at the visibility the edge was given.
    ///
    /// Recorded at the *crossing* rather than when the file is entered, and the difference is a wrong answer
    /// rather than a tidy one: `visited` enters a file once, so the second route to it never reaches its own
    /// `enter`, and a file reached by a guarded include first and an unguarded one second would be filed
    /// `Conditional` for the rest of the walk. The better of the two wins, which is what the per-edge version
    /// computed and is the only reading that is true.
    fn crossed(&mut self, target: &str, visibility: IncludeVisibility, through_an_import: bool) {
        let Collecting::Visibility(seen) = self else {
            return;
        };

        match seen.visibility.get(target) {
            // Already known, and no worse: unconditional is the strongest answer and nothing improves on it.
            Some(known) if *known <= visibility => {}
            _ => {
                seen.visibility.insert(target.to_string(), visibility);
            }
        }

        if through_an_import {
            seen.through_an_import.insert(target.to_string());
        }
    }

    /// An `#include` reaches `target`, so the exported-only rule stops applying to it.
    ///
    /// The order the two edges arrive in does not matter, and that is the point: a file imported first and
    /// included later is include-visible, and one included first and imported later was already so.
    fn reached_by_include(&mut self, target: &str) {
        let Collecting::Visibility(seen) = self else {
            return;
        };

        seen.through_an_import.remove(target);
    }

    /// **A module edge was crossed**, so the target's own module edges still have to be followed.
    ///
    /// Recorded for a second pass rather than descended, for the reason [`Seen::module_work`] gives: the walk this
    /// collector rides on is building a macro environment, and a macro does not travel across an `import`.
    ///
    /// **Queued whether or not the file was already visible**, which is the difference between following the edges
    /// of what this root reaches and following the edges of one arbitrary file: a partition's own `export import`
    /// is reachable only through this queue, and a file that is already in the visibility map for another reason
    /// still has them. Measured: gated on "not seen before", `rectangle` and `square` answered `NotDeclaredHere`.
    fn crossed_a_module(&mut self, target: &str) {
        let Collecting::Visibility(seen) = self else {
            return;
        };

        seen.visibility
            .entry(target.to_string())
            .or_insert(IncludeVisibility::Unconditional);

        if !seen.module_work.iter().any(|queued| queued == target) {
            seen.module_work.push(target.to_string());
        }
    }

    /// **One guarded edge**, and this walk is the one answering it.
    ///
    /// The sink [`ProjectIndex::include_visibility`] calls instead of building a closure state for the file: the
    /// state is in hand, because this walk is already carrying it, and that is the difference between one traversal
    /// and one traversal per condition. `state` is the walk's state **at the condition's own point**, which is what
    /// the answer is a function of — a `#define` above the condition is in force and one below is not.
    ///
    /// The answer is **the raw verdict** — `Some(true)` the condition holds, `Some(false)` it does not, `None`
    /// nobody can say — and deliberately not a [`Visibility`]: the two are not the same thing, because a guard's
    /// `#else` is compiled exactly when its `#if` does *not* hold. `include_visibility` owns that inversion, and a
    /// second copy of it here is how this function first read `Unknown` as `Inactive`.
    ///
    /// `None` means "not this walk's question", which is every other variant of [`Collecting`].
    fn decided_at(
        &mut self,
        summary: &FileSummary,
        state: &Marked,
        region: u32,
        condition_at: usize,
        offset: usize,
    ) -> Option<Option<bool>> {
        let Collecting::Visibility(seen) = self else {
            return None;
        };
        let _ = seen;

        // **The file's own include guard is not a condition**, the same rule the branch above applies: by the time
        // the walk reaches anything in the file the name has been defined by the line above it, so evaluating that
        // region would say "not taken" and drop every include in the file. `true` is "the code behind it is
        // compiled", which is what entering the file means.
        if summary.guards.own_guard == Some(region) {
            return Some(Some(true));
        }

        let asked = summary.guards.region_at(region, offset)?;
        Some(
            asked.visibility(&crate::index::environment::MacrosHere::from_walk(
                state,
                condition_at,
            )),
        )
    }
}

/// What a fact does to the state, if anything — see [`ProjectIndex::macro_candidates`] for the three cases.
///
/// Called *after* the fact's own guard has been read, which is the order a preprocessor reads in: the
/// `#ifndef NAME / #define NAME` shape is taken because the name is not defined yet, and a state that had already
/// absorbed the `#define` would decide it the other way round — for every include guard in the corpus.
fn apply_fact(state: &mut Marked, fact: &MacroFact, path_conditional: bool, reach: FactReach) {
    // A fact in a file that may not have been included at all, or in a region nobody can decide: the name may or
    // may not be defined here, and a later condition must not be told either way.
    if path_conditional || reach == FactReach::Unknown {
        // …unless the region settles the name whatever its own condition says, which is the one thing an
        // undecidable branch *can* still say — and it says it about definedness only, never about the value.
        match (fact.settles_the_name, fact.kind) {
            (true, crate::MacroKind::Definition) => state.define_name(&fact.name),
            (true, crate::MacroKind::Undefinition) => state.undefine(&fact.name),
            _ => state.mark_uncertain(&fact.name),
        }

        return;
    }

    match reach {
        // In force: the name and its value, as the file wrote them.
        FactReach::Active => state.observe(fact),
        // Handled above.
        FactReach::Inactive | FactReach::Unknown => {}
    }
}

/// How reachable a fact is, as the walk sees it: whether its own region is decided.
///
/// A name of its own rather than [`Visibility`], because the walk has a fourth case the guard layer does not: a
/// fact that is *not* written in a conditional at all, which is certain without anything being evaluated.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FactReach {
    /// The fact is outside every conditional, or its region is decided and taken.
    Active,
    /// The region is decided and **not** taken: a compiler would not have read this fact.
    Inactive,
    /// At least one enclosing condition cannot be decided here.
    Unknown,
}

/// Every fact about one macro name that a file can reach — the answer to "what is this name here", before the
/// question of *where* is asked.
///
/// Built by [`ProjectIndex::macro_environment`]. The point of holding it is that the expensive half — walking the
/// include graph for the facts — does not depend on the offset, while the cheap half does.
#[derive(Debug, Clone, Default)]
pub struct MacroEnvironment {
    /// The name asked about, kept so that a reason can say *which* name could not be resolved — the walk is over
    /// one name and a caller reading the answer should not have to remember it.
    name: String,
    candidates: Vec<MacroCandidate>,
}

impl MacroEnvironment {
    /// **Which `#define` is in force** at `offset`, or why that cannot be said.
    ///
    /// This is the question "go to macro definition" asks, and it is the strict one. The rules are the
    /// preprocessor's:
    ///
    /// * **only facts pasted in at or before the cursor count.** The first element of a candidate's chain is where
    ///   it enters the file the cursor is in — the fact's own offset, or the `#include` that pulled its file in —
    ///   so one comparison covers both cases: a `#define` written below the use is not in force yet, and neither is
    ///   anything from an `#include` written below it. Everything *inside* an included file counts, because the
    ///   preprocessor pastes all of it at the `#include`.
    /// * **the last one wins**, by lexicographic comparison of those chains.
    /// * **an unconditional fact beats a conditional one** even when the conditional one is later: a fact behind an
    ///   `#if` may not be there at all, so one that is certainly there settles the name — and only when nothing
    ///   certain exists does the conditional one make the answer `Unknown(ConditionalCompilation)`.
    ///
    /// [`MacroFact::settles_the_name`] is deliberately **not** consulted here: it says the name is a macro either
    /// way, not *which* `#define` did it, and in the `#ifndef NAME` shape the definition may have come from an
    /// earlier header this file cannot see. [`MacroEnvironment::is_a_macro_at`] is the question it answers.
    pub fn at(&self, offset: usize) -> Known<&MacroCandidate> {
        let in_force: Vec<&MacroCandidate> = self.in_force(offset).collect();

        let best = last(
            in_force
                .iter()
                .copied()
                .filter(|candidate| !candidate.is_conditional()),
        )
        .or_else(|| last(in_force.iter().copied()));

        let Some(best) = best else {
            return Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(
                self.name.as_str(),
            )));
        };

        if best.is_conditional() {
            return Known::Unknown(UnknownReason::ConditionalCompilation);
        }

        self.as_answer(best)
    }

    /// **Is this name a macro** at `offset` — the weaker question a find-references asks.
    ///
    /// The difference from [`MacroEnvironment::at`] is one word: a fact inside an `#if` counts here when the
    /// conditional *cannot change whether the name is a macro* afterwards, which is what
    /// [`MacroFact::settles_the_name`] records (the `#ifndef NAME / #define NAME` idiom and a region whose every
    /// branch agrees). That is the whole reason this is a second method rather than a flag on the first: a use is a
    /// use even when which `#define` is in force depends on a macro nobody has.
    ///
    /// The `#undef` case is where the two genuinely part company, so it gets its own rule: a certain `#undef` says
    /// the name is not a macro here — **unless** something that might be in force *after* it is a definition.
    pub fn is_a_macro_at(&self, offset: usize) -> Known<&MacroCandidate> {
        let in_force: Vec<&MacroCandidate> = self.in_force(offset).collect();

        let Some(best) = last(
            in_force
                .iter()
                .copied()
                .filter(|candidate| candidate.is_certain_about_the_name()),
        ) else {
            // Nothing that reaches this offset settles it. Either there is nothing at all — the name is not a
            // macro here — or everything there is depends on a condition.
            return if in_force.is_empty() {
                Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(
                    self.name.as_str(),
                )))
            } else {
                Known::Unknown(UnknownReason::ConditionalCompilation)
            };
        };

        if best.is_definition() {
            return Known::Yes(best);
        }

        // The name is certainly *not* a macro here — a `#define` re-asserted inside a conditional is not a second
        // definition, and this fact already answered the question. But a `#undef` can be overturned by a
        // conditional definition that comes later in the stream, and then the honest answer is "maybe".
        let overturned = in_force
            .iter()
            .any(|candidate| candidate.position > best.position && candidate.is_definition());

        if overturned {
            return Known::Unknown(UnknownReason::ConditionalCompilation);
        }

        Known::Unknown(UnknownReason::UndefinedHere(Box::from(self.name.as_str())))
    }

    /// The in-force candidates, in no particular order: everything pasted in at or before `offset`.
    fn in_force(&self, offset: usize) -> impl Iterator<Item = &MacroCandidate> {
        self.candidates
            .iter()
            .filter(move |candidate| candidate.position[0] <= offset)
    }

    /// The answer a settled candidate gives, whether or not its region was settled by the flag.
    fn as_answer<'a>(&self, best: &'a MacroCandidate) -> Known<&'a MacroCandidate> {
        if best.is_definition() {
            return Known::Yes(best);
        }

        Known::Unknown(UnknownReason::UndefinedHere(Box::from(self.name.as_str())))
    }

    /// Is there anything at all to say about the name in this file?
    pub fn is_empty(&self) -> bool {
        self.candidates.is_empty()
    }
}

/// The last of a run of candidates in translation order.
fn last<'a>(candidates: impl Iterator<Item = &'a MacroCandidate>) -> Option<&'a MacroCandidate> {
    candidates.max_by(|one, other| one.position.cmp(&other.position))
}

/// One fact about a macro name, and where it sits in the translation unit's stream.
#[derive(Debug, Clone)]
pub struct MacroCandidate {
    /// The chain of offsets that pastes this fact in: the top-level `#include`, each nested one, and the fact's
    /// own offset. Compared lexicographically, which is what makes it a position.
    position: Vec<usize>,
    file: PathBuf,
    fact: MacroFact,
    /// Is one of the `#include`s that pull this fact's file in written inside a conditional?
    ///
    /// Kept apart from the fact's own [`MacroFact::guard`] because the two are answered by different things: a
    /// path through a conditional `#include` means the fact's *file* may not be part of the translation unit at
    /// all, which nothing about the fact's own text can repair.
    path_conditional: bool,
    /// What the environment makes of the fact's own region — see [`MacroCandidate::is_conditional`].
    region: FactReach,
}

impl MacroCandidate {
    /// The file the fact is written in.
    pub fn file(&self) -> &Path {
        &self.file
    }

    pub fn fact(&self) -> &MacroFact {
        &self.fact
    }

    /// Is the fact a `#define` (as opposed to an `#undef`)?
    pub fn is_definition(&self) -> bool {
        self.fact.kind.is_definition()
    }

    /// Is **which `#define` is in force** conditional — the question [`MacroEnvironment::at`] answers?
    ///
    /// Yes when the path in is conditional, or when the fact is written inside an `#if` that the environment
    /// cannot decide — including the `#ifndef NAME` whose body defines the name, where the name is certainly a
    /// macro but the *definition* it has may be somebody else's. A region the environment **decides** is not
    /// conditional in this sense: `#ifdef _WIN32` on a machine whose compiler defines `_WIN32` is a fact about
    /// which `#define` is in force, not a doubt about it.
    pub fn is_conditional(&self) -> bool {
        self.path_conditional || self.region == FactReach::Unknown
    }

    /// Is **whether the name is a macro here** settled — the question [`MacroEnvironment::is_a_macro_at`] answers?
    ///
    /// The path in still has to be unconditional: a fact in a header that may not have been included at all says
    /// nothing. The fact's own region is settled when the environment decides it *is* taken, and otherwise by
    /// [`MacroFact::settles_the_name`] — which is exactly the case the two questions differ in.
    pub fn is_certain_about_the_name(&self) -> bool {
        !self.path_conditional && (self.fact.settles_the_name || self.region == FactReach::Active)
    }
}

/// A declaration found in another file, with how the file that asked reaches it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VisibleDeclaration<'a> {
    pub file: PathBuf,
    pub fact: &'a DeclFact,
    pub visibility: IncludeVisibility,
}

/// One declaration a name resolved to, **owned** so that the walk that found it can hand it back: a
/// [`VisibleDeclaration`] borrows the index, and the two queries built on this want to sort, dedup and truncate the
/// list before they answer.
struct ProjectDeclaration {
    file: PathBuf,
    fact: DeclFact,
    start_offset: usize,
}

impl ProjectDeclaration {
    fn of(found: &VisibleDeclaration<'_>) -> ProjectDeclaration {
        ProjectDeclaration {
            file: found.file.clone(),
            fact: found.fact.clone(),
            start_offset: found.fact.name_range.start_offset,
        }
    }
}

/// **What the index says a name is**, as the two facts a colour is drawn from — the answer to
/// [`ProjectIndex::kind_of`].
///
/// The pair and not a [`DeclFact`], because a highlighter asks this once per distinct spelling in a file and a
/// `DeclFact` is five owned strings deep: cloning one per spelling to read two fields off it is most of what such a
/// request would cost. See [`ProjectIndex::kind_of`] for why agreement among the candidates is the rule.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct IndexedKind {
    pub kind: DeclKind,
    /// The qualified scope the declaration was written in, or `None` at file scope.
    ///
    /// Part of the answer rather than a detail: it is what tells a **member** from a free name (`std::string::size`
    /// from `::size`), and it is also why this type is ordered — two candidates are one answer only when both
    /// fields agree.
    pub scope: Option<Box<str>>,
    /// **Is this an enumerator?** — a `Variable` fact written inside an enumeration.
    ///
    /// The index has one kind for "a name that holds a value", and an enumerator is one: `DeclKind` cannot tell it
    /// from a variable without a field, and adding a variant is a summary-format change. What it *can* tell is that
    /// an enumerator records **no type** — `enum class Color { Red };` declares `Red` with the enumeration's type
    /// implied, while every variable records the spelling it was written with — and that it always has a scope.
    ///
    /// So this is read off the fact rather than guessed: a `Variable` in a scope with no written type is an
    /// enumerator. A highlighter draws it as `enumMember` (a theme colours it with the enum's own), and a reader
    /// hovering it sees the enumerator rather than a variable that claims no type.
    pub enumerator: bool,
    /// **Is this a variable template?** — `template <class T> constexpr bool v = …;`.
    ///
    /// `DeclFact::parameters` is the template head's parameter names, recorded by
    /// `declared_template_parameters_with` when the fact was built, so a variable whose list is non-empty was written
    /// with a `template <…>` in front of it and names a *family* of values rather than one. A highlighter draws that
    /// apart from a plain variable — see `TypeKind::VariableTemplate` in the server.
    pub template: bool,
}

impl IndexedKind {
    /// The answer for one declaration.
    fn of(found: &DeclFact) -> IndexedKind {
        IndexedKind {
            kind: found.kind,
            scope: found.scope.clone().map(Box::from),
            enumerator: found.kind == DeclKind::Variable
                && found.type_of.is_none()
                && found.scope.is_some(),
            template: !found.parameters.is_empty(),
        }
    }
}

/// The answer to a cross-file definition question.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectDefinition {
    pub file: PathBuf,
    /// The declaration, cloned out of the index so that an answer does not borrow the project for as long as a
    /// consumer wants to hold it — a language server hands the location to a client and moves on.
    pub fact: DeclFact,
}

/// **Every declaration a name refers to** — the plural answer to "where is this declared".
///
/// See [`ProjectIndex::definitions`] for what the list means, why one namespace is collapsed to one entry, and
/// what the order is. This type exists because the answer is genuinely plural: an overload set is several
/// declarations, and a client that can show a list should be given all of them rather than told "ambiguous".
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectDefinitions {
    /// The declarations to answer with, in the order [`ProjectIndex::definitions`] documents. One entry for the
    /// ordinary case, several for an overload set or a name declared in more than one place.
    ///
    /// Never empty: a name nothing declares is [`UnknownReason::NotDeclaredHere`] rather than an empty list, and a
    /// name whose only declarations are behind a conditional `#include` is
    /// [`UnknownReason::ConditionalCompilation`]. An empty list would be an answer that looks like "here they are"
    /// and says nothing.
    pub found: Vec<ProjectDefinition>,
    /// How many declarations of the same name the index holds that are reachable **only** through a conditional
    /// `#include`, and are therefore not in [`ProjectDefinitions::found`]: whether they are in scope depends on
    /// macros this layer does not have.
    ///
    /// Counted rather than dropped, because "one declaration" and "one declaration and two that might also be
    /// there" are different answers, and a consumer that shows the first without the second is claiming more than
    /// this layer knows.
    pub conditional: usize,
}

impl ProjectDefinitions {
    /// An answer of one declaration — the shape the single-file layer's own resolution produces.
    pub fn one(found: ProjectDefinition) -> Self {
        ProjectDefinitions {
            found: vec![found],
            conditional: 0,
        }
    }

    /// Does this name refer to exactly one declaration?
    pub fn is_one(&self) -> bool {
        self.found.len() == 1
    }
}

/// A type's members, as [`members_of`] lists them.
///
/// # The order is part of the answer
///
/// Members come **nearest class first**: the type's own, then its direct bases', then theirs, level by level.
/// That is the order C++ hides in, so a consumer that shows the list in this order shows the members in
/// precedence order — and a member that a nearer level also declares is not in the list at all, because the
/// language does not find it by that name.
///
/// Within a level the order is by **name**, and it has to be imposed rather than inherited: the file's own scope
/// tree keeps its bindings name-sorted — see [`ScopeTree::add_binding`](crate::ScopeTree::add_binding) — while
/// the index keeps facts in offset order, so leaving each side as it came would make a list depend on whether the
/// class happened to be in the buffer or in a header. Sorting by name is the one rule both sides can obey, and it
/// is stable, so two declarations of one name keep the order they were written in.
///
/// # It is never a claim of completeness
///
/// [`MemberList::unlisted`] names the bases this walk could not open. An empty `unlisted` means "no base this walk
/// reached was left unread" — not "this is everything the compiler would see". The index holds a subset of the
/// translation unit, and the standard library is not in it.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct MemberList {
    pub members: Vec<ProjectMember>,
    /// The bases whose own members are **not** in this list, with why.
    ///
    /// Separate from `members` rather than folded into it, because the two say different things: `members` is
    /// what the type has, and this is where the answer stops. A consumer that shows a truncated list without
    /// saying so is the failure this field exists to prevent.
    pub unlisted: Vec<UnlistedBase>,
}

impl MemberList {
    /// The members declared by the type itself, as opposed to the ones it inherits.
    pub fn own(&self) -> impl Iterator<Item = &ProjectMember> {
        self.members.iter().filter(|member| member.depth == 0)
    }

    /// The members reached `depth` base steps away: `0` for the type's own, `1` for a direct base's.
    pub fn at_depth(&self, depth: usize) -> impl Iterator<Item = &ProjectMember> {
        self.members
            .iter()
            .filter(move |member| member.depth == depth)
    }
}

/// One member of a type: where it is declared, and which class in the chain declares it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectMember {
    pub file: PathBuf,
    pub fact: DeclFact,
    /// The **resolved** qualified name of the class that declares it — the type asked about, or one of its bases.
    ///
    /// The qualified name rather than the spelling the derived class wrote, because that is what makes the member
    /// a thing a second query can be asked about: `Base` in `struct D : public Base` is a spelling, and
    /// `ns::Base` is the class. The spelling is in [`DeclFact::bases`] on the derived class's own fact.
    pub declared_in: String,
    /// How many base steps away it is: `0` for the type's own members, `1` for a direct base's, and so on.
    ///
    /// Recorded rather than left to be recomputed from `members`, because a consumer grouping by it — an outline,
    /// a completion that shows inherited members separately — would otherwise have to reconstruct the walk it was
    /// just handed the result of.
    pub depth: usize,
    /// Another class **at the same level** also declares this name, so the name is not uniquely resolved here.
    ///
    /// The list keeps both declarations, because dropping either would be choosing. See [`members_of`].
    pub ambiguous: bool,
}

/// A base whose members are not in the list, and why.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnlistedBase {
    /// The base as a **name to look up**, not as the file spelled it: `Base` for `public Base<int>` — a base is
    /// found by name, and the template arguments say which type is inherited rather than which class declares the
    /// members.
    pub spelling: String,
    /// [`UnknownReason::NotDeclaredHere`] for a base nothing visible declares, and
    /// [`UnknownReason::ConditionalCompilation`] for one reachable only through a guarded `#include`.
    pub reason: UnknownReason,
}

impl ProjectDefinition {
    /// The same shape, from a binding the file's own scopes produced.
    ///
    /// [`crate::sema::resolve::definition_at`] answers with a [`Binding`], which carries a `Name` rather than a plain
    /// string and no qualified scope — so the two answers are made to look alike here, in one place, rather than
    /// at every call site.
    ///
    /// `scope` is what the *caller* knows and this does not: the qualified name a member access or a qualifier
    /// went through (`Widget` for `widget.size`, `ns` for `ns::Widget`), or `None` for a name written bare. It is
    /// passed rather than derived because deriving it here would mean re-reading the cursor, and left empty it
    /// would make `widget.size` and a free `size` indistinguishable to a consumer showing the answer.
    ///
    /// `local` is passed for the same reason, one step further out: whether the name can be reached from another
    /// file is a fact about the **scope chain** the binding was made in, and a `Binding` carries a [`crate::ScopeId`]
    /// rather than the tree that id belongs to. The caller has the tree; see [`ScopeTree::declares_a_local`].
    ///
    /// [`Binding`]: crate::Binding
    /// [`ScopeTree::declares_a_local`]: crate::ScopeTree::declares_a_local
    pub fn from_binding(
        path: &Path,
        binding: crate::Binding,
        scope: Option<String>,
        local: bool,
    ) -> Self {
        ProjectDefinition {
            file: path.to_path_buf(),
            fact: DeclFact {
                // The same bits the index fills — see `DeclModifiers`.
                modifiers: crate::DeclModifiers::default(),
                // The effects belong to the summary the index writes, and this answer is a *place to jump to*: a
                // caller that wants `frees` asks the fact, which is the same rule `in_namespace` below follows.
                frees: 0,
                reflection: None,
                name: binding
                    .name
                    .identifier_text()
                    .unwrap_or_default()
                    .to_string(),
                scope,
                local,
                // `None` for the same reason `type_of` below is: this answer is a **place to jump to**, built
                // from a binding, and the namespaces around a body are a fact about the file's text that lives in
                // its summary. See [`DeclFact::in_namespace`].
                in_namespace: None,
                kind: crate::DeclKind::from_binding_kind(binding.kind),
                // Unknown here, and harmlessly so: this answer is a **place to jump to**, never a candidate a member
                // query picks between definitions. See [`DeclFact::definition`].
                definition: false,
                // No type, no return type and no bases, because this answer is a *place to jump to* and the binding
                // it comes from carries none of them: they are facts about the file's text, and the file they
                // belong to has the summary that holds them. A consumer asking what a name *is* asks the index,
                // not this answer.
                type_of: None,
                returns: None,
                split_by_a_directive: false,
                bases: Vec::new(),
                parameters: Vec::new(),
                constraints: Vec::new(),
                // Same reason as `constraints` above: a clause is the declaration's text, and this is a place to jump to.
                requires_clause: None,
                parameter_defaults: Vec::new(),
                // Nor a pattern: this fact is a place to jump to, and the class it names is already the one the
                // caller asked about. See [`DeclFact::pattern`].
                pattern: None,
                // Nor a parameter list, for exactly that reason: this fact is a place to jump to, and the file it
                // points at has the summary that says what the declaration looks like.
                parameter_list: None,
                access: None,
                exported: false,
                range: binding.range,
                name_range: binding.name_range,
                // And no answer about diagnostics either, for the same reason `guard` has none: the binding came
                // from the buffer's own scopes, which are built from a node rather than from a tree with a
                // diagnostic list. See [`fact_from_binding`].
                clean: true,
                guard: FactGuard::Unconditional,
            },
        }
    }
}

/// Is the path to a declaration always taken, or only under conditions the index cannot evaluate?
///
/// Ordered by **how good the answer is**, which is what lets [`ProjectIndex::visible_files`] keep the best path to
/// a file rather than the first one it happens to find: `Unconditional < Conditional`, so "is the known answer no
/// worse than this one" is a comparison.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum IncludeVisibility {
    /// Every `#include` on the path is outside any `#if`, so the declaration is in scope whatever the macros are.
    Unconditional,
    /// At least one `#include` on the path is inside an `#if` this layer cannot evaluate.
    Conditional,
}

/// What a declaration query knows about the fact it is looking for, before it reads a single fact.
#[derive(Clone, Copy)]
enum Narrow<'q> {
    /// Nothing: every fact of every visible file is a candidate.
    Nothing,
    /// The fact's bare name is one of these.
    Named(&'q [&'q str]),
    /// The fact is written directly in this scope.
    Scoped(&'q str),
}

/// One workspace-symbol candidate, with everything its ordering needs.
struct Hit<'a> {
    rank: usize,
    /// Lowercased, because the order within a rank is alphabetical and case is not a difference a reader sees.
    name: String,
    /// The same, for the whole qualified name: two `Widget`s in different namespaces are ordered by where they are.
    qualified: String,
    file: &'a Path,
    posting: Posting,
    fact: &'a DeclFact,
}

/// Rank, then **name**, then qualified name, then **file** — answers that compare equal have to come back in one
/// order, and two files may declare the same name — then the position, so that even two overloads in one file do.
fn hit_order(one: &Hit<'_>, two: &Hit<'_>) -> std::cmp::Ordering {
    one.rank
        .cmp(&two.rank)
        .then_with(|| one.name.cmp(&two.name))
        .then_with(|| one.qualified.cmp(&two.qualified))
        .then_with(|| one.file.cmp(two.file))
        .then_with(|| one.posting.cmp(&two.posting))
}

fn sort_hits(hits: &mut [Hit<'_>]) {
    hits.sort_by(hit_order);
}

/// Does this declaration answer to `name`?
///
/// The qualified name first, then the bare one. Both are needed and the order matters: `ns::Widget` written in
/// the query is a claim that the reader knows where the name lives, and honouring it must not be diluted by
/// every unrelated `Widget` elsewhere in the project.
///
/// A **leading `::`** is a third spelling and not a decoration: `::Widget` asks about the global name space, so
/// only a declaration written at file scope answers it. Matching it by dropping the `::` would find `ns::Widget`
/// as well — the exact wrong answer the spelling exists to avoid — so the prefix is honoured rather than
/// stripped.
///
/// A **local** never answers, whatever it is called. See [`DeclFact::local`]: the index is a per-file list and
/// cannot say which function a local belongs to, so a name lookup here has no way to know whether the reader is
/// inside that function — and the answer it would give instead is a *wrong* one, not a missing one, because
/// thousands of locals in the standard library's headers are called `__first` and `n`. Resolving one is the
/// scope tree's job, and it is done there: [`crate::sema::resolve::definition_at`] walks the scopes of the file
/// being edited, which is the only place a local can be placed.
fn matches(fact: &DeclFact, name: &str) -> bool {
    if fact.local {
        return false;
    }

    // **A fact with no name declares no name.** `DeclFact::qualified_name` of a nameless fact *is* its scope, so
    // without this every nameless declaration answers for the class that encloses it — which is how a destructor
    // made `std::vector` ambiguous. Nothing is lost: a nameless fact is still reachable by position, which is
    // what it exists for (`fact_for` records the spelling for the rest).
    if fact.name.is_empty() {
        return false;
    }

    if let Some(global) = name.strip_prefix("::") {
        return fact.scope.is_none() && fact.name == global;
    }

    fact.qualified_name() == name || fact.name == name
}

/// The resolved include targets of a summary, as normalized path strings.
fn include_targets(summary: &FileSummary) -> Vec<String> {
    summary
        .includes
        .iter()
        .filter_map(|include| include.resolved.as_ref())
        .map(|path| normalize(path))
        .collect()
}

/// A path as the index keys on it.
fn normalize(path: &Path) -> String {
    // Case-insensitive on Windows, where two spellings of one path are one file. The rest of the crate reads the
    // same flag from the compiler configuration; here it is the platform, because the *index* has to agree with
    // the filesystem about identity and nothing else.
    normalize_path(path, cfg!(windows))
}

/// One declaration a **workspace symbol** search found — see [`ProjectIndex::symbols_matching`].
///
/// Owned rather than borrowed, unlike [`VisibleDeclaration`]: a search collects from several maps (the summaries
/// and the cooked readings) and sorts what it found, so there is nothing to borrow from by the time it answers.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectSymbol {
    pub file: PathBuf,
    pub fact: DeclFact,
}

/// How well a declaration matches a search query: lower is better, `None` is not a match.
///
/// # A bare word is about the **name**; a qualified query is about the qualified name's **tail**
///
/// That one rule is what keeps a search for `wid` from answering with every member of every matching class —
/// `ns::Widget::size` contains `wid` too, and two letters in a symbol box should not list a whole project's
/// members — while still letting `Widget::si` find that member, which is the query a user types when they *do* want
/// one.
///
/// ```text
/// `size`         exact, then prefix, then anywhere in the **name**      → finds `Widget::size` at any depth ✓
/// `Widget::si`   matched against the **last two** segments: the ones before the last must match exactly, the last
///                is a prefix → `ns::Widget::size` matches (its tail is `Widget::size`) ✓
/// `ns::widget`   …and `ns::Widget::size`'s tail is `Widget::size`, so `ns` does not match it ✗ — a class query
///                does not drag its members in. It matches `ns::Widget` itself ✓
/// ```
///
/// A leading `::` is dropped, so `::Widget` — how a reader spells "the global one" — finds what `Widget` finds. (The
/// index records a global declaration's qualified name as its bare name, and there is only one to find.)
fn rank_of(qualified: &str, name: &str, wanted: &str) -> Option<usize> {
    let wanted = wanted.trim_start_matches("::").to_lowercase();
    if wanted.is_empty() {
        return None;
    }

    let query: Vec<&str> = wanted.split("::").collect();

    if query.len() == 1 {
        let name = name.to_lowercase();

        if name == wanted {
            return Some(0);
        }
        if name.starts_with(&wanted) {
            return Some(1);
        }
        if name.contains(&wanted) {
            return Some(2);
        }

        return None;
    }

    let segments: Vec<String> = qualified
        .to_lowercase()
        .split("::")
        .map(str::to_string)
        .collect();

    // The **tail**: `Widget::si` has to be able to find `ns::Widget::size`, and it is the last segments it names.
    if segments.len() < query.len() {
        return None;
    }
    let tail = &segments[segments.len() - query.len()..];

    let (last_asked, asked) = query.split_last()?;
    let (last, rest) = tail.split_last()?;

    if rest.iter().map(String::as_str).ne(asked.iter().copied()) {
        return None;
    }

    if last == last_asked {
        return Some(0);
    }
    if last.starts_with(last_asked) {
        return Some(1);
    }

    None
}

/// **Are these two recordings the same declaration?**
///
/// The comparison is the model's own identity: every field a consumer can *read*. Two facts that agree on all of
/// them are one entity as far as any answer here is concerned — a hover would print the same type and the same
/// scope, a completion would show one entry, a jump would land where the name is declared.
///
/// # What is deliberately not compared
///
/// * `range` and `name_range` — *where* the declaration was written. Whether two recordings may be merged across
///   files is a separate question, and [`the_same_declaration_in_one_file`] answers it with "no".
/// * `clean` and `guard` — *how well* it was read and *which* `#if` it stands in. Two recordings of one declaration
///   legitimately disagree (one summary may have been built while that file had errors), and neither difference is
///   one a consumer could observe in an answer.
///
/// # What is compared, and why each
///
/// `name` and `scope` are the qualified name — the identity the index is keyed by. `local` separates a file-scope
/// name from a local one with the same spelling, which nothing outside its own body can name. `kind` separates a
/// class from a function of the same name. `type_of`, `returns`, `bases` and `parameters` are what a
/// **redeclaration** must agree about: a forward declaration and a definition differ in exactly these.
///
/// `parameter_list` is the sixth, and it was added late because the model did not have it: without it two overloads
/// of one function that share a return type — `string format(const string_view)`, `wstring format(const
/// wstring_view)`… and the four `std::format`s that *are* distinguishable only here — read as one recording of one
/// declaration. A fact that did not record it says `None` on both sides, which is the honest answer: "nothing here
/// tells them apart" is what `None == None` means, and it is why [`the_same_declaration_in_one_file`] still demands
/// the **presence** of evidence rather than its equality.
fn the_same_declaration(one: &DeclFact, other: &DeclFact) -> bool {
    one.name == other.name
        && one.scope == other.scope
        && one.local == other.local
        && one.kind == other.kind
        && one.type_of == other.type_of
        && one.returns == other.returns
        && one.bases == other.bases
        && one.parameters == other.parameters
        && one.parameter_list == other.parameter_list
}

/// Are these two candidates **one declaration recorded twice**, as far as this index can tell?
///
/// # The three conditions, and why each is there
///
/// 1. **The same file.** `int count;` in two headers is two answers, not one — the position this project pinned in
///    `two_declarations_of_one_name_are_a_list_for_a_consumer_that_shows_one`, and the language agrees: one name
///    written in two translation units is two objects or an error, and a reader asking where `count` is declared is
///    owed both places. Measured on one real file: of the candidate pairs that agree on everything readable,
///    **97 stand in the same file and 0 across files** — the duplicates are *inside* a header (MSVC's `<iostream>`
///    writes `cin` plain and again behind `_EXPORT_STD`), which is what this exists for.
/// 2. **A field that can tell two declarations apart must be _present_, not merely equal.** A variable's or an
///    alias's **type**; a function's **parameter list**. Equal-and-empty is not agreement: two overloads that share
///    a return type and whose parameters were never read would "agree" on everything, and an identity invented out
///    of silence collapses every overload set into one answer — which is what `std::getline`'s four overloads did
///    before the parameter list was recorded. A function whose parameters are unread is therefore **never** merged.
/// 3. **Everything else about them is equal** — see [`the_same_declaration`].
///
/// A class is deliberately not mergeable: this model records no member list, so two classes of one name in one file
/// are indistinguishable *and* genuinely different. What collapses a class's own redeclaration (`struct S;` then
/// `struct S { … };`) is not this rule — such a pair is one `DeclFact` here to begin with.
fn the_same_declaration_in_one_file(one: &ProjectDeclaration, other: &ProjectDeclaration) -> bool {
    if one.file != other.file || !the_same_declaration(&one.fact, &other.fact) {
        return false;
    }

    match one.fact.kind {
        // A variable, and an alias (which this model records as a `Type` with a spelling): the type tells two of
        // them apart, and an absent one is silence rather than agreement.
        DeclKind::Variable | DeclKind::Type => one.fact.type_of.is_some(),
        // A function: the parameter list, which is the field that separates overloads and the one this model reads
        // out of the declarator. `parameters` — the *template* parameter names — is not evidence about a function:
        // an ordinary function has none, so requiring it here would refuse to merge anything.
        DeclKind::Function => one.fact.parameter_list.is_some(),
        // A namespace has its own, wider rule at the call site; a macro and an anonymous construct have nothing here
        // that could tell two of them apart.
        _ => false,
    }
}

#[cfg(test)]
mod tests {
    use super::{IncludeVisibility, ProjectIndex};
    use crate::cache::SummaryKey;
    use crate::index::summarize;
    use crate::symbol::{Known, UnknownReason};
    use std::path::Path;

    /// **A member named like its class does not hide the class** — the reader's report "`LSPHandle` was read as the
    /// constructor itself rather than the class", as a test at the layer that broke it.
    ///
    /// `LSPHandle.cpp` defines `LSPHandle::LSPHandle(int)`, so **this file itself** declares the name `LSPHandle` — in
    /// the class's scope. The local-win rule then dropped every *other* file's fact with that name as "not local", and
    /// the class the header declares went with them: `definition("LSPHandle")` was `Ambiguous` between the two
    /// constructors, and `LSPHandle::RefreshDiagnostic` resolved its qualifier to a constructor. A candidate in a
    /// different scope is a different entity, which is what the rule says now — and removing that clause makes this
    /// test fail at the assertion below.
    #[test]
    fn a_member_named_like_its_class_does_not_hide_the_class() {
        let index = index(&[
            (
                "/p/LSPHandle.h",
                "class LSPHandle {\npublic:\n    LSPHandle(int server);\n    void RefreshDiagnostic();\n};\n",
            ),
            (
                "/p/LSPHandle.cpp",
                "#include \"LSPHandle.h\"\nLSPHandle::LSPHandle(int server) {\n}\n",
            ),
        ]);

        let found = index.definition("LSPHandle", Path::new("/p/LSPHandle.cpp"));
        let Known::Yes(definition) = found else {
            panic!("the class must resolve, not fall to its constructor: {found:?}");
        };
        assert_eq!(
            definition.fact.kind,
            crate::DeclKind::Type,
            "the name `LSPHandle` resolved to {:?} in {}",
            definition.fact.kind,
            definition.file.display()
        );
    }

    fn index(files: &[(&str, &str)]) -> ProjectIndex {
        let mut index = ProjectIndex::new();

        for (path, source) in files {
            // The includes are resolved by hand here rather than through a `FileProvider`, because what these
            // tests are about is the graph that results — not the search that produced it.
            let mut summary = summarize(Path::new(path), source, SummaryKey::new(0, 0));
            for include in &mut summary.includes {
                include.resolved =
                    Some(std::path::PathBuf::from(format!("/p/{}", include.spelling)));
            }
            index.insert(summary);
        }

        index
    }

    #[test]
    fn a_declaration_in_an_included_header_is_found() {
        let index = index(&[
            ("/p/widget.h", "struct Widget { int size; };\n"),
            (
                "/p/main.cpp",
                "#include \"widget.h\"\nvoid f() { Widget w; }\n",
            ),
        ]);

        let found = index.definition("Widget", Path::new("/p/main.cpp"));
        let Known::Yes(definition) = found else {
            panic!("the class in the included header must be found: {found:?}");
        };

        assert_eq!(definition.file, Path::new("/p/widget.h"));
        assert_eq!(definition.fact.name, "Widget");
    }

    /// **A name only a compiler can see is a name the index answers for — once the file is cooked.**
    ///
    /// `DECLARE_HANDLE(HWND)` declares `HWND__` and `HWND` to a compiler and nothing to a reader of the file's
    /// own text, because the declaration is inside the macro's replacement list. So the raw index cannot find
    /// either name, and the cooked reading — indexed and mapped back by `FileIndexer::index_rendering` — can.
    /// This is the whole reason the index holds a second reading.
    #[test]
    fn a_declaration_a_macro_makes_is_found_once_the_file_is_cooked() {
        let files = [
            (
                "/p/decl.h",
                "#define DECLARE_HANDLE(name) struct name##__ { int unused; }; \
                 typedef struct name##__ *name\n",
            ),
            ("/p/api.h", "#include \"decl.h\"\nDECLARE_HANDLE(HWND);\n"),
        ];

        let mut index = ProjectIndex::new();
        let mut definitions = crate::MacroDefinitions::default();
        for (path, source) in files {
            let mut summary = summarize(Path::new(path), source, SummaryKey::new(0, 0));
            for include in &mut summary.includes {
                include.resolved =
                    Some(std::path::PathBuf::from(format!("/p/{}", include.spelling)));
            }
            let _ = source;
            index.insert(summary);
        }

        let api = Path::new("/p/api.h");
        let source = files[1].1;
        let before = index.definition("HWND__", api);
        assert!(
            matches!(before, Known::Unknown(_)),
            "the raw reading cannot see a declaration inside a macro body: {before:?}"
        );

        // Cook the file **through a unit** — its environment is what makes the macro expand — and hand the index
        // what came out of it.
        let text_of = |wanted: &Path| {
            files
                .iter()
                .find(|(path, _)| Path::new(path) == wanted)
                .map(|(_, source)| *source)
                .unwrap_or("")
        };
        let unit = crate::TranslationUnit::walk(
            index.summary(api).expect("indexed"),
            |wanted| {
                index
                    .summary(wanted)
                    .map(|summary| (summary, text_of(wanted)))
            },
            &crate::Marked::default(),
            &mut definitions,
            false,
            &crate::WalkCache::new(),
        );
        let (tokens, _) = cpp_parser::lex(source, &cpp_parser::LexerConfig::default());
        let unit_definitions = unit.definitions();
        let macros = crate::preprocess::cooked::FileMacros::new(
            unit.environment_of(api).expect("the unit reaches api.h"),
            &unit_definitions,
            None,
            true,
        );
        let rendered = crate::preprocess::cooked::cook_with(source, &tokens, &macros).render();

        let provider = crate::MemoryFiles::new();
        let config = crate::CompilerConfig::default();
        let indexer = crate::FileIndexer::new(&provider, &config);
        let indexed = indexer.index_rendering(api, &rendered, SummaryKey::new(0, 0));
        assert_eq!(indexed.mapped.dropped, 0, "every range landed in the file");
        index.insert_cooked(api, indexed.into());

        // Now it can: the struct the macro declared, and the typedef beside it.
        let after = index.definition("HWND__", api);
        let Known::Yes(definition) = after else {
            panic!("the cooked reading declares it: {after:?}");
        };
        assert_eq!(definition.file, api);
        let written =
            &source[definition.fact.range.start_offset..definition.fact.range.end_offset()];
        assert!(
            written.contains("DECLARE_HANDLE"),
            "the declaration is reported at the invocation: {written:?}"
        );
        assert!(
            matches!(index.definition("HWND", api), Known::Yes(_)),
            "and the typedef with it: {:?}",
            index.definition("HWND", api)
        );
    }

    /// **The two readings do not double-count**: an ordinary declaration is in both, and a candidate list that
    /// held it twice would answer `Ambiguous` for every name in the project.
    #[test]
    fn a_declaration_both_readings_found_is_one_candidate() {
        let source = "struct Plain { int size; };\n";
        let mut index = index(&[("/p/a.h", source)]);

        let (tokens, _) = cpp_parser::lex(source, &cpp_parser::LexerConfig::default());
        let rendered = crate::preprocess::cooked::cook(source, &tokens).render();
        let provider = crate::MemoryFiles::new();
        let config = crate::CompilerConfig::default();
        let indexer = crate::FileIndexer::new(&provider, &config);
        let indexed =
            indexer.index_rendering(Path::new("/p/a.h"), &rendered, SummaryKey::new(0, 0));
        assert_eq!(indexed.mapped.dropped, 0);
        index.insert_cooked(Path::new("/p/a.h"), indexed.into());

        let found = index.definition("Plain", Path::new("/p/a.h"));
        assert!(matches!(found, Known::Yes(_)), "one candidate: {found:?}");
    }

    /// A cooked reading of `source`, as [`crate::Session::cook`] builds one: the rendering indexed and mapped back.
    fn cooked_reading_of(path: &str, source: &str) -> crate::CookedFile {
        let (tokens, _) = cpp_parser::lex(source, &cpp_parser::LexerConfig::default());
        let rendered = crate::preprocess::cooked::cook(source, &tokens).render();
        let provider = crate::MemoryFiles::new();
        let config = crate::CompilerConfig::default();
        let indexer = crate::FileIndexer::new(&provider, &config);
        indexer
            .index_rendering(Path::new(path), &rendered, SummaryKey::new(0, 0))
            .into()
    }

    /// **A workspace search finds declarations in files nobody has opened**, ranks them, and leaves locals out.
    ///
    /// The query is project-wide and deliberately *not* visibility-scoped: a symbol search is about the project, so
    /// a class in a header nothing includes is still a symbol. What it does share with every other declaration query
    /// is the two readings — a name only the cooked reading declares is a name a compiler knows.
    #[test]
    fn a_workspace_search_finds_symbols_across_the_project() {
        let mut index = index(&[
            (
                "/p/widget.h",
                "namespace ns {\nstruct Widget { int size; };\n}\n",
            ),
            (
                "/p/other.cpp",
                "void f() {\n    int widget_local;\n}\nstruct Widest { int y; };\n",
            ),
            (
                "/p/handle.h",
                "#define DECLARE_HANDLE(name) struct name##__ { int unused; };\nDECLARE_HANDLE(HWND);\n",
            ),
        ]);

        let names = |found: &[super::ProjectSymbol]| -> Vec<String> {
            found
                .iter()
                .map(|symbol| symbol.fact.name.clone())
                .collect()
        };

        // Case-insensitive; both names begin with the query, so they share a rank and are ordered by name.
        let found = index.symbols_matching("wid", 100);
        assert_eq!(
            names(&found),
            vec!["Widest", "Widget"],
            "one rank, alphabetical by name: {found:?}"
        );
        assert_eq!(
            found[1].fact.scope.as_deref(),
            Some("ns"),
            "and the fact says which scope it was written in: {found:?}"
        );

        // The rank comes before the name: the exact match is first although `Widest` sorts earlier than `Widget`.
        let found = index.symbols_matching("widget", 100);
        assert_eq!(names(&found), vec!["Widget"], "{found:?}");
        let found = index.symbols_matching("idg", 100);
        assert_eq!(
            names(&found),
            vec!["Widget"],
            "a substring finds the name it is inside: {found:?}"
        );

        // A local is not a project symbol, even though its name matches.
        assert_eq!(
            names(&index.symbols_matching("widget_local", 100)),
            Vec::<String>::new(),
            "a variable inside a body is not something the project has"
        );

        // A qualified query finds it too — and finds a **member**, which is the one query that should.
        assert_eq!(
            names(&index.symbols_matching("ns::widget", 100)),
            vec!["Widget"]
        );
        assert_eq!(
            names(&index.symbols_matching("Widget::si", 100)),
            vec!["size"],
            "a query with `::` is about a qualified name"
        );
        assert_eq!(index.symbols_matching("wid", 1).len(), 1);

        // **A name only the cooked reading declares is a symbol**: a compiler sees `HWND__`, so a search finds it.
        // The file has to be in the index for the reading to be reachable at all — `insert_cooked` files a *second*
        // reading of a file the index knows.
        index.insert_cooked(
            Path::new("/p/handle.h"),
            cooked_reading_of(
                "/p/handle.h",
                "#define DECLARE_HANDLE(name) struct name##__ { int unused; };\nDECLARE_HANDLE(HWND);",
            ),
        );
        assert!(
            names(&index.symbols_matching("HWND__", 100)).contains(&"HWND__".to_string()),
            "the macro-declared type is a symbol a compiler knows"
        );
    }

    /// **Re-indexing a file with *different* text takes its cooked reading with it.**
    ///
    /// The ordinary invalidation drops both together ([`ProjectIndex::forget`] — an edit, a close, a watched file all
    /// go through it), and this is the path with no `forget` in it: the file was read again and the bytes differ, so
    /// its own declarations are replaced by that insert. A cooked reading left over from the old text would go on
    /// answering for words nobody wrote any more, at offsets into them — a wrong answer rather than a missing one.
    ///
    /// The second half is the guard that keeps this from being a cache defeat: the *same* text re-read (a cache hit,
    /// a re-index of an unchanged file) is not a change, and the reading stays.
    #[test]
    fn re_indexing_different_text_takes_the_cooked_reading_with_it() {
        let source = "struct Plain { int size; };\n";
        let mut index = index(&[("/p/a.h", source)]);
        index.insert_cooked(Path::new("/p/a.h"), cooked_reading_of("/p/a.h", source));
        assert!(index.cooked_declarations(Path::new("/p/a.h")).is_some());

        // The same text, read again: the content hash matches, so the reading describes what is still there.
        let same = summarize(Path::new("/p/a.h"), source, SummaryKey::new(0, 0));
        index.insert(same);
        assert!(
            index.cooked_declarations(Path::new("/p/a.h")).is_some(),
            "an unchanged file keeps its reading"
        );

        // Different text: the reading described the old bytes, so it goes.
        let changed = summarize(
            Path::new("/p/a.h"),
            "struct Other { int size; };\n",
            SummaryKey::new(0, 0),
        );
        index.insert(changed);
        assert!(
            index.cooked_reading(Path::new("/p/a.h")).is_none(),
            "the reading goes with the text it was built from"
        );
    }

    #[test]
    fn a_declaration_in_a_header_the_file_does_not_include_is_not_found() {
        // The distinction the whole visibility walk exists for: `Widget` is in the project, and not in scope
        // here. Answering `Yes` would be a jump to a declaration the file cannot compile against.
        let index = index(&[
            ("/p/widget.h", "struct Widget { int size; };\n"),
            ("/p/other.cpp", "void g() { }\n"),
        ]);

        let found = index.definition("Widget", Path::new("/p/other.cpp"));

        assert!(
            matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
            "a name that is not in scope is not a definition: {found:?}"
        );
    }

    #[test]
    fn visibility_follows_a_chain_of_includes() {
        let index = index(&[
            ("/p/deep.h", "struct Deep { int x; };\n"),
            ("/p/middle.h", "#include \"deep.h\"\n"),
            (
                "/p/main.cpp",
                "#include \"middle.h\"\nvoid f() { Deep d; }\n",
            ),
        ]);

        let found = index.definition("Deep", Path::new("/p/main.cpp"));
        let Known::Yes(definition) = found else {
            panic!("a transitively included declaration is visible: {found:?}");
        };
        assert_eq!(definition.file, Path::new("/p/deep.h"));
    }

    #[test]
    fn the_files_own_declaration_wins_over_an_included_one() {
        // C++ resolves to the declaration in the file being compiled, and a jump that went into a header instead
        // would be to a different entity.
        let index = index(&[
            ("/p/widget.h", "struct Widget { int from_header; };\n"),
            (
                "/p/main.cpp",
                "#include \"widget.h\"\nstruct Widget { int from_this_file; };\n",
            ),
        ]);

        let found = index.definition("Widget", Path::new("/p/main.cpp"));
        let Known::Yes(definition) = found else {
            panic!("the local declaration wins: {found:?}");
        };
        assert_eq!(definition.file, Path::new("/p/main.cpp"));
    }

    #[test]
    fn a_name_declared_in_two_visible_headers_is_ambiguous_rather_than_guessed() {
        let index = index(&[
            ("/p/one.h", "int count;\n"),
            ("/p/two.h", "int count;\n"),
            (
                "/p/main.cpp",
                "#include \"one.h\"\n#include \"two.h\"\nvoid f() { count = 1; }\n",
            ),
        ]);

        let found = index.definition("count", Path::new("/p/main.cpp"));

        assert!(
            matches!(found, Known::Unknown(UnknownReason::Ambiguous(_))),
            "two declarations and nothing to choose between them: {found:?}"
        );
    }

    #[test]
    fn two_declarations_of_one_name_are_a_list_for_a_consumer_that_shows_one() {
        // The fixture above, through the plural query: `Ambiguous` is the honest answer to "which one", and a
        // client that can show a peek list never has to be told it — both of these are real answers.
        let index = index(&[
            ("/p/one.h", "int count;\n"),
            ("/p/two.h", "int count;\n"),
            (
                "/p/main.cpp",
                "#include \"one.h\"\n#include \"two.h\"\nvoid f() { count = 1; }\n",
            ),
        ]);

        let Known::Yes(found) = index.definitions("count", Path::new("/p/main.cpp")) else {
            panic!("two declarations, both of them answers");
        };

        assert_eq!(found.found.len(), 2);
        assert_eq!(found.conditional, 0);
        assert_eq!(
            found.found[0].file,
            Path::new("/p/one.h"),
            "the order is imposed (by file, then offset), so a client's peek list cannot reorder itself between \
             two identical requests"
        );
        assert_eq!(found.found[1].file, Path::new("/p/two.h"));
    }

    /// **A bare name does not reach into a class** — the scope half of the key a name lookup needs.
    ///
    /// Reported from an editor: ctrl-click on `printf` in a `.cpp` that includes a header declaring
    /// `struct Name { void printf(int); };` and `void Name::printf(int i)` offered a peek list of **three** — the
    /// member's declaration, its out-of-class definition, and the global `printf` from the C library. The first two
    /// are a function the `.cpp` cannot name without a `Name::` or an object, so following them lands on a
    /// declaration that does not describe the call.
    ///
    /// The two directions are what make this a rule rather than a filter: the member's own definition still
    /// answers its member (the cursor writes `Name::printf`), and the **unfiltered** query still holds all three —
    /// that is the list a member access with an unknown object type asks for.
    #[test]
    fn a_bare_name_does_not_reach_a_class_member() {
        let index = index(&[
            (
                "/p/name.h",
                "struct Name {\n    void printf(int i);\n};\nvoid Name::printf(int i) { }\n",
            ),
            ("/p/stdio.h", "void printf(const char* format, ...);\n"),
            (
                "/p/main.cpp",
                "#include \"name.h\"\n#include \"stdio.h\"\nvoid f() { printf(\"x\"); }\n",
            ),
        ]);

        let found = index.definitions_in_scope("printf", Path::new("/p/main.cpp"));
        let Known::Yes(found) = found else {
            panic!("the file can name the global `printf`: {found:?}");
        };
        assert_eq!(
            found.found.len(),
            1,
            "one declaration, the only one an unqualified `printf` can denote: {:?}",
            found
                .found
                .iter()
                .map(|definition| definition.file.display().to_string())
                .collect::<Vec<_>>()
        );
        assert_eq!(found.found[0].file, Path::new("/p/stdio.h"));

        // **The unfiltered list is what a member fallback wants**, and the member is in it.
        //
        // **Two, not three.** The declaration and its out-of-class definition are *one declaration recorded twice*
        // by this index's own rule (`the_same_declaration_in_one_file`: the same file, the same name and scope, and
        // the parameter list that tells two functions apart, all present and equal). They became mergeable when the
        // grammar learned the shape — before that the definition had no name of its own, so nothing about it could be
        // compared with the declaration's. What this assertion is *for* is the fallback, and that still sees
        // `Name::printf`.
        let Known::Yes(every) = index.definitions("printf", Path::new("/p/main.cpp")) else {
            panic!("the index holds the spelling");
        };
        assert_eq!(
            every.found.len(),
            2,
            "a member access whose object's type is unknown still asks this one"
        );

        // **A qualified spelling keeps the member**, which is how one is named from outside the class — and it is
        // now *one* answer for the reason above; the survivor is the declaration, which is earlier in the file.
        let Known::Yes(qualified) =
            index.definitions_in_scope("Name::printf", Path::new("/p/main.cpp"))
        else {
            panic!("a qualified name is a member's own question");
        };
        assert_eq!(
            qualified.found.len(),
            1,
            "the member, addressed through its qualifier: {qualified:?}"
        );
    }

    #[test]
    fn an_overload_set_is_a_list_and_a_namespace_is_one_entity() {
        // The two shapes the measurement on a real file produced — 46 identifiers answered `Ambiguous` there, and
        // the lists behind them were 2, 3, 4 … 17 declarations. `find` in `std::basic_string` is seventeen of them,
        // every one an answer; `std` is **58**, all of them the *same* namespace, which the language reopens
        // rather than redeclares. So the list is not simply "what the index found".
        let index = index(&[
            (
                "/p/lib.h",
                "namespace ns {\n  void f(int);\n  void f(double);\n}\n",
            ),
            ("/p/other.h", "namespace ns {\n  void f(char);\n}\n"),
            (
                "/p/main.cpp",
                "#include \"lib.h\"\n#include \"other.h\"\nvoid h() { ns::f(1); }\n",
            ),
        ]);

        let Known::Yes(found) = index.definitions("ns::f", Path::new("/p/main.cpp")) else {
            panic!("an overload set is three declarations, not an ambiguity");
        };
        assert_eq!(found.found.len(), 3);

        let Known::Yes(found) = index.definitions("ns", Path::new("/p/main.cpp")) else {
            panic!("the namespace is declared in both headers");
        };
        assert_eq!(
            found.found.len(),
            1,
            "one namespace, however many files reopen it: a peek list of fifty-eight entries answers a question \
             nobody asked"
        );
    }

    #[test]
    fn one_function_declared_twice_is_one_entity_and_an_overload_is_two() {
        // The rule that needed a parameter list to exist at all. `the_same_declaration_in_one_file` demands
        // **evidence** that can tell two declarations apart before it merges them, and for a function that evidence
        // is the parameter list — which the model did not record. So the gate `!parameters.is_empty()` was asking
        // about the *template* parameter names, which an ordinary function never has: **no function was ever
        // merged**, and the two halves of MSVC's `<iostream>` idiom (`void f(int);` written plain and again behind
        // `_EXPORT_STD`) stayed two answers where one is the truth.
        //
        // Both directions in one fixture, because a rule that merged everything would pass the first half alone:
        // the same declaration twice is one entity, and `(double)` beside `(int)` is a second one.
        let index = index(&[(
            "/p/lib.h",
            "namespace ns {\n  void f(int);\n  void f(int);\n  void f(double);\n}\n",
        )]);

        let Known::Yes(found) = index.definitions("ns::f", Path::new("/p/lib.h")) else {
            panic!("three declarations of `ns::f`, and two entities among them");
        };

        assert_eq!(
            found.found.len(),
            2,
            "the twice-declared `(int)` is one entity; `(double)` is an overload: {found:?}"
        );
    }

    /// **The two visibility walks are the same answer**, which is the only thing the cheaper one had to prove.
    ///
    /// The walk that carries macro state replaced one that asked `environment::visibility_at` per guarded edge, and
    /// the replacement is worth two orders of magnitude on a standard-library closure (114 closure walks → one
    /// traversal; 1428 ms → 18 ms of a query measured on the latency fixture). What it must not be is a *different*
    /// answer: the visibility set is what a completion list is built from, so a set that lost a file is a missing
    /// name rather than a faster query.
    ///
    /// Four shapes, because they are the four ways the two can disagree — an unguarded edge, a guarded one nobody
    /// can decide, one that is decided and false, and a file reached twice by routes of different visibility.
    #[test]
    fn the_walk_that_carries_the_state_sees_what_asking_each_condition_saw() {
        let index = index(&[
            ("/p/one.h", "#define ONE 1\n"),
            ("/p/two.h", "int count;\n"),
            ("/p/three.h", "int three;\n"),
            (
                "/p/main.cpp",
                "#include \"one.h\"\n#ifdef FEATURE\n#include \"two.h\"\n#endif\n#include \"three.h\"\n",
            ),
            // …and a second route to `two.h`, unguarded, which is the case the crossing has to record rather than
            // the entry: `visited` enters a file once, so the guarded route is the one that descends.
            ("/p/four.h", "#include \"two.h\"\n"),
            ("/p/other.cpp", "#include \"four.h\"\n"),
        ]);

        for root in ["/p/main.cpp", "/p/other.cpp"] {
            let walked = index.visible_files(Path::new(root));
            let asked = index.visible_files_by_asking_each_condition(Path::new(root));

            let mut walked = walked.clone();
            let mut asked = asked.clone();
            walked.sort_by(|left, right| left.0.cmp(&right.0));
            asked.sort_by(|left, right| left.0.cmp(&right.0));

            assert_eq!(
                walked, asked,
                "the two walks disagree about {root}: the completion list is built from this set"
            );
        }
    }

    #[test]
    fn a_declaration_behind_a_conditional_include_is_counted_not_offered() {
        // Whether a name reached through an `#if` is in scope depends on macros this layer does not have, so it is
        // not offered as a jump target — and it is not dropped either: "one declaration" and "one declaration and
        // one that might also be there" are different answers.
        let index = index(&[
            ("/p/one.h", "int count;\n"),
            ("/p/two.h", "int count;\n"),
            (
                "/p/main.cpp",
                "#include \"one.h\"\n#ifdef FEATURE\n#include \"two.h\"\n#endif\nvoid f() { count = 1; }\n",
            ),
        ]);

        let Known::Yes(found) = index.definitions("count", Path::new("/p/main.cpp")) else {
            panic!("the unguarded header declares it");
        };

        assert_eq!(found.found.len(), 1);
        assert_eq!(found.found[0].file, Path::new("/p/one.h"));
        assert_eq!(
            found.conditional, 1,
            "and the one that might also be there is counted, so the answer does not claim there is nothing else"
        );
    }

    #[test]
    fn an_include_inside_a_condition_that_is_decided_and_false_is_not_visible() {
        // The rule that turned a 14351-item completion list into a 692-item one. MSVC's `<intrin.h>` includes
        // `<arm_neon.h>`/`<arm64_neon.h>` under `#if defined(_M_ARM64)`, and `<immintrin.h>` pulls in
        // `zmmintrin.h` for AVX-512 — all of them **decided, and false**, for a file compiled for x64. While an
        // `Inactive` edge was downgraded to `Conditional` instead of dropped, every ARM and AVX-512 intrinsic was
        // "visible" from a hello-world file, and therefore offered to the user: 8 of every 10 completion items.
        //
        // `#if 0` is the same shape with nothing to evaluate: decided, false, and no macro knowledge needed.
        let index = index(&[
            ("/p/arm.h", "int arm_intrinsic;\n"),
            (
                "/p/main.cpp",
                "#if 0\n#include \"arm.h\"\n#endif\nvoid f() { }\n",
            ),
        ]);

        let found = index.definition("arm_intrinsic", Path::new("/p/main.cpp"));
        assert!(
            matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
            "the branch was not taken, so the file is not in this translation unit at all: {found:?}"
        );
    }

    #[test]
    fn a_qualified_name_prefers_the_declaration_that_matches_it() {
        let index = index(&[
            ("/p/a.h", "namespace a {\n  struct Widget { int x; };\n}\n"),
            ("/p/b.h", "namespace b {\n  struct Widget { int y; };\n}\n"),
            (
                "/p/main.cpp",
                "#include \"a.h\"\n#include \"b.h\"\nvoid f() { a::Widget w; }\n",
            ),
        ]);

        let found = index.definition("a::Widget", Path::new("/p/main.cpp"));
        let Known::Yes(definition) = found else {
            panic!("the qualified name must select one of them: {found:?}");
        };

        assert_eq!(definition.file, Path::new("/p/a.h"));
        assert_eq!(definition.fact.qualified_name(), "a::Widget");
    }

    #[test]
    fn a_guarded_include_makes_the_answer_unknown() {
        // `#include` inside an `#if`: whether it is taken depends on macros the index does not have, so the
        // honest answer is that the name may or may not be in scope.
        let index = index(&[
            ("/p/widget.h", "struct Widget { int size; };\n"),
            (
                "/p/main.cpp",
                "#if defined(USE_WIDGET)\n#include \"widget.h\"\n#endif\nvoid f() { Widget w; }\n",
            ),
        ]);

        let found = index.definition("Widget", Path::new("/p/main.cpp"));

        assert!(
            matches!(found, Known::Unknown(UnknownReason::ConditionalCompilation)),
            "a conditional include cannot be decided here: {found:?}"
        );
    }

    #[test]
    fn an_unconditional_include_beats_a_guarded_one() {
        // The same name reachable two ways: the unguarded path is always there, so it is the answer.
        let index = index(&[
            ("/p/real.h", "struct Widget { int size; };\n"),
            (
                "/p/main.cpp",
                "#include \"real.h\"\n#if defined(X)\n#include \"other.h\"\n#endif\nvoid f() { Widget w; }\n",
            ),
            ("/p/other.h", "struct Widget { int other; };\n"),
        ]);

        let found = index.definition("Widget", Path::new("/p/main.cpp"));
        let Known::Yes(definition) = found else {
            panic!("the unconditional path wins: {found:?}");
        };
        assert_eq!(definition.file, Path::new("/p/real.h"));
    }

    #[test]
    fn a_file_that_includes_nothing_sees_only_itself() {
        let index = index(&[("/p/a.cpp", "int count;\n"), ("/p/b.cpp", "int count;\n")]);

        for path in ["/p/a.cpp", "/p/b.cpp"] {
            let found = index.definition("count", Path::new(path));
            let Known::Yes(definition) = found else {
                panic!("{path} must find its own count: {found:?}");
            };
            assert_eq!(definition.file, Path::new(path));
        }
    }

    #[test]
    fn a_cycle_of_includes_does_not_hang_the_visibility_walk() {
        let index = index(&[
            ("/p/a.h", "#include \"b.h\"\nstruct A { int x; };\n"),
            ("/p/b.h", "#include \"a.h\"\nstruct B { int y; };\n"),
            ("/p/main.cpp", "#include \"a.h\"\nvoid f() { B b; }\n"),
        ]);

        let found = index.definition("B", Path::new("/p/main.cpp"));
        let Known::Yes(definition) = found else {
            panic!("a cycle must not stop a name being found: {found:?}");
        };
        assert_eq!(definition.file, Path::new("/p/b.h"));
    }

    #[test]
    fn the_reverse_edges_are_derived_from_the_summaries() {
        let index = index(&[
            ("/p/header.h", "int x;\n"),
            ("/p/one.cpp", "#include \"header.h\"\n"),
            ("/p/two.cpp", "#include \"header.h\"\n"),
        ]);

        let mut includers = index.includers_of(Path::new("/p/header.h"));
        includers.sort();
        assert_eq!(
            includers,
            [Path::new("/p/one.cpp"), Path::new("/p/two.cpp")],
            "an edit to the header invalidates exactly these"
        );
    }

    #[test]
    fn reindexing_a_file_removes_the_edges_its_old_text_had() {
        // An edge that outlived the `#include` that wrote it would keep a header reachable from a file that no
        // longer includes it — a stale conclusion with nothing on disk to contradict it.
        let mut index = index(&[
            ("/p/widget.h", "struct Widget { int size; };\n"),
            (
                "/p/main.cpp",
                "#include \"widget.h\"\nvoid f() { Widget w; }\n",
            ),
        ]);

        assert!(index.includers_of(Path::new("/p/widget.h")).len() == 1);

        let mut edited = summarize(
            Path::new("/p/main.cpp"),
            "void f() { }\n",
            SummaryKey::new(1, 0),
        );
        for include in &mut edited.includes {
            include.resolved = Some(std::path::PathBuf::from(format!("/p/{}", include.spelling)));
        }
        index.insert(edited);

        assert!(
            index.includers_of(Path::new("/p/widget.h")).is_empty(),
            "the edge must go with the line that wrote it"
        );
        assert!(
            matches!(
                index.definition("Widget", Path::new("/p/main.cpp")),
                Known::Unknown(_)
            ),
            "and the name is no longer visible there"
        );
    }

    #[test]
    fn visibility_is_reported_so_a_caller_can_downgrade() {
        let index = index(&[
            ("/p/widget.h", "struct Widget { int size; };\n"),
            ("/p/main.cpp", "#include \"widget.h\"\n"),
        ]);

        let found = index.files_declaring("Widget", Path::new("/p/main.cpp"));
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].visibility, IncludeVisibility::Unconditional);
    }

    /// The offset of the last `needle`, which is the cursor position in these fixtures.
    fn at(source: &str, needle: &str) -> usize {
        source
            .rfind(needle)
            .unwrap_or_else(|| panic!("{needle:?} is not in {source:?}"))
    }

    /// An index over the fixtures **plus** the analysed querying file, which is what
    /// [`super::definition_across_files`] needs: the index holds the other files, and the scope tree holds this
    /// one.
    fn analysed(
        files: &[(&str, &str)],
        from: &str,
        source: &str,
    ) -> (ProjectIndex, cpp_parser::CppSyntaxTree) {
        let (index, tree) = analysed_while_typing(files, from, source);

        assert!(
            tree.get_errors().is_empty(),
            "the fixture must parse cleanly: {source:?}"
        );

        (index, tree)
    }

    /// The same, for a file that is **being typed** and therefore need not parse cleanly.
    ///
    /// Separate from [`analysed`] rather than a flag on it, because the two assertions mean different things: a
    /// shape assertion is worthless if the tree it reads came from a file with errors, while an incomplete file is
    /// the *state the completion query exists for* — `w.` is not a program, it is a question. What is deliberately
    /// **not** relaxed is that the querying file is indexed: the index and the tree have to describe the same text
    /// or the offsets in the answer mean something else.
    fn analysed_while_typing(
        files: &[(&str, &str)],
        from: &str,
        source: &str,
    ) -> (ProjectIndex, cpp_parser::CppSyntaxTree) {
        let mut index = index(files);

        let tree = cpp_parser::CppParser::parse(source, cpp_parser::ParserConfig::default());

        let mut summary = summarize(Path::new(from), source, SummaryKey::new(0, 0));
        for include in &mut summary.includes {
            include.resolved = Some(std::path::PathBuf::from(format!("/p/{}", include.spelling)));
        }
        index.insert(summary);

        (index, tree)
    }

    #[test]
    fn a_local_declaration_is_answered_without_looking_in_the_index() {
        // The first step of the resolution order, and the one that has to win: a local shadows a header's
        // declaration, so a jump that went into the header would be to a different entity.
        let source = "#include \"widget.h\"\nvoid f() {\n  int count = 0;\n  count = 1;\n}\n";
        let (index, tree) = analysed(&[("/p/widget.h", "int count;\n")], "/p/main.cpp", source);

        let root = tree.get_red_root();
        let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
        let found = super::definition_across_files(
            &index,
            &mut |_: &Path| None,
            &scopes,
            &root,
            Path::new("/p/main.cpp"),
            at(source, "count = 1;"),
        );

        let Known::Yes(definition) = found else {
            panic!("the local must win: {found:?}");
        };
        assert_eq!(definition.file, Path::new("/p/main.cpp"));
        assert!(
            definition.fact.range.start_offset > at(source, "void f"),
            "the jump goes to the local, not to the header"
        );
    }

    #[test]
    fn another_files_local_is_never_the_answer() {
        // The wrong answer this exists to prevent, and it is the *common* one rather than a corner: a header's
        // function bodies declare thousands of names (`__first`, `__n`, `_Tp`), and every one of them is a
        // declaration in the index with no scope to place it in. A lookup that matched one would answer with a
        // name the reader cannot see — and, worse, a name that is not the entity the cursor is asking about.
        let source = "#include \"widget.h\"\nvoid f() {\n  helper();\n}\n";
        let (index, tree) = analysed(
            &[(
                "/p/widget.h",
                "void g() {\n  int helper = 0;\n}\nstruct Widget { int size; };\n",
            )],
            "/p/main.cpp",
            source,
        );

        // The fact itself, so that a failure says which half broke: the header's declaration is marked local.
        let header = index.summary(Path::new("/p/widget.h")).expect("indexed");
        let helper = header
            .declarations
            .iter()
            .find(|fact| fact.name == "helper")
            .expect("the header declares `helper`");
        assert!(helper.local, "declared inside `g`'s body");
        assert_eq!(helper.scope, None, "…which is why the scope cannot say so");

        let root = tree.get_red_root();
        let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
        let found = super::definition_across_files(
            &index,
            &mut |_: &Path| None,
            &scopes,
            &root,
            Path::new("/p/main.cpp"),
            at(source, "helper();"),
        );

        assert!(
            matches!(
                found,
                Known::Unknown(UnknownReason::NotDeclaredHere(_)) | Known::No
            ),
            "the header's local is not a declaration of the name this file writes: {found:?}"
        );

        // And the other half, so that the skip is a filter rather than a hole: a *file-scope* declaration in the
        // same header is still found through the index.
        let source = "#include \"widget.h\"\nvoid f() {\n  Widget w;\n}\n";
        let (index, tree) = analysed(
            &[(
                "/p/widget.h",
                "void g() {\n  int helper = 0;\n}\nstruct Widget { int size; };\n",
            )],
            "/p/main.cpp",
            source,
        );

        let root = tree.get_red_root();
        let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
        let found = super::definition_across_files(
            &index,
            &mut |_: &Path| None,
            &scopes,
            &root,
            Path::new("/p/main.cpp"),
            at(source, "Widget w;"),
        );

        let Known::Yes(definition) = found else {
            panic!("`Widget` is at file scope in the header: {found:?}");
        };
        assert_eq!(definition.file, Path::new("/p/widget.h"));
        assert!(!definition.fact.local);
    }

    #[test]
    fn a_call_resolves_through_the_return_type_of_a_header() {
        // The whole chain, and three of its links are in the header rather than in the buffer: the class, the
        // member function, and the class its return type names. This is what `DeclFact::returns` was added for,
        // and it is also the path a cached summary goes through — the field is written and read by the codec.
        let source = "#include \"widget.h\"\nvoid f() {\n  Widget w;\n  w.inner().size = 1;\n}\n";
        let (index, tree) = analysed(
            &[(
                "/p/widget.h",
                "struct Inner {\n  int size;\n};\nstruct Widget {\n  Inner inner();\n};\n",
            )],
            "/p/main.cpp",
            source,
        );

        let root = tree.get_red_root();
        let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
        let found = super::member_across_files(
            &index,
            &mut |_: &Path| None,
            &scopes,
            &root,
            Path::new("/p/main.cpp"),
            at(source, "size = 1;"),
        );

        let Known::Yes(definition) = found else {
            panic!("`w.inner()` returns an `Inner`, which declares `size`: {found:?}");
        };
        assert_eq!(definition.fact.name, "size");
        assert_eq!(
            definition.file,
            Path::new("/p/widget.h"),
            "the member is in the header, like everything else on this chain"
        );
    }

    #[test]
    fn a_name_only_a_header_declares_is_found_through_the_index() {
        let source = "#include \"widget.h\"\nvoid f() {\n  Widget w;\n}\n";
        let (index, tree) = analysed(
            &[("/p/widget.h", "struct Widget { int size; };\n")],
            "/p/main.cpp",
            source,
        );

        let root = tree.get_red_root();
        let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
        let found = super::definition_across_files(
            &index,
            &mut |_: &Path| None,
            &scopes,
            &root,
            Path::new("/p/main.cpp"),
            at(source, "Widget w;"),
        );

        let Known::Yes(definition) = found else {
            panic!("the header's class must be found: {found:?}");
        };
        assert_eq!(definition.file, Path::new("/p/widget.h"));
        assert_eq!(definition.fact.name, "Widget");
    }

    #[test]
    fn a_qualified_name_resolves_into_an_included_header() {
        // The two layers together: the qualifier names a namespace that only the *header* declares, so the
        // single-file layer cannot answer it and the spelling goes to the index — which can, because a fact
        // records the scope it was written in.
        let source = "#include \"a.h\"\nvoid f() {\n  a::Widget w;\n}\n";
        let (index, tree) = analysed(
            &[("/p/a.h", "namespace a {\n  struct Widget { int x; };\n}\n")],
            "/p/main.cpp",
            source,
        );

        let root = tree.get_red_root();
        let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
        let found = super::definition_across_files(
            &index,
            &mut |_: &Path| None,
            &scopes,
            &root,
            Path::new("/p/main.cpp"),
            at(source, "Widget w;"),
        );

        let Known::Yes(definition) = found else {
            panic!("the header's `a::Widget` must be found: {found:?}");
        };
        assert_eq!(definition.file, Path::new("/p/a.h"));
        assert_eq!(definition.fact.qualified_name(), "a::Widget");
    }

    #[test]
    fn a_qualified_name_is_not_answered_by_a_same_named_declaration_elsewhere() {
        // The wrong answer qualification exists to prevent, one file further out: `b::Widget` is in scope (its
        // header is included), and the cursor asked for `a::Widget`, which is not. Answering with `b`'s would be a
        // jump to a different entity that the user cannot tell apart from the right one.
        let source = "#include \"b.h\"\nvoid f() {\n  a::Widget w;\n}\n";
        let (index, tree) = analysed(
            &[("/p/b.h", "namespace b {\n  struct Widget { int y; };\n}\n")],
            "/p/main.cpp",
            source,
        );

        let root = tree.get_red_root();
        let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
        let found = super::definition_across_files(
            &index,
            &mut |_: &Path| None,
            &scopes,
            &root,
            Path::new("/p/main.cpp"),
            at(source, "Widget w;"),
        );

        assert!(
            matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
            "`a::Widget` is not declared anywhere this file can see: {found:?}"
        );
    }

    #[test]
    fn a_global_spelling_does_not_match_a_namespaced_declaration() {
        // `::Widget` means the global name space. Both declarations exist and both are visible, so a matcher that
        // dropped the `::` would have two candidates and no way to choose — the prefix is what chooses.
        let source = "#include \"both.h\"\nvoid f() {\n  ::Widget w;\n}\n";
        let (index, tree) = analysed(
            &[(
                "/p/both.h",
                "struct Widget { int global; };\nnamespace ns {\n  struct Widget { int nested; };\n}\n",
            )],
            "/p/main.cpp",
            source,
        );

        let root = tree.get_red_root();
        let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
        let found = super::definition_across_files(
            &index,
            &mut |_: &Path| None,
            &scopes,
            &root,
            Path::new("/p/main.cpp"),
            at(source, "Widget w;"),
        );

        let Known::Yes(definition) = found else {
            panic!("the global `Widget` is the one asked for: {found:?}");
        };
        assert_eq!(definition.fact.scope, None);
        assert_eq!(definition.fact.name, "Widget");
    }

    // -------------------------------------------------------------------------------------------
    // Member access
    //
    // The first query that needs a *type*. Every fixture here declares the object and its type in the same
    // file, because that is where the interesting failure is — the lookup that would otherwise happen is
    // "find some `size` in scope", and a test that only ever has one `size` in the project cannot tell the
    // difference between typing the object and guessing.
    // -------------------------------------------------------------------------------------------

    /// The member a `needle` position names, with the file analysed and indexed the way a real query has it.
    fn member_of(
        files: &[(&str, &str)],
        from: &str,
        source: &str,
        needle: &str,
    ) -> Known<super::ProjectDefinition> {
        let (index, tree) = analysed(files, from, source);
        let root = tree.get_red_root();
        let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);

        super::member_across_files(
            &index,
            &mut |_: &Path| None,
            &scopes,
            &root,
            Path::new(from),
            at(source, needle),
        )
    }

    // -------------------------------------------------------------------------------------------
    // typedef / using aliases
    //
    // The shape the standard library is written in: `std::string` **is** `std::basic_string<char>` and has no
    // members of its own, so a lookup that stops at the spelling finds nothing at all. The motivating case is in
    // these tests in its real form — a `typedef` inside a namespace, with the target written relative to it.
    // -------------------------------------------------------------------------------------------

    #[test]
    fn a_member_of_an_alias_resolves_through_it() {
        let source = "struct Widget {\n  int size;\n};\nusing Alias = Widget;\n\
                      void f() {\n  Alias w;\n  w.size = 1;\n}\n";
        let found = member_of(&[], "/p/a.cpp", source, "size = 1;");

        let Known::Yes(member) = found else {
            panic!("`Alias` names `Widget`, so `size` is `Widget::size`: {found:?}");
        };
        assert_eq!(member.fact.name, "size");
        assert_eq!(member.fact.scope.as_deref(), Some("Widget"));
    }

    #[test]
    fn a_member_of_the_standard_library_string_resolves_into_basic_string() {
        // The case: `basic_string` is where every member is declared, and the
        // alias's target is written **unqualified** inside `namespace std`, so following it needs the alias's own
        // scope. Getting that wrong looks up a global `basic_string` and finds nothing.
        let source = "namespace std {\n  template<typename T> struct basic_string {\n    int size;\n    \
                      int find(int);\n  };\n  typedef basic_string<char> string;\n}\n\
                      void f() {\n  std::string s;\n  s.size = 1;\n}\n";
        let found = member_of(&[], "/p/a.cpp", source, "size = 1;");

        let Known::Yes(member) = found else {
            panic!("`std::string::size` is `std::basic_string::size`: {found:?}");
        };
        assert_eq!(member.fact.name, "size");
        assert_eq!(
            member.fact.scope.as_deref(),
            Some("std::basic_string"),
            "the member is declared in the class the alias points at, and its scope says so"
        );
    }

    #[test]
    fn an_alias_written_with_using_resolves_the_same_way() {
        let source = "namespace std {\n  template<typename T> struct basic_string {\n    int size;\n  };\n  \
                      using string = basic_string<char>;\n}\n\
                      void f() {\n  std::string s;\n  s.size = 1;\n}\n";
        let found = member_of(&[], "/p/a.cpp", source, "size = 1;");

        let Known::Yes(member) = found else {
            panic!("the `using` form is the same declaration shape: {found:?}");
        };
        assert_eq!(member.fact.scope.as_deref(), Some("std::basic_string"));
    }

    #[test]
    fn an_alias_target_written_with_a_qualifier_is_taken_as_it_stands() {
        // A qualified target is already a complete spelling, so the alias's scope is not prepended: doing it would
        // ask for `ns::other::Thing`, which nothing declares.
        let source = "namespace other {\n  struct Thing {\n    int size;\n  };\n}\n\
                      namespace ns {\n  using Alias = other::Thing;\n}\n\
                      void f() {\n  ns::Alias t;\n  t.size = 1;\n}\n";
        let found = member_of(&[], "/p/a.cpp", source, "size = 1;");

        let Known::Yes(member) = found else {
            panic!("the qualified target is the class: {found:?}");
        };
        assert_eq!(member.fact.scope.as_deref(), Some("other::Thing"));
    }

    #[test]
    fn an_alias_to_an_alias_is_followed_to_the_class() {
        // Two steps, which is what the bound exists for: `A` → `B` → the class.
        let source = "struct Widget {\n  int size;\n};\nusing B = Widget;\nusing A = B;\n\
                      void f() {\n  A w;\n  w.size = 1;\n}\n";
        let found = member_of(&[], "/p/a.cpp", source, "size = 1;");

        let Known::Yes(member) = found else {
            panic!("two aliases deep is still a class at the end: {found:?}");
        };
        assert_eq!(member.fact.scope.as_deref(), Some("Widget"));
    }

    #[test]
    fn a_cycle_of_aliases_terminates_and_says_nothing_was_declared() {
        // `using A = B; using B = A;` is writable, so the walk has to stop on its own rather than follow the pair
        // for ever. The answer is the honest one: nothing in the chain names a class.
        let source = "using A = B;\nusing B = A;\nvoid f() {\n  A w;\n  w.size = 1;\n}\n";
        let found = member_of(&[], "/p/a.cpp", source, "size = 1;");

        assert!(
            matches!(found, Known::Unknown(_)),
            "a cycle of aliases names no class: {found:?}"
        );
    }

    #[test]
    fn an_alias_to_itself_terminates() {
        let source = "using A = A;\nvoid f() {\n  A w;\n  w.size = 1;\n}\n";
        let found = member_of(&[], "/p/a.cpp", source, "size = 1;");

        assert!(
            matches!(found, Known::Unknown(_)),
            "`using A = A;` names no class: {found:?}"
        );
    }

    #[test]
    fn an_alias_whose_target_is_not_indexed_reports_the_target() {
        // The target is a real spelling even when nobody indexed it, and the answer says so rather than reporting
        // the alias: `Widget::size` is the question that could not be answered, not `Alias::size`.
        let source = "using Alias = Widget;\nvoid f() {\n  Alias w;\n  w.size = 1;\n}\n";
        let found = member_of(&[], "/p/a.cpp", source, "size = 1;");

        let Known::Unknown(UnknownReason::NotDeclaredHere(written)) = found else {
            panic!("the target is what was looked for: {found:?}");
        };
        assert_eq!(&*written, "Widget::size");
    }

    #[test]
    fn an_alias_to_a_non_class_is_not_a_member_lookup() {
        // `typedef int MyInt;` — following it lands on `int`, which names no class, so the answer is "not
        // declared" rather than a jump into whatever `int` might be mistaken for.
        let source = "typedef int MyInt;\nvoid f() {\n  MyInt x;\n  x.size = 1;\n}\n";
        let found = member_of(&[], "/p/a.cpp", source, "size = 1;");

        assert!(
            matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
            "`int` declares no members: {found:?}"
        );
    }

    #[test]
    fn a_function_pointer_typedef_records_the_whole_type() {
        // `typedef void (*F)(int);` — the type is the specifiers *and* the declarator with the alias's own name
        // cut out, which is `void (*)(int)`. Reading only the specifiers would give `void`, and reading the
        // declarator without cutting would give a type whose *name* is `F`.
        let source = "typedef void (*F)(int);\nvoid f() {\n  F callback;\n  callback();\n}\n";
        let (index, tree) = analysed(&[], "/p/a.cpp", source);
        let root = tree.get_red_root();

        let Known::Yes(fact) = index.definition("F", Path::new("/p/a.cpp")) else {
            panic!("the alias is a fact")
        };
        assert_eq!(
            fact.fact.type_of.as_deref(),
            Some("void (*)(int)"),
            "specifiers plus declarator minus the name"
        );

        // And a `typedef` of a plain type needs no such surgery.
        let plain = "typedef basic_string<char> String;\n";
        let (index, tree) = analysed(&[], "/p/b.cpp", plain);
        let Known::Yes(fact) = index.definition("String", Path::new("/p/b.cpp")) else {
            panic!("the alias is a fact")
        };
        assert_eq!(fact.fact.type_of.as_deref(), Some("basic_string<char>"));

        let _ = (root, tree);
    }

    #[test]
    fn a_member_list_of_an_alias_is_the_member_list_of_its_target() {
        // The other query that turns a spelling into a class, and it has to agree with the single-member one:
        // completion for `std::string` that listed nothing would be a member list of the alias rather than of the
        // class, and an alias has no members.
        let source = "namespace std {\n  template<typename T> struct basic_string {\n    int size;\n    \
                      int find(int);\n  };\n  typedef basic_string<char> string;\n}\n";
        let list = members_of_class(&[], "/p/a.cpp", source, "std::string");

        let Known::Yes(list) = list else {
            panic!("the alias's target is a class with members: {list:?}");
        };
        assert!(
            names(&list).contains(&"size") && names(&list).contains(&"find"),
            "the members are `basic_string`'s: {:?}",
            names(&list)
        );
    }

    #[test]
    fn a_member_access_resolves_through_the_objects_type() {
        let source =
            "struct Widget {\n  int size;\n};\nvoid f() {\n  Widget w;\n  w.size = 1;\n}\n";
        let found = member_of(&[], "/p/a.cpp", source, "size = 1;");

        let Known::Yes(member) = found else {
            panic!("`Widget::size` is declared in this file: {found:?}");
        };
        assert_eq!(member.fact.name, "size");
        assert_eq!(member.fact.scope.as_deref(), Some("Widget"));
        assert!(
            member.fact.range.start_offset < at(source, "void f"),
            "the jump goes to the member's declaration, not to the use"
        );
    }

    #[test]
    fn a_member_of_another_class_with_the_same_name_is_not_the_answer() {
        // The wrong answer this query exists to avoid: two classes with a `size`, and the object decides which
        // one. A lookup that ignored the object would answer with whichever was declared first.
        let source = "struct Other {\n  int size;\n};\nstruct Widget {\n  int size;\n};\n\
                      void f() {\n  Widget w;\n  w.size = 1;\n}\n";
        let found = member_of(&[], "/p/a.cpp", source, "size = 1;");

        let Known::Yes(member) = found else {
            panic!("`Widget::size` is the one the object names: {found:?}");
        };
        assert_eq!(member.fact.scope.as_deref(), Some("Widget"));
        assert!(
            member.fact.range.start_offset > at(source, "struct Widget"),
            "the jump lands in `Widget`, not in `Other`"
        );
    }

    #[test]
    fn a_member_access_reads_a_pointer_the_same_way() {
        // `ptr->member` names a member of the pointee. The type spelling of `Widget* p` is `Widget*`, and the
        // pointer is a fact about the declarator rather than about which class the name refers to.
        let source =
            "struct Widget {\n  int size;\n};\nvoid f() {\n  Widget* p;\n  p->size = 1;\n}\n";
        let found = member_of(&[], "/p/a.cpp", source, "size = 1;");

        let Known::Yes(member) = found else {
            panic!("the pointee's member is the answer: {found:?}");
        };
        assert_eq!(member.fact.name, "size");
    }

    #[test]
    fn a_member_access_reaches_a_class_in_an_included_header() {
        // The everyday case: the class is in the header, the object is local to the `.cpp`.
        let source = "#include \"widget.h\"\nvoid f() {\n  Widget w;\n  w.size = 1;\n}\n";
        let (index, tree) = analysed(
            &[("/p/widget.h", "struct Widget {\n  int size;\n};\n")],
            "/p/main.cpp",
            source,
        );

        let root = tree.get_red_root();
        let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
        let found = super::member_across_files(
            &index,
            &mut |_: &Path| None,
            &scopes,
            &root,
            Path::new("/p/main.cpp"),
            at(source, "size = 1;"),
        );

        let Known::Yes(member) = found else {
            panic!("the member declared in the header is the answer: {found:?}");
        };
        assert_eq!(member.file, Path::new("/p/widget.h"));
        assert_eq!(member.fact.name, "size");
    }

    #[test]
    fn a_member_access_through_a_qualified_type_resolves() {
        // `ns::Widget` as a type: the type spelling goes through the qualified-name machinery rather than being
        // treated as a plain name, which is what makes the two features compose instead of each needing its own
        // path.
        let source = "namespace ns {\n  struct Widget {\n    int size;\n  };\n}\n\
                      void f() {\n  ns::Widget w;\n  w.size = 1;\n}\n";
        let found = member_of(&[], "/p/a.cpp", source, "size = 1;");

        let Known::Yes(member) = found else {
            panic!("`ns::Widget::size` is in this file: {found:?}");
        };
        assert_eq!(member.fact.scope.as_deref(), Some("ns::Widget"));
    }

    #[test]
    fn a_member_of_a_class_that_does_not_have_it_is_not_declared_here() {
        let source =
            "struct Widget {\n  int size;\n};\nvoid f() {\n  Widget w;\n  w.nope = 1;\n}\n";
        let found = member_of(&[], "/p/a.cpp", source, "nope = 1;");

        assert!(
            matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
            "the class is known and the member is not in it: {found:?}"
        );
    }

    #[test]
    fn a_member_access_on_a_call_is_the_callees_return_type() {
        // `make().size` — the construct `DeclFact::returns` exists for.
        //
        // This test used to assert the *opposite*, and its comment said so: "the boundary of this layer, stated as
        // an answer rather than as a wrong guess: `f().size` has a type, and working it out is the larger problem
        // the type layer will have to take on". That problem is now solved for a call whose callee is a
        // declaration this analysis can find, so the boundary moved — the failure of this test is what said so.
        let source = "struct Widget {\n  int size;\n};\nWidget make();\n\
                      void f() {\n  make().size = 1;\n}\n";
        let found = member_of(&[], "/p/a.cpp", source, "size = 1;");

        let Known::Yes(definition) = found else {
            panic!("`make()` returns a `Widget`, so `size` is its member: {found:?}");
        };
        assert_eq!(definition.fact.name, "size");
        assert_eq!(definition.fact.type_of.as_deref(), Some("int"));

        // The other reading of the same tokens: `Widget()` is a **temporary** of the class rather than a call of
        // anything, and the declaration is what says which one this is.
        let constructed = member_of(
            &[],
            "/p/a.cpp",
            "struct Widget {\n  int size;\n};\nvoid f() {\n  Widget().size = 1;\n}\n",
            "size = 1;",
        );
        assert!(
            matches!(constructed, Known::Yes(_)),
            "a temporary of a known class has the class's members: {constructed:?}"
        );
    }

    #[test]
    fn a_member_access_through_a_dereference_resolves() {
        // **`(*make()).size` and `(*p).size`** — the dereference, which is arithmetic on a spelling rather than a
        // lookup: the pointer's declaration already says what it points at.
        //
        // This test asserted the *opposite* until the dereference was implemented, and its comment said so: "the
        // object is a dereference, not a call … a dereference, a subscript and an arithmetic expression each need
        // a type *computed* rather than read off a declaration". Two of the three are now computed, so the
        // boundary moved — the failure of this test is what said so, which is the way this file records a
        // capability landing.
        let through_a_call = member_of(
            &[],
            "/p/a.cpp",
            "struct Widget {\n  int size;\n};\nWidget* make();\nvoid f() {\n  (*make()).size = 1;\n}\n",
            "size = 1;",
        );
        let Known::Yes(found) = through_a_call else {
            panic!(
                "`make()` returns a `Widget*`, so `(*make())` is a `Widget`: {through_a_call:?}"
            );
        };
        assert_eq!(found.fact.name, "size");

        // …and the same spelling through a declaration in the file: `Widget* p;`.
        let through_a_pointer = member_of(
            &[],
            "/p/a.cpp",
            "struct Widget {\n  int size;\n};\nvoid f() {\n  Widget* p;\n  (*p).size = 1;\n}\n",
            "size = 1;",
        );
        let Known::Yes(found) = through_a_pointer else {
            panic!("`p` points at a `Widget`: {through_a_pointer:?}");
        };
        assert_eq!(found.fact.name, "size");

        // …and the same spelling through a **parameter**, whose declarator is written inside the parameter list
        // rather than at the top of a declaration: `void f(Widget* p)`.
        let through_a_parameter = member_of(
            &[],
            "/p/a.cpp",
            "struct Widget {\n  int size;\n};\nvoid f(Widget* p) {\n  (*p).size = 1;\n}\n",
            "size = 1;",
        );
        let Known::Yes(found) = through_a_parameter else {
            panic!("`p` points at a `Widget`: {through_a_parameter:?}");
        };
        assert_eq!(found.fact.name, "size");

        // A reference is the other operator that says "the object is elsewhere", and `*` on it gives the same
        // answer — the declaration spells the type the same way up to the operator.
        let through_a_reference = member_of(
            &[],
            "/p/a.cpp",
            "struct Widget {\n  int size;\n};\nvoid f() {\n  Widget& r = w;\n  (&r)->size = 1;\n}\n",
            "size = 1;",
        );
        assert!(
            matches!(through_a_reference, Known::Yes(_)),
            "`&r` is a `Widget*`: {through_a_reference:?}"
        );
    }

    #[test]
    fn a_dereference_of_something_that_is_not_a_pointer_is_an_unknown_type() {
        // The boundary that is left, and it is a *refusal* rather than a wrong answer: `int* q` dereferenced is an
        // `int`, and an `int` is not a class — so there is nothing to look a member up in, and the answer says which
        // type it was that had no members. It used to say "not declared here" (the lookup went looking for a class
        // called `int`), which reads like a missing file rather than a wrong question. What must not happen, either
        // way, is an invented type.
        let source =
            "struct Widget {\n  int size;\n};\nvoid f() {\n  int* q;\n  (*q).size = 1;\n}\n";
        let found = member_of(&[], "/p/a.cpp", source, "size = 1;");

        assert!(
            matches!(found, Known::Unknown(UnknownReason::UnknownType(_))),
            "an `int` is not a class, and saying so beats inventing one: {found:?}"
        );

        // The other refusal: a subscript on a *class* is `operator[]`, and reaching its element type means
        // instantiating the template. Nothing about the spelling says which argument that is — `vector`'s is the
        // first and `map`'s is the second — so this answers `Unknown` rather than guessing.
        let vector = member_of(
            &[],
            "/p/a.cpp",
            "struct Widget {\n  int size;\n};\ntemplate<typename T> struct Box { T first; };\n\
             void f() {\n  Box<Widget> box;\n  box[0].size = 1;\n}\n",
            "size = 1;",
        );
        assert!(
            matches!(vector, Known::Unknown(UnknownReason::UnknownType(_))),
            "a class subscript needs the template instantiated: {vector:?}"
        );
    }

    #[test]
    fn a_member_access_through_a_subscript_of_an_array_resolves() {
        // `arr[0].size` — an array's element type is written in the declaration: `Widget[4]` is four `Widget`s,
        // and the subscript takes the last `[…]` off.
        let source = "struct Widget {\n  int size;\n};\nvoid f() {\n  Widget arr[4];\n  arr[0].size = 1;\n}\n";
        let found = member_of(&[], "/p/a.cpp", source, "size = 1;");

        let Known::Yes(found) = found else {
            panic!("`arr[0]` is a `Widget`: {found:?}");
        };
        assert_eq!(found.fact.name, "size");

        // An index that is not a literal is the same question, and so is the second dimension of an array of
        // arrays: the subscript takes *one* pair of brackets off, outermost last.
        let two_dimensional = member_of(
            &[],
            "/p/a.cpp",
            "struct Widget {\n  int size;\n};\nvoid f() {\n  Widget grid[2][3];\n  grid[i][j].size = 1;\n}\n",
            "size = 1;",
        );
        assert!(
            matches!(two_dimensional, Known::Yes(_)),
            "`grid[i][j]` is a `Widget`: {two_dimensional:?}"
        );
    }

    #[test]
    fn a_call_of_something_with_no_return_type_is_an_unknown_type() {
        // **A deduced return the syntax can name is recorded.** `return Widget{}` is a prvalue of `Widget`, so
        // `make().size` resolves — the boundary moved here when the construction arm was added (fig 5: the hover had no
        // return type and the caller had nothing to substitute into).
        let source = "struct Widget {\n  int size;\n};\nauto make() { return Widget{}; }\n\
                      void f() {\n  make().size = 1;\n}\n";
        let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
        let Known::Yes(found) = found else {
            panic!("`return Widget{{}}` states the type it returns: {found:?}");
        };
        assert_eq!(found.fact.name, "size");

        // **And the refusals that remain are the honest ones**: a return that is a call (this layer has no callee
        // declaration to read) and a declaration with no body at all.
        for source in [
            "struct Widget {\n  int size;\n};\nWidget source();\n\
             auto make() { return source(); }\nvoid f() {\n  make().size = 1;\n}\n",
            "struct Widget {\n  int size;\n};\nauto make();\nvoid f() {\n  make().size = 1;\n}\n",
        ] {
            let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
            assert!(
                matches!(found, Known::Unknown(UnknownReason::UnknownType(_))),
                "the file does not state what this call has: {found:?}"
            );
        }
    }

    #[test]
    fn a_member_access_on_an_unknown_object_is_an_unknown_type() {
        // The object is a name, but nothing declares it — so there is no type to read, and the answer has to say
        // *that* rather than "the member is missing".
        let source = "void f() {\n  widget.size = 1;\n}\n";
        let found = member_of(&[], "/p/a.cpp", source, "size = 1;");

        assert!(
            matches!(found, Known::Unknown(UnknownReason::UnknownType(_))),
            "nothing says what `widget` is: {found:?}"
        );
    }

    #[test]
    fn a_cursor_that_is_not_on_a_member_access_has_nothing_to_look_up() {
        let source =
            "struct Widget {\n  int size;\n};\nvoid f() {\n  Widget w;\n  w.size = 1;\n}\n";
        let found = member_of(&[], "/p/a.cpp", source, "= 1;");

        assert!(
            matches!(found, Known::Unknown(UnknownReason::UnparsableName)),
            "the cursor is not on a member name: {found:?}"
        );
    }

    #[test]
    fn a_nested_member_access_follows_the_types_down() {
        // This test used to assert the opposite — that `a.b.size` is `Unknown`, because inferring a nested
        // object's type was not done. It is done now, and this is what it bought: the inner access is typed by the
        // same query, so the outer one is answered by asking the inner one what it is.
        let source = "struct Inner {\n  int size;\n};\nstruct Outer {\n  Inner b;\n};\n\
                      void f() {\n  Outer a;\n  a.b.size = 1;\n}\n";
        let found = member_of(&[], "/p/a.cpp", source, "size = 1;");

        let Known::Yes(member) = found else {
            panic!("`Inner::size` is what `a.b.size` names: {found:?}");
        };
        assert_eq!(member.fact.name, "size");
        assert_eq!(member.fact.scope.as_deref(), Some("Inner"));
        assert!(
            member.fact.range.start_offset < at(source, "struct Outer"),
            "the jump lands in `Inner`, not in `Outer`"
        );
    }

    #[test]
    fn a_nested_member_access_that_disagrees_with_the_outer_class_is_not_answered_by_it() {
        // `Outer` has a `size` of its own *and* a member whose type has one: the answer is the inner one, because
        // the object is `a.b`. A lookup that fell back to the outer class when the object was not a plain name
        // would land on `Outer::size`, which is the wrong entity and looks plausible.
        let source = "struct Inner {\n  int size;\n};\nstruct Outer {\n  Inner b;\n  int size;\n};\n\
                      void f() {\n  Outer a;\n  a.b.size = 1;\n}\n";
        let found = member_of(&[], "/p/a.cpp", source, "size = 1;");

        let Known::Yes(member) = found else {
            panic!("the member of `a.b`'s type is the answer: {found:?}");
        };
        assert_eq!(member.fact.scope.as_deref(), Some("Inner"));
    }

    #[test]
    fn this_resolves_to_the_enclosing_class() {
        // `this` needs no inference at all: the scope chain already knows which class it is, which is why it is
        // the cheapest case in the type layer and the first one to handle.
        let source =
            "struct Widget {\n  int size;\n  void grow() {\n    this->size = 1;\n  }\n};\n";
        let found = member_of(&[], "/p/a.cpp", source, "size = 1;");

        let Known::Yes(member) = found else {
            panic!("`this->size` is `Widget::size`: {found:?}");
        };
        assert_eq!(member.fact.name, "size");
        assert_eq!(member.fact.scope.as_deref(), Some("Widget"));
    }

    #[test]
    fn this_resolves_to_the_nearest_class_when_classes_are_nested() {
        let source = "struct Outer {\n  int size;\n  struct Inner {\n    int size;\n    void f() {\n      \
                      this->size = 1;\n    }\n  };\n};\n";
        let found = member_of(&[], "/p/a.cpp", source, "size = 1;");

        let Known::Yes(member) = found else {
            panic!("`this` inside `Inner` is `Inner`: {found:?}");
        };
        assert_eq!(member.fact.scope.as_deref(), Some("Outer::Inner"));
    }

    #[test]
    fn a_nested_access_propagates_why_the_inner_one_failed() {
        // The inner access is where the trouble is, and its reason is kept rather than flattened: there is no
        // member `nope` in `Outer`, so the inner one has no type — and saying "`Outer` has no `nope`" tells a
        // consumer what to fix, where "the type of `a.nope` is unknown" would only say that something is wrong.
        // (This test's first expectation was `UnknownType`, which is what flattening would produce.)
        let source = "struct Inner {\n  int size;\n};\nstruct Outer {\n  Inner b;\n};\n\
                      void f() {\n  Outer a;\n  a.nope.size = 1;\n}\n";
        let found = member_of(&[], "/p/a.cpp", source, "size = 1;");

        assert!(
            matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
            "there is no `nope` to type, and that is the answer worth keeping: {found:?}"
        );
    }

    #[test]
    fn a_member_inherited_from_a_base_class_resolves() {
        // The everyday OO case: the member is not in the class the object's type names, it is in the class that
        // one inherits from. Without the base walk this is `Unknown(NotDeclaredHere)`, which is the answer a user
        // would see for most of their code.
        let source = "struct Base {\n  int size;\n};\nstruct Derived : public Base {\n  int other;\n};\n\
                      void f() {\n  Derived d;\n  d.size = 1;\n}\n";
        let found = member_of(&[], "/p/a.cpp", source, "size = 1;");

        let Known::Yes(member) = found else {
            panic!("`Base::size` is inherited by `Derived`: {found:?}");
        };
        assert_eq!(member.fact.name, "size");
        assert_eq!(member.fact.scope.as_deref(), Some("Base"));
        assert!(
            member.fact.range.start_offset < at(source, "struct Derived"),
            "the jump lands in the base, not in the derived class"
        );
    }

    #[test]
    fn a_member_of_the_class_itself_hides_one_in_a_base() {
        // Level by level, and the class's own level is first: a `size` written in `Derived` wins over `Base`'s,
        // which is what the language does and what a reader expects.
        let source = "struct Base {\n  int size;\n};\nstruct Derived : public Base {\n  int size;\n};\n\
                      void f() {\n  Derived d;\n  d.size = 1;\n}\n";
        let found = member_of(&[], "/p/a.cpp", source, "size = 1;");

        let Known::Yes(member) = found else {
            panic!("the class's own member hides the one it inherits: {found:?}");
        };
        assert_eq!(member.fact.scope.as_deref(), Some("Derived"));
    }

    #[test]
    fn a_member_inherited_through_another_base_resolves() {
        // Two levels: `Derived` has nothing, `Middle` has nothing, `Base` has it.
        let source = "struct Base {\n  int size;\n};\nstruct Middle : public Base {\n  int m;\n};\n\
                      struct Derived : public Middle {\n  int d;\n};\n\
                      void f() {\n  Derived x;\n  x.size = 1;\n}\n";
        let found = member_of(&[], "/p/a.cpp", source, "size = 1;");

        let Known::Yes(member) = found else {
            panic!("a member two bases down is still inherited: {found:?}");
        };
        assert_eq!(member.fact.scope.as_deref(), Some("Base"));
    }

    #[test]
    fn a_member_declared_in_two_bases_at_once_is_ambiguous_rather_than_picked() {
        // A diamond without `virtual`: both sides declare `size`, so the name is not uniquely resolved by the
        // language. Picking the first would be a jump to an entity the user cannot tell from the other, which is
        // exactly the wrong answer this project refuses to give.
        let source = "struct Left {\n  int size;\n};\nstruct Right {\n  int size;\n};\n\
                      struct Both : public Left, public Right {\n  int own;\n};\n\
                      void f() {\n  Both b;\n  b.size = 1;\n}\n";
        let found = member_of(&[], "/p/a.cpp", source, "size = 1;");

        assert!(
            matches!(found, Known::Unknown(UnknownReason::Ambiguous(_))),
            "two bases declare it and nothing chooses: {found:?}"
        );
    }

    #[test]
    fn a_member_inherited_across_a_header_resolves() {
        // The base is in the header and the derived class is in the file being edited: the base *list* comes from
        // this file's tree and the base *class* from the index, which is the two halves meeting.
        let source = "#include \"base.h\"\nstruct Derived : public Base {\n  int d;\n};\n\
                      void f() {\n  Derived x;\n  x.size = 1;\n}\n";
        let (index, tree) = analysed(
            &[("/p/base.h", "struct Base {\n  int size;\n};\n")],
            "/p/main.cpp",
            source,
        );

        let root = tree.get_red_root();
        let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
        let found = super::member_across_files(
            &index,
            &mut |_: &Path| None,
            &scopes,
            &root,
            Path::new("/p/main.cpp"),
            at(source, "size = 1;"),
        );

        let Known::Yes(member) = found else {
            panic!("the inherited member is declared in the header: {found:?}");
        };
        assert_eq!(member.file, Path::new("/p/base.h"));
        assert_eq!(member.fact.name, "size");
    }

    #[test]
    fn a_member_nobody_declares_is_still_not_declared() {
        // The base walk must not turn "not found" into "found somewhere": the honest answer survives it.
        let source = "struct Base {\n  int size;\n};\nstruct Derived : public Base {\n  int d;\n};\n\
                      void f() {\n  Derived x;\n  x.nope = 1;\n}\n";
        let found = member_of(&[], "/p/a.cpp", source, "nope = 1;");

        assert!(
            matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
            "neither the class nor its base declares it: {found:?}"
        );
    }

    #[test]
    fn a_base_list_is_read_without_its_access_keywords() {
        // `public Base` is one base called `Base`: reading the whole specifier would look for a class named
        // "public Base", which is a name nothing declares.
        let source = "struct Base {\n  int size;\n};\nstruct Derived : private virtual Base {\n  int d;\n};\n\
                      void f() {\n  Derived x;\n  x.size = 1;\n}\n";
        let found = member_of(&[], "/p/a.cpp", source, "size = 1;");

        let Known::Yes(member) = found else {
            panic!("the access and `virtual` are not part of the base's name: {found:?}");
        };
        assert_eq!(member.fact.scope.as_deref(), Some("Base"));
    }

    #[test]
    fn a_base_that_inherits_from_itself_terminates() {
        // A cycle in the base list cannot be written in valid C++, and a malformed file can produce one: the
        // visited set is what keeps the walk from being an infinite loop on a file that is being typed.
        let source = "struct A : public B {\n  int a;\n};\nstruct B : public A {\n  int size;\n};\n\
                      void f() {\n  A x;\n  x.size = 1;\n}\n";
        let found = member_of(&[], "/p/a.cpp", source, "size = 1;");

        let Known::Yes(member) = found else {
            panic!("a cycle must not stop the member being found: {found:?}");
        };
        assert_eq!(member.fact.scope.as_deref(), Some("B"));
    }

    #[test]
    fn a_local_declaration_still_wins_when_the_header_also_has_the_name() {
        // `count` is declared both here and in the header. The answer is this file's, and it is reached without
        // the index — which is the resolution order, not an optimisation.
        let source = "#include \"widget.h\"\nint count = 0;\nvoid f() {\n  count = 1;\n}\n";
        let (index, tree) = analysed(
            &[("/p/widget.h", "int count = 7;\n")],
            "/p/main.cpp",
            source,
        );

        let root = tree.get_red_root();
        let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
        let found = super::definition_across_files(
            &index,
            &mut |_: &Path| None,
            &scopes,
            &root,
            Path::new("/p/main.cpp"),
            at(source, "count = 1;"),
        );

        let Known::Yes(definition) = found else {
            panic!("the file's own declaration wins: {found:?}");
        };
        assert_eq!(definition.file, Path::new("/p/main.cpp"));
    }

    // -------------------------------------------------------------------------------------------
    // Member lists
    //
    // The *list* form of the member query, and the fixtures are written to make the one decision it makes
    // visible: which class declares each member, and whether that is the type asked about or a base. The
    // staleness test at the end is the reason none of it is stored.
    // -------------------------------------------------------------------------------------------

    /// The members of `class`, with the file analysed and indexed the way a real query has them.
    fn members_of_class(
        files: &[(&str, &str)],
        from: &str,
        source: &str,
        class: &str,
    ) -> Known<super::MemberList> {
        let (index, tree) = analysed(files, from, source);
        let root = tree.get_red_root();
        let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);

        super::members_of(&index, &scopes, &root, Path::new(from), class)
    }

    /// The member names, in the order the query produced them.
    fn names(list: &super::MemberList) -> Vec<&str> {
        list.members
            .iter()
            .map(|member| member.fact.name.as_str())
            .collect()
    }

    /// **An anonymous union's members are the enclosing struct's members** — `line.integer` in a C corpus.
    ///
    /// ```c
    /// struct line {
    ///     struct point from;
    ///     union { long integer; double real; };   // no member name between the struct and the union
    ///     char colour;
    /// };
    /// ```
    ///
    /// C11's anonymous members put `integer` and `real` in `line`'s member space. The scope walk reached the
    /// declaration, saw one with no name, walked its body — and the body's declarations landed in a scope of their own
    /// instead of in `line`, so a completion after `line.` offered four of the six names.
    #[test]
    fn an_anonymous_unions_members_belong_to_the_struct() {
        let source = "struct point { int x; int y; };\n\
struct line {\n\
    struct point from;\n\
    union { long integer; double real; };\n\
    char colour;\n\
};\n";
        let found = members_of_class(&[], "/p/a.c", source, "line");
        let Known::Yes(list) = found else {
            panic!("`line` is declared here: {found:?}");
        };
        assert!(
            names(&list).contains(&"integer"),
            "the union is anonymous, so its members are `line`'s: {:?}",
            names(&list)
        );
        assert!(
            names(&list).contains(&"real"),
            "and so is `real`: {:?}",
            names(&list)
        );
    }

    #[test]
    fn a_class_declared_more_than_once_still_reports_the_bases_it_could_not_read() {
        // MSVC's `<istream>`, in miniature: the class, and an explicit instantiation of it. Measured on the real
        // header, `std::basic_istream` is declared three times — the class and two
        // `template class _CRTIMP2_PURE_IMPORT basic_istream<char, …>;` lines — and the inherited members used
        // to be missing with `unlisted` **empty**, which is a list claiming a completeness it does not have.
        //
        // **What changed, and why the expectation is `Base` rather than `Stream`.** The base walk used to ask
        // `definition` for the class, which answers `Unknown(Ambiguous)` for a name declared twice, and an
        // ambiguous class answered *no base list at all* — so the base clause was never even read, and the
        // class itself was named as the thing that could not be read. It now merges the bases of **every**
        // declaration, which is what makes `xmemory`'s `allocator_traits` — forward-declared at 554 with no
        // base and defined at 755 with one — inherit anything at all. What is left unread is the base the
        // clause actually names.
        //
        // `Base` is named here because `a.cpp` does not include the header that declares it, which is the
        // honest gap and the one this field exists for: the list says which name it could not follow rather
        // than quietly ending.
        let source = "template <class E>\nstruct Stream : Base {\n  int read;\n};\ntemplate struct Stream<char>;\n";
        let found = members_of_class(
            &[("/p/base.h", "struct Base { int eof; };\n")],
            "/p/a.cpp",
            source,
            "Stream",
        );

        let Known::Yes(list) = found else {
            panic!("`Stream` is declared here: {found:?}");
        };
        assert_eq!(names(&list), ["read"], "its own member is listed");
        assert_eq!(
            list.unlisted
                .iter()
                .map(|base| base.spelling.as_str())
                .collect::<Vec<_>>(),
            ["Base"],
            "and the base the walk could not follow is named, so the list does not claim completeness"
        );
    }

    #[test]
    fn a_class_lists_the_members_written_in_it() {
        // Written out of alphabetical order on purpose: a member list is ordered by name rather than by the text,
        // because the file's scope tree keeps its bindings name-sorted while the index keeps facts in offset
        // order, and the two have to agree for a class to list the same way wherever it is declared.
        let source = "struct Widget {\n  void grow();\n  int size;\n};\n";
        let found = members_of_class(&[], "/p/a.cpp", source, "Widget");

        let Known::Yes(list) = found else {
            panic!("`Widget` is declared in this file: {found:?}");
        };

        assert_eq!(names(&list), ["grow", "size"]);
        assert!(
            list.unlisted.is_empty(),
            "a class with no bases has nothing left unread: {:?}",
            list.unlisted
        );

        let size = &list.members[1];
        assert_eq!(size.declared_in, "Widget");
        assert_eq!(size.depth, 0, "its own member, not an inherited one");
        assert!(!size.ambiguous);
        assert_eq!(size.file, Path::new("/p/a.cpp"));
        assert_eq!(
            size.fact.type_of.as_deref(),
            Some("int"),
            "the type a completion shows beside the name"
        );
        assert_eq!(
            list.own().count(),
            2,
            "every member here is the class's own"
        );
    }

    #[test]
    fn a_derived_class_lists_its_own_members_before_the_ones_it_inherits() {
        // Nearest first, which is the order C++ hides in — and the base is tagged rather than flattened into the
        // derived class, so a consumer can show an inherited member as inherited and can jump to `Base::count`
        // rather than to a copy of it.
        let source = "struct Base {\n  int inherited_count;\n};\n\
                      struct Derived : public Base {\n  int own_count;\n};\n";
        let found = members_of_class(&[], "/p/a.cpp", source, "Derived");

        let Known::Yes(list) = found else {
            panic!("`Derived` is declared in this file: {found:?}");
        };

        assert_eq!(
            names(&list),
            ["own_count", "inherited_count"],
            "the class's own members come first, and the inherited one is last"
        );
        assert_eq!(list.members[0].declared_in, "Derived");
        assert_eq!(list.members[0].depth, 0);
        assert_eq!(
            list.members[1].declared_in, "Base",
            "the member is the base's, not the derived class's"
        );
        assert_eq!(list.members[1].depth, 1);
        assert_eq!(
            list.members[1].fact.type_of.as_deref(),
            Some("int"),
            "and it carries its own declaration's type"
        );
        assert_eq!(list.at_depth(1).count(), 1);
    }

    #[test]
    fn a_member_the_class_redeclares_hides_the_one_in_its_base() {
        // Hiding is by name, not by signature: `Derived::size` hides `Base::size` whatever the parameters are,
        // so the base's is not in the list. A list that kept both would offer a name the language does not find.
        let source = "struct Base {\n  int size;\n};\n\
                      struct Derived : public Base {\n  double size;\n};\n";
        let found = members_of_class(&[], "/p/a.cpp", source, "Derived");

        let Known::Yes(list) = found else {
            panic!("`Derived` is declared in this file: {found:?}");
        };

        assert_eq!(
            names(&list),
            ["size"],
            "one `size`, and it is the derived class's"
        );
        assert_eq!(list.members[0].declared_in, "Derived");
        assert_eq!(list.members[0].fact.type_of.as_deref(), Some("double"));
    }

    #[test]
    fn a_name_two_bases_declare_is_listed_twice_and_marked_ambiguous() {
        // The list form of the ambiguity the single-member query reports: both declarations are kept, because
        // dropping either would be choosing one for the user, and both are flagged, because a consumer offering
        // the name has to be able to say that the language does not resolve it here.
        let source = "struct Left {\n  int value;\n};\nstruct Right {\n  int value;\n};\n\
                      struct Both : public Left, public Right {\n  int own;\n};\n";
        let found = members_of_class(&[], "/p/a.cpp", source, "Both");

        let Known::Yes(list) = found else {
            panic!("`Both` is declared in this file: {found:?}");
        };

        assert_eq!(names(&list), ["own", "value", "value"]);

        let values: Vec<&super::ProjectMember> = list
            .members
            .iter()
            .filter(|member| member.fact.name == "value")
            .collect();
        assert_eq!(values.len(), 2, "both declarations survive into the list");
        assert!(
            values.iter().all(|member| member.ambiguous),
            "both are contested: {values:?}"
        );

        let mut declaring: Vec<&str> = values
            .iter()
            .map(|member| member.declared_in.as_str())
            .collect();
        declaring.sort_unstable();
        assert_eq!(declaring, ["Left", "Right"]);

        assert!(
            !list.members[0].ambiguous,
            "`own` is declared once, in one class"
        );
    }

    #[test]
    fn a_destructor_hides_nothing_in_a_base_because_its_spelling_is_its_own() {
        // `virtual ~Base();` — the name the binding holds is `~Base`, and a destructor's `identifier_text()` is
        // `None`, so this path used to store an **empty** name. Comparing two empty names made `~Derived` hide
        // `~Base`, which is a wrong answer arrived at by treating a missing spelling as if it were a spelling.
        //
        // The spelling is stored now (`DeclFact::name` is `binding.name.text()`, the same one the index files), so the
        // two destructors are two *different* names and neither hides the other for the right reason rather than by
        // exception — and an operator, which had the same empty name, is a member a lookup can find.
        let source = "struct Base {\n  virtual ~Base();\n  int size;\n};\n\
                      struct Derived : public Base {\n  virtual ~Derived();\n  int d;\n};\n";
        let found = members_of_class(&[], "/p/a.cpp", source, "Derived");

        let Known::Yes(list) = found else {
            panic!("`Derived` is declared in this file: {found:?}");
        };

        let destructors: Vec<&super::ProjectMember> = list
            .members
            .iter()
            .filter(|member| member.fact.name.starts_with('~'))
            .collect();
        assert_eq!(
            destructors.len(),
            2,
            "both destructors are declarations that exist, and dropping one would be a silent omission: {:?}",
            names(&list)
        );

        let mut classes: Vec<&str> = destructors
            .iter()
            .map(|member| member.declared_in.as_str())
            .collect();
        classes.sort_unstable();
        assert_eq!(classes, ["Base", "Derived"]);

        let mut spellings: Vec<&str> = destructors
            .iter()
            .map(|member| member.fact.name.as_str())
            .collect();
        spellings.sort_unstable();
        assert_eq!(
            spellings,
            ["~Base", "~Derived"],
            "a destructor's name is the class it destroys, so the two are not one name"
        );

        assert!(
            destructors.iter().all(|member| !member.ambiguous),
            "two different spellings are not one contested name: {destructors:?}"
        );
        assert!(
            list.members
                .iter()
                .any(|member| member.fact.name == "size" && member.declared_in == "Base"),
            "and the named members still cross the inheritance boundary: {:?}",
            names(&list)
        );
    }

    /// **A destructor written without a specifier is a member, and is listed by its spelling.**
    ///
    /// Two halves of this were broken at different times, and the fixture pins both.
    ///
    /// The first is the *class's* name. A constructor and a destructor have no `decl-specifier-seq`, so the grammar
    /// puts their name straight under the declaration, and `name_from_text` used to read the class's name off the
    /// destructor inside its body: `Derived` was never bound and `d` was filed under `~Derived`. That half is green
    /// (`tests/scopes.rs`, shape `File{Widget}(Class{size,~Widget})`).
    ///
    /// The second is the *fact's* name, and it is why this test was `#[ignore]`d for several rounds with the
    /// expectation `["~Derived", "d"]` written down: `DeclFact::name` was empty for anything without an identifier —
    /// a destructor, an operator, a conversion function — on the argument that their spellings are not lookup keys.
    /// Measured, that cost more than it bought: `members_of` answered `[""]` for a class whose member is
    /// `operator[]`, so an operator was invisible to every member query, and a destructor answered for its own class
    /// in `definition`. A fact now carries the **spelling** (`binding.name.text()`), so the member list reads
    /// `~Derived` — the round that fixed it is the one that also removed the `#[ignore]`.
    ///
    /// The order is the list's, not the source's: members are sorted by name, so `d` comes before `~Derived`.
    #[test]
    fn a_destructor_without_a_specifier_is_a_member() {
        let source = "struct Derived {\n  ~Derived();\n  int d;\n};\n";
        let found = members_of_class(&[], "/p/a.cpp", source, "Derived");

        let Known::Yes(list) = found else {
            panic!("the class must be found by its own name: {found:?}");
        };
        assert_eq!(names(&list), ["d", "~Derived"]);
    }

    #[test]
    fn overloads_in_one_class_are_not_ambiguous() {
        // The other half of the rule above, and the case a count-of-declarations implementation gets wrong:
        // `f` is declared twice and is one name in one class, so nothing about it is contested.
        let source = "struct Widget {\n  void f();\n  void f(int);\n};\n";
        let found = members_of_class(&[], "/p/a.cpp", source, "Widget");

        let Known::Yes(list) = found else {
            panic!("`Widget` is declared in this file: {found:?}");
        };

        assert_eq!(names(&list), ["f", "f"], "both overloads are listed");
        assert!(
            list.members.iter().all(|member| !member.ambiguous),
            "one class declaring a name twice is an overload set, not an ambiguity: {:?}",
            list.members
        );
    }

    #[test]
    fn a_cycle_of_bases_terminates_and_each_class_contributes_once() {
        // A base list that cannot be written in valid C++ and can be produced by a malformed file. The visited set
        // is what keeps the walk finite; without it this test does not fail, it does not return.
        let source = "struct A : public B {\n  int a_member;\n};\nstruct B : public A {\n  int b_member;\n};\n";
        let found = members_of_class(&[], "/p/a.cpp", source, "A");

        let Known::Yes(list) = found else {
            panic!("`A` is declared in this file: {found:?}");
        };

        assert_eq!(names(&list), ["a_member", "b_member"]);
        assert_eq!(list.members[0].depth, 0);
        assert_eq!(
            list.members[1].depth, 1,
            "`A` is reached again as `B`'s base and is not listed a second time"
        );
    }

    #[test]
    fn a_template_class_lists_the_members_it_was_written_with() {
        // No instantiation, and the answer says so by what it contains: `value` has the type `T`, which is what
        // the class wrote. Instantiating would mean picking an argument, and a member list for `Holder<int>` and
        // `Holder<std::string>` would then be two different lists — which is a `sema` question, not this one.
        let source = "template <typename T>\nstruct Holder {\n  T value;\n  int count;\n};\n";
        let found = members_of_class(&[], "/p/a.cpp", source, "Holder");

        let Known::Yes(list) = found else {
            panic!("`Holder` is declared in this file: {found:?}");
        };

        assert_eq!(names(&list), ["count", "value"]);
        assert_eq!(
            list.members[1].fact.type_of.as_deref(),
            Some("T"),
            "the parameter as written, not an instantiated type"
        );
        assert!(
            !list.members.iter().any(|member| member.fact.name == "T"),
            "the template parameter is declared in the parameter list, not in the class: {:?}",
            names(&list)
        );
    }

    #[test]
    fn a_type_nothing_declares_has_no_member_list_rather_than_an_empty_one() {
        // The distinction the whole crate is built around, asked of a list: an empty list is a claim that the type
        // has no members, and this analysis cannot make it about a type it has never seen.
        let source = "void f() { }\n";
        let found = members_of_class(&[], "/p/a.cpp", source, "Nowhere");

        assert!(
            matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
            "`Nowhere` is not a type this analysis has seen: {found:?}"
        );
    }

    #[test]
    fn a_class_that_is_empty_has_an_empty_member_list() {
        // The other side of the test above, and the one that needs the *name* to be asked about rather than the
        // members: `struct Empty { };` writes no member and no scope either — see `scopes::class_like` — so a
        // query that read "no members found" as "no class found" would report an empty class as a missing one.
        let source = "struct Empty { };\n";
        let found = members_of_class(&[], "/p/a.cpp", source, "Empty");

        let Known::Yes(list) = found else {
            panic!("`Empty` is declared in this file and has no members: {found:?}");
        };
        assert!(list.members.is_empty());
    }

    #[test]
    fn a_member_declared_in_a_nested_class_is_not_a_member_of_the_outer_one() {
        // The scope a fact records is the scope it was written in, so `Inner::x` is a member of `Inner` and the
        // member of `Outer` is the class `Inner`. A list built by name rather than by scope would put `x` in both.
        let source = "struct Outer {\n  struct Inner {\n    int x;\n  };\n  int y;\n};\n";
        let found = members_of_class(&[], "/p/a.cpp", source, "Outer");

        let Known::Yes(list) = found else {
            panic!("`Outer` is declared in this file: {found:?}");
        };

        assert_eq!(names(&list), ["Inner", "y"]);
        assert_eq!(list.members[0].fact.qualified_name(), "Outer::Inner");
    }

    #[test]
    fn a_member_list_crosses_a_header_and_keeps_the_base_tagged() {
        // The everyday layout: the base is in a header, the derived class is in the file being edited. The base
        // list comes from the buffer's tree and the base's members from the index, and the answer has to name the
        // header as the place to jump to rather than the buffer.
        let source = "#include \"base.h\"\nstruct Derived : public Base {\n  int d;\n};\n";
        let (index, tree) = analysed(
            &[("/p/base.h", "struct Base {\n  int size;\n};\n")],
            "/p/main.cpp",
            source,
        );
        let root = tree.get_red_root();
        let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);

        let found = super::members_of(&index, &scopes, &root, Path::new("/p/main.cpp"), "Derived");
        let Known::Yes(list) = found else {
            panic!("`Derived` is declared in the buffer: {found:?}");
        };

        assert_eq!(names(&list), ["d", "size"]);
        assert_eq!(list.members[1].file, Path::new("/p/base.h"));
        assert_eq!(list.members[1].declared_in, "Base");
    }

    #[test]
    fn a_base_that_resolves_to_a_template_is_listed_without_instantiating_it() {
        // `public Base<int>` is the class `Base` for the purpose of finding members: the arguments say which type
        // is inherited, not which class declares what. Reading the spelling literally would look for a class named
        // `Base<int>`, which is a name no declaration has.
        //
        // **What the arguments are kept for is the member, not the lookup.** A member inherited from a template base is
        // written in that base's parameters (`T size;`), and substituting them is what makes its type the one a reader of
        // `Derived` sees. The tag therefore names the instantiation: `Base<int>` is where the member came from.
        let source = "template <typename T>\nstruct Base {\n  T size;\n};\n\
                      struct Derived : public Base<int> {\n  int d;\n};\n";
        let found = members_of_class(&[], "/p/a.cpp", source, "Derived");

        let Known::Yes(list) = found else {
            panic!("`Derived` is declared in this file: {found:?}");
        };

        assert_eq!(names(&list), ["d", "size"]);
        assert_eq!(
            list.members[1].fact.type_of.as_deref(),
            Some("int"),
            "the base's parameter is substituted: {list:?}"
        );
        assert_eq!(list.members[1].declared_in, "Base<int>");
    }

    #[test]
    fn a_base_nothing_declares_is_reported_as_a_gap_rather_than_dropped() {
        // The list is incomplete and says so. Answering with just `d` would be a claim that `Derived` has one
        // member, which is exactly what this analysis cannot know: `Base` is behind an include nobody indexed.
        let source = "#include \"missing.h\"\nstruct Derived : public Base {\n  int d;\n};\n";
        let found = members_of_class(&[], "/p/a.cpp", source, "Derived");

        let Known::Yes(list) = found else {
            panic!("`Derived` itself is in the buffer: {found:?}");
        };

        assert_eq!(names(&list), ["d"], "what could be listed is listed");
        assert_eq!(list.unlisted.len(), 1, "and what could not is named");
        assert_eq!(list.unlisted[0].spelling, "Base");
        assert!(
            matches!(list.unlisted[0].reason, UnknownReason::NotDeclaredHere(_)),
            "the reason has to say that the base is not here, not that the list ended: {:?}",
            list.unlisted[0].reason
        );
    }

    #[test]
    fn a_base_of_a_class_in_a_namespace_is_looked_up_in_that_namespace() {
        // The rule that took `examples/std_query.rs` from 7/9 to 9/9, in the shape MSVC's STL has it: `std::map`
        // inherits from `_Tree`, `_Tree` is declared in `<xtree>` inside `_STD_BEGIN` (= `namespace std {`), and
        // the base clause spells it **unqualified**. A base name is looked up from the scope *enclosing* the class
        // and outward, so `_Tree` written inside `std` names `std::_Tree` — and the file-scope `_Tree` below,
        // which declares something else entirely, must not be consulted: the enclosing namespace is a nearer scope
        // and unqualified lookup stops at the first scope that has the name.
        //
        // Both walks are asserted here because both had the same hole and a fix to one is invisible from the
        // other: the list (`members_of`) and the single member (`member_across_files`).
        let lib = "namespace std {\nstruct _Tree {\n  void find();\n};\nstruct map : _Tree {\n  int count;\n};\n}\n";
        let source = "#include \"lib.h\"\nstruct _Tree {\n  void wrong();\n};\nvoid f() {\n  std::map m;\n  m.find();\n  m.wrong();\n}\n";
        let files: &[(&str, &str)] = &[("/p/lib.h", lib)];

        let Known::Yes(list) = members_of_class(files, "/p/a.cpp", source, "std::map") else {
            panic!("`std::map` is in the indexed header");
        };
        assert_eq!(
            names(&list),
            ["count", "find"],
            "`find` comes from the base, and `wrong` is not a member of anything this class inherits"
        );
        assert!(
            list.unlisted.is_empty(),
            "the base was found, so nothing here is a gap: {:?}",
            list.unlisted
        );
        assert_eq!(
            list.members[1].declared_in, "std::_Tree",
            "the answer names the scope the base was found in, not the spelling the class wrote"
        );
        assert_eq!(list.members[1].depth, 1);

        let found = member_of(files, "/p/a.cpp", source, "find();");
        let Known::Yes(found) = found else {
            panic!("`m.find` is `std::_Tree::find`: {found:?}");
        };
        assert_eq!(found.file, Path::new("/p/lib.h"));
        assert_eq!(found.fact.qualified_name(), "std::_Tree::find");

        assert!(
            matches!(
                member_of(files, "/p/a.cpp", source, "wrong();"),
                Known::Unknown(UnknownReason::NotDeclaredHere(_))
            ),
            "a base name that a nearer scope has does not fall through to the file-scope `_Tree`"
        );
    }

    #[test]
    fn a_type_spelled_from_the_global_name_space_lists_the_same_members() {
        // `::Widget w;` is a declaration whose type spelling carries the leading `::`, and a consumer feeding this
        // query from `DeclFact.type_of` therefore hands it `::Widget`. The index keys a global declaration under
        // its bare name — a file-scope declaration has no scope prefix — so the prefix has to come off before the
        // walk, or a class that is plainly in the buffer answers `Unknown(NotDeclaredHere("::Widget"))`.
        let source = "struct Widget {\n  int size;\n};\nvoid f() {\n  ::Widget w;\n}\n";
        let found = members_of_class(&[], "/p/a.cpp", source, "::Widget");

        let Known::Yes(list) = found else {
            panic!("`::Widget` is the file-scope `Widget`: {found:?}");
        };
        assert_eq!(names(&list), ["size"]);
        assert_eq!(list.members[0].declared_in, "Widget");
    }

    #[test]
    fn a_member_added_to_a_base_appears_without_reindexing_the_derived_class() {
        // The test that decides whether inherited members are *materialized*, and the reason they are not.
        //
        // Only `b.h` is rebuilt below. Nothing about `A`'s text or its key changes, so a summary that stored the
        // members `A` inherits would go on answering with `old_member` for ever — and no invalidation rule could
        // catch it, because there is nothing to invalidate: the edit is in a file `A` never mentions by name.
        // Walking the chain at query time is what makes the second assertion true.
        let a_header = "#include \"b.h\"\nstruct A : public B {\n  int a_member;\n};\n";
        let before = "struct B {\n  int old_member;\n};\n";
        let after = "struct B {\n  int new_member;\n};\n";
        let main = "#include \"a.h\"\n";

        let mut index = index(&[
            ("/p/main.cpp", main),
            ("/p/a.h", a_header),
            ("/p/b.h", before),
        ]);

        let tree = cpp_parser::CppParser::parse(main, cpp_parser::ParserConfig::default());
        let root = tree.get_red_root();
        let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);

        let listed = |index: &ProjectIndex| match super::members_of(
            index,
            &scopes,
            &root,
            Path::new("/p/main.cpp"),
            "A",
        ) {
            Known::Yes(list) => list
                .members
                .iter()
                .map(|member| member.fact.name.clone())
                .collect::<Vec<_>>(),
            other => panic!("`A` is declared in an included header: {other:?}"),
        };

        assert_eq!(listed(&index), ["a_member", "old_member"]);

        // `b.h` and nothing else. `a.h` keeps the summary it was built with, which is the whole point.
        let mut rebuilt = summarize(Path::new("/p/b.h"), after, SummaryKey::new(1, 0));
        for include in &mut rebuilt.includes {
            include.resolved = Some(std::path::PathBuf::from(format!("/p/{}", include.spelling)));
        }
        index.insert(rebuilt);

        assert_eq!(
            listed(&index),
            ["a_member", "new_member"],
            "the derived class's members are read from its bases at query time, so the edit is seen without \
             anything of `A`'s being rebuilt"
        );

        // And why that worked, asserted rather than implied: `A`'s own summary holds its own member and nothing it
        // inherits. The day something starts writing inherited members into a derived class's summary, this is
        // where it shows up — before the stale answers do.
        let a = index
            .summary(Path::new("/p/a.h"))
            .expect("`a.h` is indexed");
        let a_members: Vec<&str> = a
            .declarations
            .iter()
            .filter(|fact| fact.scope.as_deref() == Some("A"))
            .map(|fact| fact.name.as_str())
            .collect();
        assert_eq!(
            a_members,
            ["a_member"],
            "a fact stores the spelling `B`, never the members `B` happens to have"
        );
    }

    // -------------------------------------------------------------------------------------------
    // Completion: the cursor-to-members query
    //
    // Every fixture here is an **incomplete program**, which is the only honest way to test this: `w.` does not
    // parse, and a test that made it parse would be testing a question nobody asks. The helper below therefore
    // does not assert a clean parse — see `analysed_while_typing`.
    // -------------------------------------------------------------------------------------------
    /// The offset just **past** the last `needle`, which is where the cursor is after that much has been typed.
    fn after(source: &str, needle: &str) -> usize {
        source
            .rfind(needle)
            .unwrap_or_else(|| panic!("{needle:?} is not in {source:?}"))
            + needle.len()
    }

    /// The members offered at the cursor just past `needle`.
    fn completions_at(
        files: &[(&str, &str)],
        from: &str,
        source: &str,
        needle: &str,
    ) -> Known<super::MemberCompletions> {
        let (index, tree) = analysed_while_typing(files, from, source);
        let root = tree.get_red_root();
        let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);

        super::member_completions_at(
            &index,
            &mut |_: &Path| None,
            &scopes,
            &root,
            Path::new(from),
            after(source, needle),
        )
    }

    /// **A `private` member is not offered from outside the class**, and is offered from inside it.
    ///
    /// The two directions in one fixture, because a rule that hid everything would pass the first half alone: what
    /// the reader may *write* is the question, and C++ answers it by where the cursor is — see
    /// [`DeclFact::access`] for the field and [`offerable_members`] for the rule.
    ///
    /// The default access of a `class` is the other half: `int hidden;` written before any label is private, which
    /// is why the key matters and not just the labels.
    #[test]
    fn a_private_member_is_offered_inside_the_class_and_not_outside_it() {
        let outside = "\
class Widget {
    int hidden;
public:
    int shown;
};
void f() {
    Widget w;
    w.
}
";
        let Known::Yes(found) = completions_at(&[], "/p/a.cpp", outside, "w.") else {
            panic!("`w` is a `Widget`");
        };
        let offered: Vec<&str> = found
            .members
            .members
            .iter()
            .map(|m| m.fact.name.as_str())
            .collect();
        assert_eq!(
            offered,
            ["shown"],
            "`hidden` is private and the cursor is not in `Widget`"
        );
        assert_eq!(
            found.hidden_by_access, 1,
            "and the answer says how many it kept out"
        );

        let inside = "\
class Widget {
    int hidden;
public:
    int shown;
    void grow(Widget& other) {
        other.
    }
};
";
        let Known::Yes(found) = completions_at(&[], "/p/a.cpp", inside, "other.") else {
            panic!("`other` is a `Widget`");
        };
        let offered: Vec<&str> = found
            .members
            .members
            .iter()
            .map(|m| m.fact.name.as_str())
            .collect();
        assert_eq!(
            offered,
            ["grow", "hidden", "shown"],
            "inside the class both are nameable, so both are offered"
        );
    }

    /// **A member defined outside its class is still that class's member** — for access, which is the question this
    /// test is about, and for everything else that is a property of the declaration.
    ///
    /// The shape is one every real C++ codebase is written in: the class states the declaration (and with it the
    /// access) and the definition lives further down the file, in a section of its own with no access label in
    /// sight. `declared_access_at` reads the level *where the name is written*, so at an out-of-class definition it
    /// finds no class body at all — see the expectations below.
    #[test]
    fn a_member_defined_outside_its_class_keeps_its_access() {
        let source = "\
class Widget {
    int hidden;
public:
    int shown;
    void set(int value);
    void grow(Widget& other);
};

void Widget::set(int value) {
    hidden = value;
}

void Widget::grow(Widget& other) {
    other.
}

void f(Widget& w) {
    w.
}
";
        let Known::Yes(found) = completions_at(&[], "/p/a.cpp", source, "other.") else {
            panic!("`other` is a `Widget`");
        };
        let offered: Vec<&str> = found
            .members
            .members
            .iter()
            .map(|m| m.fact.name.as_str())
            .collect();
        assert!(
            offered.contains(&"hidden"),
            "the cursor is inside a member of `Widget`, so `hidden` is nameable there: {offered:?}"
        );
        assert!(
            offered.contains(&"set") && offered.contains(&"shown") && offered.contains(&"grow"),
            "and so is everything else the class declares: {offered:?}"
        );

        let Known::Yes(found) = completions_at(&[], "/p/a.cpp", source, "w.") else {
            panic!("`w` is a `Widget`");
        };
        let offered: Vec<&str> = found
            .members
            .members
            .iter()
            .map(|m| m.fact.name.as_str())
            .collect();
        assert!(
            !offered.contains(&"hidden"),
            "and from outside the class the same member is not: {offered:?}"
        );
    }

    /// **A `protected` member is offered in a class derived from the one that declares it** — and not from a free
    /// function, which is the whole difference between `protected` and `public`.
    ///
    /// The base chain is walked from the cursor's own class ([`classes_the_cursor_is_in`]), which is what makes the
    /// derived case work: the member's own class is not where the cursor is, but it is an ancestor of it.
    #[test]
    fn a_protected_member_is_offered_in_a_derived_class() {
        let source = "\
class Base {
protected:
    int guarded;
public:
    int open;
};
class Derived : public Base {
    void grow(Derived& other) {
        other.
    }
};
void f(Derived& d) {
    d.
}
";
        let Known::Yes(found) = completions_at(&[], "/p/a.cpp", source, "other.") else {
            panic!("`other` is a `Derived`");
        };
        let offered: Vec<&str> = found
            .members
            .members
            .iter()
            .map(|m| m.fact.name.as_str())
            .collect();
        assert_eq!(
            offered,
            ["grow", "guarded", "open"],
            "`guarded` is protected and the cursor is in a class derived from the one that declares it"
        );

        let Known::Yes(found) = completions_at(&[], "/p/a.cpp", source, "d.") else {
            panic!("`d` is a `Derived`");
        };
        let offered: Vec<&str> = found
            .members
            .members
            .iter()
            .map(|m| m.fact.name.as_str())
            .collect();
        assert_eq!(
            offered,
            ["open"],
            "and from a free function the same member is not nameable"
        );
    }

    #[test]
    fn a_member_access_with_nothing_typed_offers_the_types_members() {
        // The keystroke that asks the question. `w.` is not a program and does not parse, which is exactly why
        // this is a query over a damaged tree rather than over a compiled one.
        let source = "struct Widget {\n  int size;\n  void grow();\n};\n\
                      void f() {\n  Widget w;\n  w.\n}\n";
        let found = completions_at(&[], "/p/a.cpp", source, "w.");

        let Known::Yes(completions) = found else {
            panic!("`w` is a `Widget` declared two lines up: {found:?}");
        };

        assert_eq!(completions.class, "Widget");
        assert_eq!(
            completions
                .members
                .members
                .iter()
                .map(|member| member.fact.name.as_str())
                .collect::<Vec<_>>(),
            ["grow", "size"]
        );
        assert_eq!(completions.prefix, "", "nothing of the name is written yet");
        assert_eq!(
            completions.member_range.start_offset,
            after(source, "w."),
            "the empty range sits just past the operator, which is where the name goes"
        );
        assert_eq!(completions.member_range.length, 0);
    }

    #[test]
    fn a_half_typed_member_offers_the_same_members_and_names_the_prefix() {
        // The other half of the same question: the list is the *whole* list — filtering is the client's job and
        // it has the document — while the range is what the client replaces with the chosen member.
        let source = "struct Widget {\n  int size;\n  void grow();\n};\n\
                      void f() {\n  Widget w;\n  w.si\n}\n";
        let found = completions_at(&[], "/p/a.cpp", source, "w.si");

        let Known::Yes(completions) = found else {
            panic!("the cursor is on the member being typed: {found:?}");
        };

        assert_eq!(completions.class, "Widget");
        assert_eq!(completions.prefix, "si");
        assert_eq!(
            &source[completions.member_range.start_offset..completions.member_range.end_offset()],
            "si",
            "the range covers what is written, so replacing it does not leave a doubled name"
        );
    }

    #[test]
    fn a_pointer_member_access_offers_the_pointees_members() {
        let source = "struct Widget {\n  int size;\n};\nvoid f() {\n  Widget* p;\n  p->\n}\n";
        let found = completions_at(&[], "/p/a.cpp", source, "p->");

        let Known::Yes(completions) = found else {
            panic!("`Widget* p` is a pointer to a `Widget`: {found:?}");
        };
        assert_eq!(completions.class, "Widget");
        assert_eq!(completions.members.members.len(), 1);
    }

    #[test]
    fn a_completion_on_this_offers_the_enclosing_class_members() {
        // `this` needs no inference — the scope chain already knows which class it is — which makes it the one
        // completion inside a class body that works before the object has a name.
        let source = "struct Widget {\n  int size;\n  void grow() {\n    this->\n  }\n};\n";
        let found = completions_at(&[], "/p/a.cpp", source, "this->");

        let Known::Yes(completions) = found else {
            panic!("`this` is the enclosing `Widget`: {found:?}");
        };
        assert_eq!(completions.class, "Widget");
        assert_eq!(
            completions
                .members
                .members
                .iter()
                .map(|member| member.fact.name.as_str())
                .collect::<Vec<_>>(),
            ["grow", "size"]
        );
    }

    #[test]
    fn the_members_offered_include_the_ones_the_bases_declare() {
        // Completion is where the query-time base walk pays off: the whole inherited list is there, each entry
        // tagged with the class that declares it, without anything having been stored on `Derived`.
        let source = "struct Base {\n  int inherited_size;\n};\n\
                      struct Derived : public Base {\n  int own_size;\n};\n\
                      void f() {\n  Derived d;\n  d.\n}\n";
        let found = completions_at(&[], "/p/a.cpp", source, "d.");

        let Known::Yes(completions) = found else {
            panic!("`d` is a `Derived`: {found:?}");
        };

        let listed: Vec<(&str, &str)> = completions
            .members
            .members
            .iter()
            .map(|member| (member.fact.name.as_str(), member.declared_in.as_str()))
            .collect();
        assert_eq!(
            listed,
            [("own_size", "Derived"), ("inherited_size", "Base")],
            "the class's own member first, then the inherited one, tagged with where it is declared"
        );
    }

    #[test]
    fn the_members_offered_cross_a_header() {
        let source = "#include \"widget.h\"\nvoid f() {\n  Widget w;\n  w.\n}\n";
        let (index, tree) = analysed_while_typing(
            &[("/p/widget.h", "struct Widget {\n  int size;\n};\n")],
            "/p/main.cpp",
            source,
        );
        let root = tree.get_red_root();
        let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);

        let found = super::member_completions_at(
            &index,
            &mut |_: &Path| None,
            &scopes,
            &root,
            Path::new("/p/main.cpp"),
            after(source, "w."),
        );

        let Known::Yes(completions) = found else {
            panic!("the class is in the included header: {found:?}");
        };
        assert_eq!(completions.class, "Widget");
        assert_eq!(
            completions.members.members[0].file,
            Path::new("/p/widget.h")
        );
    }

    #[test]
    fn a_completion_after_a_call_offers_what_the_call_returns() {
        // `make().` — the keystroke this capability exists for, and the one the test below is the boundary of.
        // Before `returns` existed this answered `UnknownType`; now it is the same answer as `w.` for a `w` of the
        // same type, which is the whole point of recording a return type at all.
        let source = "struct Widget {\n  int size;\n  void grow();\n};\nWidget make();\n\
                      void f() {\n  make().\n}\n";
        let Known::Yes(completions) = completions_at(&[], "/p/a.cpp", source, "make().") else {
            panic!("`make()` returns a `Widget`");
        };

        assert_eq!(completions.class, "Widget");
        assert_eq!(
            completions
                .members
                .members
                .iter()
                .map(|member| member.fact.name.as_str())
                .collect::<Vec<_>>(),
            ["grow", "size"]
        );
    }

    #[test]
    fn a_completion_after_a_dereference_offers_the_pointees_members() {
        // The completion form of [`a_member_access_through_a_dereference_resolves`], and the one a user meets:
        // typing `(*make()).` should offer the `Widget`'s members, not nothing.
        //
        // This test asserted the *opposite* until the dereference was implemented — "a call's return type is not
        // computed yet" — and the failing assertion is what said the boundary had moved.
        let source = "struct Widget {\n  int size;\n};\nWidget* make();\n\
                      void f() {\n  (*make()).\n}\n";
        let found = completions_at(&[], "/p/a.cpp", source, "(*make()).");

        let Known::Yes(completions) = found else {
            panic!("`(*make())` is a `Widget`, so its members are the answer: {found:?}");
        };
        assert_eq!(completions.class, "Widget");
    }

    #[test]
    fn a_completion_on_an_expression_with_no_type_offers_nothing_and_says_why() {
        // What is left of the boundary, and this is where a user meets it. Offering the members of some other
        // class would be worse than offering none: the list looks like an answer.
        //
        // An **arithmetic expression** is the case that is still out of reach, and it is the honest one: `a + b`
        // has a type the language computes from conversions this layer does not model, so there is nothing to
        // read off a declaration.
        let source =
            "struct Widget {\n  int size;\n};\nvoid f() {\n  Widget a;\n  (a.size + a.size).\n}\n";
        let found = completions_at(&[], "/p/a.cpp", source, "(a.size + a.size).");

        assert!(
            matches!(found, Known::Unknown(UnknownReason::UnknownType(_))),
            "an arithmetic expression's type is not read off a declaration: {found:?}"
        );
    }

    #[test]
    fn a_completion_on_an_object_of_an_unknown_type_offers_nothing() {
        // The object resolves fine — `w`'s declaration *says* its type is `Nowhere` — and what fails is the type:
        // nothing here declares it. So the reason names the type rather than the object, which is what tells a
        // consumer whether to go looking for a missing declaration of `w` or of `Nowhere`.
        let source = "void f() {\n  Nowhere w;\n  w.\n}\n";
        let found = completions_at(&[], "/p/a.cpp", source, "w.");

        assert!(
            matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
            "`Nowhere` is a type nothing here declares: {found:?}"
        );
        let Known::Unknown(UnknownReason::NotDeclaredHere(name)) = found else {
            unreachable!("just checked")
        };
        assert_eq!(
            &*name, "Nowhere",
            "and the reason names the type, not the object"
        );
    }

    #[test]
    fn a_cursor_that_is_not_on_a_member_access_offers_nothing() {
        let source = "struct Widget {\n  int size;\n};\nvoid f() {\n  Widget w;\n}\n";
        let found = completions_at(&[], "/p/a.cpp", source, "Widget w;");

        assert!(
            matches!(found, Known::Unknown(UnknownReason::UnparsableName)),
            "a declaration is not a member access: {found:?}"
        );
    }

    #[test]
    fn a_cursor_on_the_object_asks_about_the_object() {
        // The offset decides, not the node: `w.size` with the cursor *on* `w` is a question about `w`, and
        // answering it with `Widget`'s members would insert a member name in the middle of the object's.
        let source = "struct Widget {\n  int size;\n};\nvoid f() {\n  Widget w;\n  w.size;\n}\n";
        let (index, tree) = analysed_while_typing(&[], "/p/a.cpp", source);
        let root = tree.get_red_root();
        let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);

        let found = super::member_completions_at(
            &index,
            &mut |_: &Path| None,
            &scopes,
            &root,
            Path::new("/p/a.cpp"),
            at(source, "w.size"),
        );

        assert!(
            matches!(found, Known::Unknown(UnknownReason::UnparsableName)),
            "the cursor is on the object, before the operator: {found:?}"
        );
    }

    #[test]
    fn a_cursor_inside_a_name_filters_by_the_part_before_it() {
        // The range and the prefix answer two halves of one edit, and this is where they differ: the client
        // replaces all of `size`, while the filter matches `si` — the part the user has actually typed. Using the
        // whole spelling for both is what makes completion offer nothing in the middle of a word.
        let source = "struct Widget {\n  int size;\n};\nvoid f() {\n  Widget w;\n  w.size;\n}\n";
        let (index, tree) = analysed_while_typing(&[], "/p/a.cpp", source);
        let root = tree.get_red_root();
        let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);

        // Two characters into `size`.
        let cursor = at(source, "w.size") + 2 + 2;

        let found = super::member_completions_at(
            &index,
            &mut |_: &Path| None,
            &scopes,
            &root,
            Path::new("/p/a.cpp"),
            cursor,
        );
        let Known::Yes(completions) = found else {
            panic!("the cursor is inside the member's name: {found:?}");
        };

        assert_eq!(completions.prefix, "si", "what has been typed so far");
        assert_eq!(
            &source[completions.member_range.start_offset..completions.member_range.end_offset()],
            "size",
            "and the whole name is what gets replaced"
        );
    }

    #[test]
    fn a_completed_member_access_still_answers_with_its_own_prefix() {
        // The state between two keystrokes: `w.size` is a finished expression, and a cursor at its end is still
        // asking for the members — with `size` as the prefix to replace. Nothing about the completion path is
        // special to the half-typed case.
        let source = "struct Widget {\n  int size;\n  void grow();\n};\n\
                      void f() {\n  Widget w;\n  w.size\n}\n";
        let found = completions_at(&[], "/p/a.cpp", source, "w.size");

        let Known::Yes(completions) = found else {
            panic!("the cursor is at the end of `size`: {found:?}");
        };
        assert_eq!(completions.prefix, "size");
        assert_eq!(
            &source[completions.member_range.start_offset..completions.member_range.end_offset()],
            "size"
        );
    }

    #[test]
    fn a_jump_on_a_member_that_is_not_written_yet_has_nothing_to_jump_to() {
        // The completion query tolerates a nameless access; the *definition* query must not, and the difference is
        // the question rather than the shape. Reading `w.` as "the member named nothing" would answer
        // `NotDeclaredHere("Widget::")`, which says the class is missing a member that has not been typed.
        let source = "struct Widget {\n  int size;\n};\nvoid f() {\n  Widget w;\n  w.\n}\n";
        let (index, tree) = analysed_while_typing(&[], "/p/a.cpp", source);
        let root = tree.get_red_root();
        let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);

        let found = super::member_across_files(
            &index,
            &mut |_: &Path| None,
            &scopes,
            &root,
            Path::new("/p/a.cpp"),
            after(source, "w."),
        );

        assert!(
            matches!(found, Known::Unknown(UnknownReason::UnparsableName)),
            "there is no written name to resolve: {found:?}"
        );
    }

    // -------------------------------------------------------------------------------------------
    // Completion: the cursor-to-names query
    //
    // The sibling of the member query above, and the same kind of fixture: a *name being written* is not a
    // program, so these files do not parse and are not meant to. What each test asserts is one of the four
    // positions — after a `::`, after a class's `::`, after a global `::`, and with no qualifier at all — because
    // they reach the same query through different scopes.
    // -------------------------------------------------------------------------------------------

    /// The names offered at the cursor just past `needle`.
    fn names_at(
        files: &[(&str, &str)],
        from: &str,
        source: &str,
        needle: &str,
    ) -> Known<super::NameCompletions> {
        let (index, tree) = analysed_while_typing(files, from, source);
        let root = tree.get_red_root();
        let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);

        super::name_completions_at(
            &index,
            &scopes,
            &root,
            Path::new(from),
            after(source, needle),
        )
    }

    /// The names offered at the **first offset of the body** of `source` — where nothing is written yet.
    ///
    /// The position with no prefix, which is a different question from [`names_at`]'s and cannot be spelled as one:
    /// a needle is what a test looks for, and "the cursor is at the start of a line" is not a spelling.
    fn names_at_blank(
        files: &[(&str, &str)],
        from: &str,
        source: &str,
    ) -> Known<super::NameCompletions> {
        let (index, tree) = analysed_while_typing(files, from, source);
        let root = tree.get_red_root();
        let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);

        let at = source
            .find("void f()")
            .and_then(|body| source[body..].find('{').map(|brace| body + brace + 1))
            .expect("the fixture has a body");

        super::name_completions_at(&index, &scopes, &root, Path::new(from), at)
    }

    /// The names in an answer, in the order the query put them.
    #[track_caller]
    fn offered(found: &Known<super::NameCompletions>) -> Vec<String> {
        match found {
            Known::Yes(completions) => completions
                .names
                .iter()
                .map(|name| name.fact.name.clone())
                .collect(),
            other => panic!("expected names: {other:?}"),
        }
    }

    /// **A name is offered however far into its namespace's files it is written.**
    ///
    /// The budget that used to apply here was spent in **file order**: the walk took whole files until it had
    /// collected 400 declarations, so a namespace whose first file is large — every standard header is — pushed the
    /// rest out of the answer. Measured on a file that includes `<cstdio>`, `<iostream>`, `<optional>`, `<string>`
    /// and `<format>`: completion after `std::` offered **175** names, `cin` and `cout` among them, and `string`
    /// (declared in `<xstring>`, one include further along) was not there at all — so the list a reader saw depended
    /// on the order of their `#include` lines. See [`MAX_COLLECTED_IN_A_SCOPE`].
    #[test]
    fn a_name_in_a_late_file_of_a_namespace_is_still_offered() {
        // More than the old budget, so that the file after this one is never read under it.
        let mut big = String::from("namespace ns {\n");
        for index in 0..(super::MAX_COLLECTED_NAMES + 20) {
            big.push_str(&format!("  int filler{index};\n"));
        }
        big.push_str("}\n");

        let late = "namespace ns {\n  int zebra;\n}\n";
        // **`late.h` is reached through `big.h`**, which is the shape the defect had: the header that fills the
        // budget is a *direct* include of the file being typed in, and the one holding the wanted name is one step
        // further along the walk — `string` lives in `<xstring>`, which `<string>` includes.
        let big_with_include = format!("#include \"late.h\"\n{big}");
        let source = "#include \"big.h\"\nvoid f() {\n  ns::\n}\n";
        let files = [
            ("/p/big.h", big_with_include.as_str()),
            ("/p/late.h", late),
            ("/p/a.cpp", source),
        ];

        let found = names_at(&files, "/p/a.cpp", source, "ns::");
        let names = offered(&found);

        assert!(
            names.iter().any(|name| name == "zebra"),
            "the name is declared in a file the cursor can see, and the list must not stop before it: \
             {} names offered, none of them `zebra`",
            names.len()
        );
    }

    /// **The members of a class template reached through an alias**: `std::string::` is how a reader asks this
    /// every day, and the class it names is not a scope *in the buffer's tree* — it is an alias declared in a header.
    ///
    /// The query that answers it is the same one a member access uses ([`members_of`]), which resolves the alias, the
    /// template spelling and the bases; asking only `declarations_in("std::string")` — what this used to do — finds
    /// nothing at all, because no declaration in the program has that scope. Measured on a file that includes
    /// `<string>`: **0** members before this, **63** of `basic_string`'s after.
    #[test]
    fn the_members_of_a_class_template_reached_through_an_alias_are_offered() {
        let header = "namespace ns {\n\
                      template <class _Ty>\n\
                      struct Basic {\n\
                        unsigned long size() const;\n\
                        _Ty* data();\n\
                      };\n\
                      using String = Basic<char>;\n\
                      }\n";
        let source = "#include \"basic.h\"\nvoid f() {\n  ns::String::\n}\n";
        let files = [("/p/basic.h", header), ("/p/a.cpp", source)];

        let found = names_at(&files, "/p/a.cpp", source, "ns::String::");
        let names = offered(&found);

        assert!(
            names.iter().any(|name| name == "size") && names.iter().any(|name| name == "data"),
            "`ns::String` is `ns::Basic<char>`, and its members are the answer: {names:?}"
        );
    }

    #[test]
    fn a_qualified_scope_offers_the_names_written_in_it() {
        let source =
            "namespace ns {\n  struct Widget { };\n  int helper();\n}\nvoid f() {\n  ns::\n}\n";
        let found = names_at(&[], "/p/a.cpp", source, "ns::");

        assert_eq!(
            offered(&found),
            ["Widget", "helper"],
            "sorted within the scope"
        );
        let Known::Yes(completions) = found else {
            unreachable!("asserted above")
        };
        assert_eq!(completions.scope, "ns", "the scope as a lookup key");
        assert_eq!(completions.prefix, "", "nothing of the name is typed yet");
        assert_eq!(
            completions.name_range.start_offset,
            after(source, "ns::"),
            "the empty range sits just past the `::`, where the name goes"
        );
        assert_eq!(completions.name_range.length, 0);
    }

    #[test]
    fn a_half_typed_name_keeps_the_prefix_and_replaces_the_whole_segment() {
        // The two halves of one edit, as in the member query: the range covers what the client replaces (`Wid`),
        // and the prefix is what it filters by — the part before the cursor.
        let source = "namespace ns {\n  struct Widget { };\n}\nvoid f() {\n  ns::Wid\n}\n";
        let Known::Yes(completions) = names_at(&[], "/p/a.cpp", source, "ns::Wid") else {
            panic!("the cursor is on the name being typed");
        };

        assert_eq!(completions.scope, "ns");
        assert_eq!(completions.prefix, "Wid");
        assert_eq!(
            completions.name_range.start_offset,
            at(source, "Wid"),
            "the range is the written segment, not the point"
        );
        assert_eq!(completions.name_range.length, 3);
    }

    #[test]
    fn a_class_scope_offers_its_members_and_the_ones_its_bases_declare() {
        // `Derived::` is a scope like `ns::`, and the difference between them is the language's: a class is
        // defined once, and the names it has include the ones it inherits.
        let source = "struct Base {\n  typedef int size_type;\n};\n\
                      struct Derived : Base {\n  typedef int value_type;\n};\n\
                      void f() {\n  Derived::\n}\n";
        let found = names_at(&[], "/p/a.cpp", source, "Derived::");

        assert_eq!(
            offered(&found),
            ["value_type", "size_type"],
            "the class's own names first, then the ones a base declares"
        );
        let Known::Yes(completions) = found else {
            unreachable!("asserted above")
        };
        assert_eq!(completions.scope, "Derived");
        assert_eq!(
            completions
                .names
                .iter()
                .map(|name| name.depth)
                .collect::<Vec<_>>(),
            [0, 1],
            "the base's name is one step further out, which is the order lookup walks in"
        );
    }

    #[test]
    fn a_global_scope_offers_only_what_is_declared_at_file_scope() {
        // `::` is a scope and not an empty qualifier: it asks about the global name space, so a namespace member
        // and a local are both *not* in the answer, while the file-scope declarations are — the enclosing function
        // and namespace included, because those are written there.
        let source =
            "int global;\nnamespace ns {\n  int inner;\n}\nvoid f() {\n  int local;\n  ::\n}\n";
        let found = names_at(&[], "/p/a.cpp", source, "::");

        assert_eq!(offered(&found), ["f", "global", "ns"]);
        let Known::Yes(completions) = found else {
            unreachable!("asserted above")
        };
        assert_eq!(completions.scope, "::", "the global name space, as spelled");

        let names = offered(&Known::Yes(completions.clone()));
        assert!(
            !names.contains(&"inner".to_string()) && !names.contains(&"local".to_string()),
            "a namespace member and a local are not in the global name space: {names:?}"
        );
    }

    #[test]
    fn a_bare_name_offers_the_scopes_the_cursor_is_inside_innermost_first() {
        // No qualifier: every name visible from here, and the order is C++'s — the body's own, then the class's,
        // then the namespace's, then the file's.
        let source = "int at_file_scope;\nnamespace ns {\n  int in_a_namespace;\n  struct C {\n    int member;\n    \
                      void g() {\n      int local;\n      loc\n    }\n  };\n}\n";
        let found = names_at(&[], "/p/a.cpp", source, "loc");

        assert_eq!(
            offered(&found),
            [
                // depth 0: the body the cursor is in
                "local",
                // depth 1: the class — its members, `g` among them
                "g",
                "member",
                // depth 2: the namespace
                "C",
                "in_a_namespace",
                // depth 3: file scope, which is also where every included file writes
                "at_file_scope",
                "ns"
            ]
        );

        let Known::Yes(completions) = found else {
            unreachable!("asserted above")
        };
        assert_eq!(completions.scope, "", "no qualifier was written");
        assert_eq!(completions.prefix, "loc");

        // The order is not alphabetical and is not meant to be: it is the order C++ searches in, so a consumer
        // that shows the list in this order shows the name the user would get first.
        let depths: Vec<usize> = completions.names.iter().map(|name| name.depth).collect();
        let mut sorted = depths.clone();
        sorted.sort_unstable();
        assert_eq!(depths, sorted, "nearer scopes come first");
        assert_eq!(depths[0], 0, "the local is in the scope the cursor is in");
    }

    #[test]
    fn another_files_local_is_not_offered_by_a_bare_name() {
        // The reason `local` is a field at all. The header's `__first` is a declaration in the index with no scope
        // to place it in, and the standard library's headers declare thousands of names like it — offering one
        // would fill the list with names the user cannot see, and the *right* answer for this cursor is the local
        // that really is here.
        let header = "/p/widget.h";
        let declaration = "void g() {\n  int __first = 0;\n  int helper;\n}\nint global_name;\n";
        let source = "#include \"widget.h\"\nvoid f() {\n  int mine;\n  min\n}\n";
        let found = names_at(&[(header, declaration)], "/p/main.cpp", source, "min");

        let names = offered(&found);
        assert!(
            names.contains(&"mine".to_string()),
            "the local of *this* file is offered, from its own scopes: {names:?}"
        );
        assert!(
            !names.contains(&"__first".to_string()) && !names.contains(&"helper".to_string()),
            "another file's locals are not names this file can write: {names:?}"
        );

        // **A name that does not begin with what is being typed is not collected**, which is a filter and not a
        // ranking: `global_name` cannot be completed from `min`, and a client would drop it. So the same question
        // is asked once more at the **blank** position the feature exists for, which is where the file-scope name
        // has to appear — asking it at `min` would be asserting two things at once.
        let at_a_blank = names_at_blank(&[(header, declaration)], "/p/main.cpp", source);
        let names = offered(&at_a_blank);
        assert!(
            names.contains(&"global_name".to_string()),
            "…while a file-scope name in the same header is offered where nothing is typed: {names:?}"
        );
    }

    #[test]
    fn a_namespace_is_merged_across_the_buffer_and_the_header() {
        // A namespace can be reopened by every file that mentions it, so the buffer's names are never the whole
        // answer — the difference from a class, which is defined once and listed from one place.
        let source =
            "#include \"ns.h\"\nnamespace ns {\n  int in_the_buffer;\n}\nvoid f() {\n  ns::\n}\n";
        let found = names_at(
            &[("/p/ns.h", "namespace ns {\n  int in_the_header;\n}\n")],
            "/p/main.cpp",
            source,
            "ns::",
        );

        assert_eq!(offered(&found), ["in_the_buffer", "in_the_header"]);
    }

    #[test]
    fn a_scope_nothing_declares_is_not_an_empty_list() {
        // "Declared and empty" and "no such scope" are different answers, and the second one is what stops a
        // consumer from reporting that the user is looking at a namespace with nothing in it.
        let source = "void f() {\n  nowhere::\n}\n";
        let found = names_at(&[], "/p/a.cpp", source, "nowhere::");

        assert!(
            matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
            "nothing declares `nowhere`: {found:?}"
        );
    }

    #[test]
    fn a_cursor_where_a_name_can_be_written_offers_the_visible_names() {
        // **The entry condition, which used to be the whole bug.** A cursor with no name written yet — at the start
        // of a declaration, after `return `, at the beginning of a line — is the position completion exists for.
        // This test used to assert the opposite ("the cursor is on a declaration's name, which is not a name being
        // written"), and a language server that answers nothing when a client asks at a blank position is one a
        // user reports as "it has no completion for local variables" — which is what happened.
        //
        // The replacement range is the *whole* identifier the cursor is on, so choosing a name replaces it rather
        // than inserting beside it.
        // The cursor is just past the name `Widget` — the position a client reports when the user puts the cursor
        // on the identifier and presses the completion key.
        let source = "struct Widget { int size; };\nvoid f() {\n  Widget w;\n}\n";
        let found = names_at(&[], "/p/a.cpp", source, "Widget");

        let Known::Yes(found) = found else {
            panic!("a name can be written here: {found:?}");
        };
        let names: Vec<&str> = found
            .names
            .iter()
            .map(|offered| offered.fact.name.as_str())
            .collect();
        assert!(
            names.contains(&"Widget") && names.contains(&"f"),
            "the names in scope: {names:?}"
        );
        assert_eq!(found.prefix, "Widget", "what is written filters the list");
        assert_eq!(
            found.name_range.length,
            "Widget".len(),
            "and the chosen name replaces it rather than being inserted beside it"
        );
    }

    // -------------------------------------------------------------------------------------------
    // Macros
    //
    // Every test here is about **translation order**: which of the `#define`s and `#undef`s the
    // preprocessor would have gone past last. The fixtures are written so that the *set* of facts is the
    // same in several of them and only their order differs, because the set is what a naive
    // implementation gets right and the order is what it gets wrong.
    // -------------------------------------------------------------------------------------------

    /// The line a found fact is on, so a test can say "the second one" without arithmetic.
    fn line_of(source: &str, offset: usize) -> usize {
        source[..offset].matches('\n').count()
    }

    #[test]
    fn a_macro_defined_above_its_use_resolves_to_the_define() {
        let source = "#define MAX 1\nint x = MAX;\n";
        let (index, tree) = analysed(&[], "/p/a.cpp", source);
        let root = tree.get_red_root();

        let found =
            super::macro_across_files(&index, &root, Path::new("/p/a.cpp"), at(source, "MAX;"));

        let Known::Yes(found) = found else {
            panic!("the define above the use is the answer: {found:?}");
        };
        assert_eq!(found.file, Path::new("/p/a.cpp"));
        assert_eq!(found.fact.name, "MAX");
        assert!(found.fact.kind.is_definition());
        assert_eq!(
            &source[found.fact.range.start_offset..found.fact.range.end_offset()],
            "MAX",
            "and the range is the name a user would be sent to"
        );
    }

    #[test]
    fn a_macro_defined_below_its_use_is_not_in_force_yet() {
        // The file is read top to bottom, so a `#define` further down the page is not what the name above it
        // means. A table keyed by name alone answers this one wrong, and it is the reason the query is positional.
        let source = "int x = MAX;\n#define MAX 1\n";
        let (index, tree) = analysed(&[], "/p/a.cpp", source);
        let root = tree.get_red_root();

        let found =
            super::macro_across_files(&index, &root, Path::new("/p/a.cpp"), at(source, "MAX;"));
        assert!(
            matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
            "nothing above the use defines it: {found:?}"
        );
    }

    #[test]
    fn a_macro_in_an_included_header_resolves_into_that_header() {
        let source = "#include \"config.h\"\nint x = FEATURE;\n";
        let header = "#define FEATURE 1\n";
        let (index, tree) = analysed(&[("/p/config.h", header)], "/p/main.cpp", source);
        let root = tree.get_red_root();

        let found = super::macro_across_files(
            &index,
            &root,
            Path::new("/p/main.cpp"),
            at(source, "FEATURE;"),
        );

        let Known::Yes(found) = found else {
            panic!("the header's define must be found: {found:?}");
        };
        assert_eq!(found.file, Path::new("/p/config.h"));
        assert_eq!(line_of(header, found.fact.range.start_offset), 0);
    }

    #[test]
    fn a_header_included_after_the_use_does_not_define_it_yet() {
        let source = "int x = FEATURE;\n#include \"config.h\"\n";
        let (index, tree) = analysed(
            &[("/p/config.h", "#define FEATURE 1\n")],
            "/p/main.cpp",
            source,
        );
        let root = tree.get_red_root();

        let found = super::macro_across_files(
            &index,
            &root,
            Path::new("/p/main.cpp"),
            at(source, "FEATURE;"),
        );
        assert!(
            matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
            "the include is below the use: {found:?}"
        );
    }

    #[test]
    fn the_later_of_two_headers_that_define_it_wins() {
        // The set of facts is identical in this test and the next one; only the order differs. That is the pair a
        // name-keyed implementation cannot tell apart.
        let source = "#include \"one.h\"\n#include \"two.h\"\nint x = FLAG;\n";
        let one = "#define FLAG 1\n";
        let two = "#define FLAG 2\n";
        let (index, tree) = analysed(
            &[("/p/one.h", one), ("/p/two.h", two)],
            "/p/main.cpp",
            source,
        );
        let root = tree.get_red_root();

        let found =
            super::macro_across_files(&index, &root, Path::new("/p/main.cpp"), at(source, "FLAG;"));

        let Known::Yes(found) = found else {
            panic!("the last define gone past is the answer: {found:?}");
        };
        assert_eq!(found.file, Path::new("/p/two.h"));
    }

    #[test]
    fn swapping_the_two_includes_swaps_the_answer() {
        let source = "#include \"two.h\"\n#include \"one.h\"\nint x = FLAG;\n";
        let one = "#define FLAG 1\n";
        let two = "#define FLAG 2\n";
        let (index, tree) = analysed(
            &[("/p/one.h", one), ("/p/two.h", two)],
            "/p/main.cpp",
            source,
        );
        let root = tree.get_red_root();

        let found =
            super::macro_across_files(&index, &root, Path::new("/p/main.cpp"), at(source, "FLAG;"));

        let Known::Yes(found) = found else {
            panic!("order is the whole answer: {found:?}");
        };
        assert_eq!(found.file, Path::new("/p/one.h"));
    }

    #[test]
    fn a_local_define_after_an_include_wins_over_the_header() {
        let source = "#include \"config.h\"\n#define FEATURE 2\nint x = FEATURE;\n";
        let (index, tree) = analysed(
            &[("/p/config.h", "#define FEATURE 1\n")],
            "/p/main.cpp",
            source,
        );
        let root = tree.get_red_root();

        let found = super::macro_across_files(
            &index,
            &root,
            Path::new("/p/main.cpp"),
            at(source, "FEATURE;"),
        );
        let Known::Yes(found) = found else {
            panic!("the file's own later define is what is in force: {found:?}");
        };
        assert_eq!(found.file, Path::new("/p/main.cpp"));
    }

    #[test]
    fn a_local_define_before_an_include_loses_to_the_header() {
        // The same two facts as the test above with the lines the other way round, which is the whole point: this
        // is a positional query, so it is not enough to know that both files define the name.
        let source = "#define FEATURE 2\n#include \"config.h\"\nint x = FEATURE;\n";
        let (index, tree) = analysed(
            &[("/p/config.h", "#define FEATURE 1\n")],
            "/p/main.cpp",
            source,
        );
        let root = tree.get_red_root();

        let found = super::macro_across_files(
            &index,
            &root,
            Path::new("/p/main.cpp"),
            at(source, "FEATURE;"),
        );
        let Known::Yes(found) = found else {
            panic!("the header was pasted after the local define: {found:?}");
        };
        assert_eq!(found.file, Path::new("/p/config.h"));
    }

    #[test]
    fn a_nested_include_is_reached() {
        let source = "#include \"middle.h\"\nint x = DEEP;\n";
        let (index, tree) = analysed(
            &[
                ("/p/middle.h", "#include \"leaf.h\"\n"),
                ("/p/leaf.h", "#define DEEP 1\n"),
            ],
            "/p/main.cpp",
            source,
        );
        let root = tree.get_red_root();

        let found =
            super::macro_across_files(&index, &root, Path::new("/p/main.cpp"), at(source, "DEEP;"));

        let Known::Yes(found) = found else {
            panic!("a define two includes down is still in force: {found:?}");
        };
        assert_eq!(found.file, Path::new("/p/leaf.h"));
    }

    #[test]
    fn an_undef_of_a_local_define_leaves_an_ordinary_identifier() {
        // The answer is not the `#define` it used to have: pointing there would send a user to a definition that is
        // not in force, which is a wrong answer rather than a missing one.
        let source = "#define MAX 1\n#undef MAX\nint x = MAX;\n";
        let (index, tree) = analysed(&[], "/p/a.cpp", source);
        let root = tree.get_red_root();

        let found =
            super::macro_across_files(&index, &root, Path::new("/p/a.cpp"), at(source, "MAX;"));

        assert!(
            matches!(found, Known::Unknown(UnknownReason::UndefinedHere(_))),
            "an `#undef` above the use settles it: {found:?}"
        );
    }

    #[test]
    fn an_undef_of_a_headers_define_also_counts() {
        // Across a file boundary, which is the case a single-file macro table cannot see at all: the `#undef` is
        // in the querying file and the `#define` is in the header.
        let source = "#include \"config.h\"\n#undef FEATURE\nint x = FEATURE;\n";
        let (index, tree) = analysed(
            &[("/p/config.h", "#define FEATURE 1\n")],
            "/p/main.cpp",
            source,
        );
        let root = tree.get_red_root();

        let found = super::macro_across_files(
            &index,
            &root,
            Path::new("/p/main.cpp"),
            at(source, "FEATURE;"),
        );
        assert!(
            matches!(found, Known::Unknown(UnknownReason::UndefinedHere(_))),
            "the header's define is ended by the file's own `#undef`: {found:?}"
        );
    }

    #[test]
    fn a_define_after_an_undef_is_in_force_again() {
        let source = "#define MAX 1\n#undef MAX\n#define MAX 2\nint x = MAX;\n";
        let (index, tree) = analysed(&[], "/p/a.cpp", source);
        let root = tree.get_red_root();

        let found =
            super::macro_across_files(&index, &root, Path::new("/p/a.cpp"), at(source, "MAX;"));
        let Known::Yes(found) = found else {
            panic!("the last fact is a define: {found:?}");
        };
        assert_eq!(line_of(source, found.fact.range.start_offset), 2);
    }

    #[test]
    fn a_define_inside_a_conditional_is_unknown_rather_than_guessed() {
        let source = "#if defined(USE_MAX)\n#define MAX 1\n#endif\nint x = MAX;\n";
        let (index, tree) = analysed(&[], "/p/a.cpp", source);
        let root = tree.get_red_root();

        let found =
            super::macro_across_files(&index, &root, Path::new("/p/a.cpp"), at(source, "MAX;"));
        assert!(
            matches!(found, Known::Unknown(UnknownReason::ConditionalCompilation)),
            "whether that branch was taken is not knowable here: {found:?}"
        );
    }

    #[test]
    fn an_unconditional_define_beats_a_guarded_one_after_it() {
        // The rule the declaration query uses, applied to positions: the name certainly is a macro, so refusing to
        // answer would be refusing a question that has an answer. What the guarded define might do is stated in the
        // documentation rather than turned into an `Unknown`.
        let source = "#define MAX 1\n#if defined(OTHER)\n#define MAX 3\n#endif\nint x = MAX;\n";
        let (index, tree) = analysed(&[], "/p/a.cpp", source);
        let root = tree.get_red_root();

        let found =
            super::macro_across_files(&index, &root, Path::new("/p/a.cpp"), at(source, "MAX;"));
        let Known::Yes(found) = found else {
            panic!("the unconditional define is what is certain: {found:?}");
        };
        assert_eq!(line_of(source, found.fact.range.start_offset), 0);
    }

    #[test]
    fn a_guarded_include_makes_the_answer_conditional() {
        let source = "#if defined(USE_CONFIG)\n#include \"config.h\"\n#endif\nint x = FEATURE;\n";
        let (index, tree) = analysed(
            &[("/p/config.h", "#define FEATURE 1\n")],
            "/p/main.cpp",
            source,
        );
        let root = tree.get_red_root();

        let found = super::macro_across_files(
            &index,
            &root,
            Path::new("/p/main.cpp"),
            at(source, "FEATURE;"),
        );
        assert!(
            matches!(found, Known::Unknown(UnknownReason::ConditionalCompilation)),
            "the only path to the define goes through an `#if`: {found:?}"
        );
    }

    #[test]
    fn a_name_no_one_defines_is_not_declared_here() {
        let source = "int x = NOT_A_MACRO;\n";
        let (index, tree) = analysed(&[], "/p/a.cpp", source);
        let root = tree.get_red_root();

        let found = super::macro_across_files(
            &index,
            &root,
            Path::new("/p/a.cpp"),
            at(source, "NOT_A_MACRO;"),
        );
        assert!(
            matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
            "the index is a subset of the translation unit, so this is not a definite no: {found:?}"
        );
    }

    #[test]
    fn a_cursor_that_is_not_on_a_name_has_nothing_to_look_up() {
        let source = "#define MAX 1\nint x = MAX + 1;\n";
        let (index, tree) = analysed(&[], "/p/a.cpp", source);
        let root = tree.get_red_root();

        let found =
            super::macro_across_files(&index, &root, Path::new("/p/a.cpp"), at(source, "+ 1;"));
        assert!(
            matches!(found, Known::Unknown(UnknownReason::UnparsableName)),
            "the cursor is on an operator: {found:?}"
        );
    }

    #[test]
    fn a_cycle_of_includes_terminates() {
        // Two headers that include each other, both defining the name: the walk expands a file once per query, so
        // it ends instead of growing a chain for ever.
        let source = "#include \"a.h\"\nint x = SHARED;\n";
        let (index, tree) = analysed(
            &[
                ("/p/a.h", "#include \"b.h\"\n#define SHARED 1\n"),
                ("/p/b.h", "#include \"a.h\"\n"),
            ],
            "/p/main.cpp",
            source,
        );
        let root = tree.get_red_root();

        let found = super::macro_across_files(
            &index,
            &root,
            Path::new("/p/main.cpp"),
            at(source, "SHARED;"),
        );
        let Known::Yes(found) = found else {
            panic!("a cycle must not stop the define being found: {found:?}");
        };
        assert_eq!(found.file, Path::new("/p/a.h"));
    }

    #[test]
    fn an_undef_in_a_header_is_reached_like_a_define() {
        // The symmetric case, and the reason `#undef` is a fact rather than a note: the fact that settles the
        // question can be in either file.
        let source = "#include \"config.h\"\n#include \"cleanup.h\"\nint x = FEATURE;\n";
        let (index, tree) = analysed(
            &[
                ("/p/config.h", "#define FEATURE 1\n"),
                ("/p/cleanup.h", "#undef FEATURE\n"),
            ],
            "/p/main.cpp",
            source,
        );
        let root = tree.get_red_root();

        let found = super::macro_across_files(
            &index,
            &root,
            Path::new("/p/main.cpp"),
            at(source, "FEATURE;"),
        );
        assert!(
            matches!(found, Known::Unknown(UnknownReason::UndefinedHere(_))),
            "the later header undefines it: {found:?}"
        );
    }
}

/// The name index against the scan it replaced: the same questions, asked of the same index, answered both ways.
///
/// The inverted index is derived data, and derived data has one failure that no ordinary test finds — it drifts
/// from what it was derived from after some particular sequence of edits. So this builds a corpus that has every
/// kind of collision (one name in many files, one name in many scopes, a name only the cooked reading declares),
/// mutates it the way a session does (forget, re-insert edited, cook, forget the cooking), and after **every**
/// step asserts that each name query equals the brute-force answer over `summaries()`.
#[cfg(test)]
mod name_index_agrees_with_the_scan {
    use super::*;
    use crate::cache::SummaryKey;
    use crate::index::summarize;

    const WORDS: [&str; 6] = ["Widget", "size", "run", "Gadget", "count", "widest"];

    /// A small deterministic generator: the corpus has to be the same on every machine and every run.
    struct Lcg(u64);

    impl Lcg {
        fn next(&mut self, below: usize) -> usize {
            self.0 = self
                .0
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            ((self.0 >> 33) as usize) % below
        }
    }

    fn source_of(number: usize, generator: &mut Lcg) -> String {
        let mut text = String::new();
        for _ in 0..generator.next(3) {
            text.push_str(&format!(
                "#include \"f{}.h\"\n",
                generator.next(number.max(1))
            ));
        }
        text.push_str(&format!("#define DECL{number}(n) struct n {{ int v; }};\n"));
        text.push_str(&format!("DECL{number}(Made{})\n", generator.next(4)));
        text.push_str(&format!("namespace ns{} {{\n", generator.next(3)));
        for _ in 0..1 + generator.next(3) {
            let class = WORDS[generator.next(WORDS.len())];
            let member = WORDS[generator.next(WORDS.len())];
            text.push_str(&format!(
                "struct {class} {{ int {member}; void {member}2(); }};\n"
            ));
        }
        text.push_str("}\n");
        text.push_str(&format!("int {};\n", WORDS[generator.next(WORDS.len())]));
        text.push_str(&format!(
            "void fn{number}() {{ int {}; }}\n",
            WORDS[generator.next(WORDS.len())]
        ));
        text
    }

    fn file(index: &mut ProjectIndex, number: usize, source: &str) {
        let path = format!("/p/f{number}.h");
        let mut summary = summarize(Path::new(&path), source, SummaryKey::new(number as u64, 0));
        for include in &mut summary.includes {
            include.resolved = Some(PathBuf::from(format!("/p/{}", include.spelling)));
        }
        index.insert(summary);
    }

    fn cook(index: &mut ProjectIndex, number: usize, source: &str) {
        let path = format!("/p/f{number}.h");
        let (tokens, _) = cpp_parser::lex(source, &cpp_parser::LexerConfig::default());
        let rendered = crate::preprocess::cooked::cook(source, &tokens).render();
        let provider = crate::MemoryFiles::new();
        let config = crate::CompilerConfig::default();
        let indexed = crate::FileIndexer::new(&provider, &config).index_rendering(
            Path::new(&path),
            &rendered,
            SummaryKey::new(number as u64, 0),
        );
        index.insert_cooked(Path::new(&path), indexed.into());
    }

    type Row = (PathBuf, String, Option<String>, usize, IncludeVisibility);

    fn row(file: &Path, fact: &DeclFact, visibility: IncludeVisibility) -> Row {
        (
            file.to_path_buf(),
            fact.name.clone(),
            fact.scope.clone(),
            fact.range.start_offset,
            visibility,
        )
    }

    /// Every fact a query can see, with the raw-then-cooked deduplication, the way the per-file scan did it.
    fn scanned(index: &ProjectIndex, from: &Path, accepts: impl Fn(&DeclFact) -> bool) -> Vec<Row> {
        let visible: HashMap<String, IncludeVisibility> =
            index.visible_files(from).into_iter().collect();
        let mut rows = Vec::new();

        for summary in index.summaries() {
            let Some(visibility) = visible.get(&normalize(&summary.path)).copied() else {
                continue;
            };
            let raw: Vec<&DeclFact> = summary
                .declarations
                .iter()
                .filter(|fact| accepts(fact))
                .collect();
            rows.extend(raw.iter().map(|fact| row(&summary.path, fact, visibility)));

            for fact in index
                .cooked_declarations(&summary.path)
                .into_iter()
                .flatten()
                .filter(|fact| accepts(fact))
            {
                if !raw
                    .iter()
                    .any(|known| known.name == fact.name && known.kind == fact.kind)
                {
                    rows.push(row(&summary.path, fact, visibility));
                }
            }
        }

        rows
    }

    fn rows(found: &[VisibleDeclaration<'_>]) -> Vec<Row> {
        found
            .iter()
            .map(|found| row(&found.file, found.fact, found.visibility))
            .collect()
    }

    /// The workspace search as it was written before the index: every declaration of every file.
    fn symbols_by_scanning(
        index: &ProjectIndex,
        query: &str,
        limit: usize,
    ) -> Vec<(PathBuf, String, Option<String>, usize)> {
        let wanted = query.trim().to_lowercase();
        let mut matches: Vec<(usize, String, String, PathBuf, &DeclFact)> = Vec::new();

        for summary in index.summaries() {
            let raw: Vec<&DeclFact> = summary
                .declarations
                .iter()
                .filter(|fact| !fact.local)
                .collect();
            let fresh: Vec<&DeclFact> = index
                .cooked_declarations(&summary.path)
                .into_iter()
                .flatten()
                .filter(|fact| {
                    !fact.local
                        && !raw
                            .iter()
                            .any(|known| known.name == fact.name && known.kind == fact.kind)
                })
                .collect();

            for fact in raw.into_iter().chain(fresh) {
                let qualified = fact.qualified_name();
                let Some(rank) = rank_of(&qualified, &fact.name, &wanted) else {
                    continue;
                };
                let qualified = qualified.to_lowercase();
                let name = match fact.name.is_empty() {
                    false => fact.name.to_lowercase(),
                    true => qualified
                        .rsplit("::")
                        .next()
                        .unwrap_or_default()
                        .to_string(),
                };
                matches.push((rank, name, qualified, summary.path.clone(), fact));
            }
        }

        matches.sort_by(|one, two| {
            one.0
                .cmp(&two.0)
                .then_with(|| one.1.cmp(&two.1))
                .then_with(|| one.2.cmp(&two.2))
                .then_with(|| one.3.cmp(&two.3))
        });
        matches
            .into_iter()
            .take(limit)
            .map(|(_, _, _, file, fact)| {
                (
                    file,
                    fact.name.clone(),
                    fact.scope.clone(),
                    fact.range.start_offset,
                )
            })
            .collect()
    }

    fn check(index: &ProjectIndex, files: usize, step: &str) {
        let asked_from: Vec<PathBuf> = (0..files)
            .step_by(3)
            .map(|n| PathBuf::from(format!("/p/f{n}.h")))
            .collect();

        for from in &asked_from {
            for word in WORDS.iter().copied().chain([
                "Made0",
                "Made3",
                "nothing",
                "ns0::Widget",
                "::size",
                "ns1::Gadget",
            ]) {
                assert_eq!(
                    rows(&index.files_declaring(word, from)),
                    scanned(index, from, |fact| matches(fact, word)),
                    "{step}: files_declaring({word:?}) from {from:?}"
                );
            }
            for scope in [
                "ns0",
                "ns1",
                "ns2",
                "ns0::Widget",
                "ns1::Gadget",
                "ns2::size",
                "nowhere",
            ] {
                assert_eq!(
                    rows(&index.declarations_in(scope, from)),
                    scanned(index, from, |fact| fact.scope.as_deref() == Some(scope)),
                    "{step}: declarations_in({scope:?}) from {from:?}"
                );
            }
        }

        for query in [
            "w",
            "wid",
            "Widget",
            "size",
            "ma",
            "made",
            "run2",
            "ns0::wid",
            "ns1::Gadget::si",
            "Widget::",
            "::widget",
            "ns0::",
            "zzz",
            "  count ",
            "e",
        ] {
            for limit in [1, 4, 1000] {
                let found: Vec<_> = index
                    .symbols_matching(query, limit)
                    .into_iter()
                    .map(|symbol| {
                        (
                            symbol.file,
                            symbol.fact.name,
                            symbol.fact.scope,
                            symbol.fact.range.start_offset,
                        )
                    })
                    .collect();
                assert_eq!(
                    found,
                    symbols_by_scanning(index, query, limit),
                    "{step}: symbols_matching({query:?}, {limit})"
                );
            }
        }

        let defining: Vec<PathBuf> = index
            .summaries()
            .filter(|summary| {
                summary
                    .macros
                    .iter()
                    .any(|fact| fact.name == "DECL3" && fact.kind.is_definition())
            })
            .map(|summary| summary.path.clone())
            .collect();
        assert_eq!(
            index.files_defining_macro("DECL3"),
            defining,
            "{step}: files_defining_macro"
        );
    }

    /// A name declared thousands of times is cut at the limit rather than ordered — and the cut is deterministic.
    #[test]
    fn a_name_declared_everywhere_answers_the_first_hits_in_file_order() {
        let mut index = ProjectIndex::new();
        for number in 0..POPULAR_NAME + 50 {
            file(
                &mut index,
                number,
                &format!("struct C{number} {{ void run(); }};\n"),
            );
        }

        let found = index.symbols_matching("run", 10);
        assert_eq!(found.len(), 10);
        assert_eq!(
            found,
            index.symbols_matching("run", 10),
            "the same answer twice"
        );
        assert!(
            found.iter().all(|symbol| {
                let number: usize = symbol.file.to_string_lossy()[4..]
                    .trim_end_matches(".h")
                    .parse()
                    .unwrap();
                number < 10
            }),
            "the cut takes the files in the order the index saw them: {found:?}"
        );
    }

    #[test]
    fn after_every_kind_of_edit() {
        const FILES: usize = 24;
        let mut generator = Lcg(7);
        let mut sources: Vec<String> = Vec::new();
        let mut index = ProjectIndex::new();

        for number in 0..FILES {
            sources.push(source_of(number, &mut generator));
            file(&mut index, number, &sources[number]);
        }
        check(&index, FILES, "after building");

        for number in (0..FILES).step_by(2) {
            cook(&mut index, number, &sources[number]);
        }
        check(&index, FILES, "after cooking half of them");
        // The corpus is not vacuous: the collisions the checks are about are really there.
        assert!(
            index.symbols_matching("widget", 1000).len() > 10,
            "one name, many files and scopes"
        );
        assert!(
            index
                .symbols_matching("made", 1000)
                .iter()
                .any(|symbol| symbol.fact.name.starts_with("Made")),
            "a name only the cooked reading declares"
        );
        assert!(
            !index
                .declarations_in("ns0", Path::new("/p/f21.h"))
                .is_empty()
        );

        // An edit, as a session does one: the summary is replaced under the same key and the reading is dropped.
        for number in [3, 4, 11] {
            index.forget(Path::new(&format!("/p/f{number}.h")));
            sources[number] = source_of(number + 100, &mut generator);
            file(&mut index, number, &sources[number]);
        }
        check(&index, FILES, "after forgetting and re-reading three files");

        // A replacement under a *different* key (the key is made from the text) drops the reading with it.
        let path = Path::new("/p/f6.h");
        sources[6].push_str(
            "int rekeyed;
",
        );
        let mut summary = summarize(path, &sources[6], SummaryKey::new(999, 0));
        for include in &mut summary.includes {
            include.resolved = Some(PathBuf::from(format!("/p/{}", include.spelling)));
        }
        index.insert(summary);
        assert!(
            index.cooked_declarations(path).is_none(),
            "the reading described a different key"
        );
        check(&index, FILES, "after a re-key");

        for number in [0, 2, 8] {
            index.forget_cooked(Path::new(&format!("/p/f{number}.h")));
        }
        check(&index, FILES, "after forgetting three readings");

        cook(&mut index, 8, &sources[8]);
        cook(&mut index, 8, &sources[8]);
        check(&index, FILES, "after cooking one twice");

        for number in 0..FILES {
            index.forget(Path::new(&format!("/p/f{number}.h")));
        }
        assert_eq!(
            index.distinct_names(),
            0,
            "an index with no files has no names"
        );
        assert!(index.symbols_matching("w", 10).is_empty());
    }
}
/// **What a template-id's own arguments do to the type its declaration wrote.**
///
/// `template <class T> constexpr T pi = T(3.14159);` declares a type spelled **`T`**, and `pi<double>` names that
/// declaration with `double` written for it. Without this, the type of a use of a variable template was the
/// parameter's own name — measured: `double x = pi<double>;` answered `T`, which is not a missing answer but a wrong
/// one, because nothing in the answer says the file did not write it.
///
/// The pairing is positional and both halves already exist: the declaration's template parameter names — through
/// [`NamedDeclaration::parameters_of`], which reads `DeclFact::parameters` for a declaration in another file and walks
/// this tree for one in the file being edited — and the arguments the **use** wrote, through the same
/// `written_template_arguments` the call path uses. Nothing is invented here. When either side is empty the type is
/// returned untouched, which is the ordinary case and the reason this is a pass-through rather than a step in the
/// chain: `v.front` on a `std::vector<int>` is substituted from the *object's* type, which is a different question
/// with a different source of arguments.
fn substituted_at_the_use(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    expression: &cpp_parser::CppSyntaxNode,
    named: &NamedDeclaration,
    type_of: Type,
) -> Type {
    let arguments = written_template_arguments(expression);
    if arguments.is_empty() {
        return type_of;
    }

    let (names, _) = named.parameters_of(index, scopes, root, path);
    if names.is_empty() {
        return type_of;
    }

    // **And what a parameter the use did not write stands for.** `twice<float>` writes one argument for
    // `template <class T, class U = T>`, so the second meaning is the first argument — see
    // [`crate::TypeSubstitutions::with_defaults`]. The defaults are written in the declaration's own parameter names
    // (`U = T`), so each one is substituted with what the use wrote before it stands for anything; a default that
    // names itself is left alone by `TypeSubstitutions::get`.
    let written_defaults = named.parameter_defaults_of(index, root);
    let written_arguments: Vec<Type> = arguments.clone();
    let mut defaults: Vec<Type> = Vec::with_capacity(written_defaults.len());
    for default in &written_defaults {
        if default.trim().is_empty() {
            defaults.push(Type::builtin(""));
            continue;
        }
        let parsed = parse_type_spelling(default);
        defaults.push(
            parsed.substituted(&crate::sema::types::TypeSubstitutions::new(
                &names,
                &written_arguments,
            )),
        );
    }

    let substitutions =
        crate::sema::types::TypeSubstitutions::with_defaults(&names, &written_arguments, &defaults);
    type_of.substituted(&substitutions)
}
/// **An argument spelling as the pattern comparison should see it**: a decidable compiler builtin, folded.
///
/// `enable_if<true, _Ty>` is a pattern with a literal in it, and the uses that select it are written
/// `enable_if<__is_same(_Ty, _Uty), _Ty>` — so the comparison has to be against what the builtin *answers* rather
/// than against how it is spelled. [`crate::sema::builtins`] decides the ones the written arguments settle
/// (`__is_same(int, int)` is `true`, `__is_pointer(int*)` is `true`) and leaves the rest open
/// (`__is_constructible(T, U)` is a question about a class body, and half of one is not in front of this layer).
///
/// An undecided builtin is returned **unchanged**, so it compares equal to nothing except its own spelling — which
/// is what it did before this existed. The fold can therefore only add the matches that are true: it never removes
/// one that was right, and it never invents one, which is the rule this whole matcher follows.
fn folded_for_matching(argument: &str) -> String {
    crate::sema::builtins::folded(argument)
}
/// **The class and member an alias template's spelling stands for** — and `None` when it is not one.
///
/// This is the step a comment in this file has been referring to as `the_alias_behind` since long before it existed.
/// `template <bool _Test, class _Ty> using enable_if_t = typename enable_if<_Test, _Ty>::type;` is stored as the
/// spelling after its `=`, so `enable_if_t<__is_same(int, int), double>` becomes
/// `typename enable_if<__is_same(int, int), double>::type` once the alias's own parameters are replaced — and what
/// that *names* is the member `type` of the class `enable_if<__is_same(int, int), double>`.
///
/// Two answers, in one pair: the class the member is looked up in, and the member's name. A target with no `::` in it
/// — `template <class _Ty> using ptr = _Ty*;` — is not a member of anything, and that case is answered by the caller
/// parsing the substituted spelling; the member name is empty then, which is how it says so.
fn the_alias_behind(
    index: &ProjectIndex,
    declaring: &Path,
    written: &str,
) -> Option<(String, String)> {
    let (head, rest) = written.split_once('<')?;
    let inside = rest.trim_end().strip_suffix('>')?;
    let Known::Yes(found) = index.definition(head.trim(), declaring) else {
        return None;
    };
    if found.fact.kind != crate::DeclKind::Type {
        return None;
    }

    let target = found.fact.type_of.as_deref()?;
    let arguments = crate::sema::builtins::split_arguments(inside);
    let substituted =
        crate::sema::types::substituted_spelling(target, &found.fact.parameters, &arguments);

    // `typename enable_if<_Test, _Ty>::type` — the last `::` separates the class from the member it names.
    let substituted = substituted
        .trim()
        .trim_start_matches("typename ")
        .trim()
        .trim_start_matches("class ")
        .trim();
    let (named, member) = substituted.rsplit_once("::")?;

    Some((named.trim().to_string(), member.trim().to_string()))
}

/// **`std::vector<int>`'s members, with `T` written through as `int`.**
///
/// A member's fact records the spelling its **class** wrote — `void push_back(T value)`, `T& front()` — and every
/// consumer of the list reads those spellings: completion offers the parameters, hover shows them, `param-type-check`
/// and `argument-count` compare against them. For an instantiated use they are wrong, and the consequence is silence:
/// `std::vector<int>::push_back("text")` is not reported, because `T value` is a parameter neither check can classify.
///
/// The substitution is `sema::types::substituted_spelling` — the same function that makes a member's **return** type
/// come out as `int&` — so this is the arguments reaching the member list, not a second implementation of anything.
///
/// # The parameter names come from the **fact**, and that is a correction
///
/// They used to be read out of the class's file — `template_parameters_before(text, offset)` — which required a
/// reader and the file's **own** text: the fact's offset is the file's, while a `FileView` may be of a *rendering*
/// whose offsets are shifted by everything the cook deleted. `view.written_text().unwrap_or(&view.source)` was the
/// guard, and it is only right when the caller happened to hand over a written view. `Session::members_of` does;
/// `SemanticModel::members_of` — which is what every **check** goes through — hands over the rendering, so
/// `written_text()` was `None`, the guard fell through to the rendering, no `template <…>` was found at the offset,
/// and the substitution was silently skipped.
///
/// Measured on the report this was written for: `std::vector<int> anotherVec; anotherVec.push_back("123131");` on a
/// class declared `void push_back(const value_type& __x);` with `using value_type = _Tp;` — the parameter stayed
/// `const value_type&`, `convertible_to(char*, const value_type&)` answered `Unknown`, and the check said nothing.
/// `DeclFact::parameters` is the class's parameter names, recorded by `declared_template_parameters_with` when the
/// fact was built, so the answer needs no reader at all — and `SemanticModel` and `Session` cannot disagree about it.
pub fn substituted_members(
    index: &ProjectIndex,
    from: &Path,
    class: &str,
    listed: Known<MemberList>,
) -> Known<MemberList> {
    let Known::Yes(mut list) = listed else {
        return listed;
    };
    let Some((base, arguments)) = split_template_arguments(class) else {
        return Known::Yes(list);
    };
    let Some(declared) = index
        .files_declaring(&base, from)
        .into_iter()
        .find(|declared| declared.fact.kind == crate::DeclKind::Type)
    else {
        return Known::Yes(list);
    };
    let mut names = declared.fact.parameters.clone();
    if names.is_empty() {
        return Known::Yes(list);
    }

    // **A declaration with a defaulted parameter is written without it at the use.** `std::vector<int>` writes one
    // argument for `template <class _Tp, class _Alloc = allocator<_Tp>>` — two names — and `substituted_spelling`
    // refuses a positional substitution whose two sides do not line up (`names.len() != arguments.len()` returns the
    // text unchanged). So both sides are cut to the shorter one: the arguments written are the first parameters, in
    // order, which is what a positional substitution means. Measured on the real `<vector>`: without this,
    // `push_back("123131")` on a `std::vector<int>` stayed silent while the one-parameter fixture beside it reported.
    let mut arguments = arguments;
    names.truncate(arguments.len());
    arguments.truncate(names.len());
    if names.is_empty() {
        return Known::Yes(list);
    }

    // **The class's own aliases, expanded before the arguments go in.** `std::vector` declares its parameter as
    // `void push_back(const value_type& __x);` with `using value_type = _Tp;` in the class — so substituting
    // `_Tp → int` alone leaves the word `value_type`, which nothing in this layer can compare: measured on
    // `std::vector<int> anotherVec; anotherVec.push_back("123131");`, the target stayed `const value_type&`,
    // `convertible_to(const char[7], const value_type&)` answered `Unknown`, and a check that cannot compare says
    // nothing — the report. An alias's target is in its own fact (`DeclFact::type_of` is the target for an alias,
    // see `declared_alias_target`), and the aliases of *this* class are already in the list being substituted,
    // which is why no second lookup is needed.
    //
    // A plain `using value_type = _Tp;` inside a class template records the **class's** parameters as its own
    // (`declared_template_parameters_with` pairs the `template <…>` head with the declaration it introduces), so
    // there is deliberately no `parameters.is_empty()` test here: the alias that matters most has one.
    let mut alias_names: Vec<String> = Vec::new();
    let mut alias_targets: Vec<String> = Vec::new();
    for member in list
        .members
        .iter()
        .filter(|member| member.depth == 0 && member.fact.kind == crate::DeclKind::Type)
    {
        let Some(target) = member.fact.type_of.clone() else {
            continue;
        };
        // **Not the alias itself**: `type_of` is the target, and a member whose target names itself would make
        // `value_type` → `value_type` a rewrite that changes nothing but costs a pass.
        if target == member.fact.name {
            continue;
        }
        alias_names.push(member.fact.name.clone());
        alias_targets.push(target);
    }

    // **An alias's own target is not an alias to expand.** `std::shared_ptr`'s `element_type` is written
    // `using element_type = typename __shared_ptr<_Tp>::element_type;`, so the target contains its own name and
    // replacing that name with the target doubles the prefix —
    // `typename __shared_ptr<Resource>::typename __shared_ptr<Resource>::element_type`, measured. The member's own
    // `type_of` *is* the target, so the expansion is a step for the other members only.
    let declares_an_alias = |member: &ProjectMember| {
        member.fact.kind == crate::DeclKind::Type && alias_names.contains(&member.fact.name)
    };
    for member in list
        .members
        .iter_mut()
        .filter(|member| !declares_an_alias(member))
    {
        for spelling in [
            &mut member.fact.parameter_list,
            &mut member.fact.returns,
            &mut member.fact.type_of,
        ]
        .into_iter()
        .flatten()
        {
            if !alias_names.is_empty() {
                *spelling = crate::sema::types::substituted_spelling(
                    spelling,
                    &alias_names,
                    &alias_targets,
                );
            }
        }
    }
    for member in &mut list.members {
        for spelling in [
            &mut member.fact.parameter_list,
            &mut member.fact.returns,
            &mut member.fact.type_of,
        ]
        .into_iter()
        .flatten()
        {
            *spelling = crate::sema::types::substituted_spelling(spelling, &names, &arguments);
        }
    }
    Known::Yes(list)
}

/// **Split `std::vector<int>` into its name and its arguments** — `("std::vector", ["int"])`.
///
/// `None` when there is no top-level `<…>` at the end: a plain class name has no arguments to substitute, and returning
/// an empty list rather than `None` would make `std::vector<>` and `std::vector` indistinguishable at the call site.
fn split_template_arguments(spelling: &str) -> Option<(String, Vec<String>)> {
    let spelling = spelling.trim();
    let open = spelling.find('<')?;
    let close = spelling.rfind('>')?;
    if close < open || close + 1 != spelling.len() {
        return None;
    }
    let base = spelling[..open].trim().to_string();
    let mut arguments: Vec<String> = Vec::new();
    let mut depth = 0i32;
    let mut current = String::new();
    for character in spelling[open + 1..close].chars() {
        match character {
            '<' | '(' | '[' => depth += 1,
            '>' | ')' | ']' => depth -= 1,
            ',' if depth == 0 => {
                arguments.push(current.trim().to_string());
                current.clear();
                continue;
            }
            _ => {}
        }
        current.push(character);
    }
    if !current.trim().is_empty() {
        arguments.push(current.trim().to_string());
    }
    Some((base, arguments))
}

/// **The class of the definition the cursor is in, when the declarator is qualified** — `Source` for `int Source::GetLine(…)`.
///
/// The question this answers is the language's: **a function defined out of class is a member of that class**, so its
/// body's unqualified lookup includes the class's members. The class is usually in another file (`a.cpp` defines
/// what `a.h` declares), so no scope in *this* file's tree can offer them — the members come from the index, and the
/// only thing that has to be read from the tree is **which** class the declarator names.
///
/// # Where the name is written, and why it is read in two places
///
/// The grammar puts the qualified name in one of two places, and both are the same declaration:
///
/// ```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
/// ```
///
/// In the first the name is written straight against the parameter list, and since **a type in a declaration is never
/// followed by `(`** the declaration rule knows it is the declarator's own name. In the second `Box` is followed by
/// `<`, which a declaration cannot tell from a return type, so the whole spelling stays in the specifier sequence and
/// is read there (the same two shapes [`crate::sema::scopes`] reads for the scope tree).
///
/// `None` for anything else — a cursor outside a declaration, an ordinary declarator, or a qualifier with more than
/// one level (which would need the nested class's own file, and is left to the scope chain).
fn the_class_a_definition_belongs_to(
    root: &cpp_parser::CppSyntaxNode,
    offset: usize,
) -> Option<String> {
    use cpp_parser::CppAstNode;

    for declaration in root.descendants() {
        let range = declaration.text_range();
        if usize::from(range.start()) > offset || offset >= usize::from(range.end()) {
            continue;
        }
        let Some(declaration) = cpp_parser::CppDeclaration::cast(declaration.clone()) else {
            continue;
        };
        // **One reader for "what is this declaration's own name"**, the same one the scope tree uses — see
        // [`crate::sema::scopes::the_qualified_name_of_a_declaration`]. Two readers of the same two shapes is how the
        // completion and the scope tree came to disagree about an out-of-class definition in the first place.
        let Some((qualifier, _)) =
            crate::sema::scopes::the_qualified_name_of_a_declaration(declaration.syntax())
        else {
            continue;
        };
        // The class is the **last segment of the qualifier** — `Source` for `Source::GetLine`, and `Inner` for
        // `Outer::Inner::deep` (whose innermost class is the one the declaration belongs to). A segment with `::`
        // left in it is a qualifier this file cannot name as a class, which is the answer `None` gives.
        let before = qualifier.trim_end();
        let start = before
            .rfind(|character: char| {
                !(character.is_alphanumeric() || matches!(character, '_' | ':'))
            })
            .map(|boundary| boundary + 1)
            .unwrap_or(0);
        let class = before[start..].trim();
        if !class.is_empty() && !class.contains("::") {
            return Some(class.to_string());
        }
    }
    None
}

/// **A qualified spelling without its namespace** — the name the class is declared under, with any template arguments
/// kept.
///
/// The last `::` **outside angle brackets** is the boundary: `std::basic_string<char>` → `basic_string<char>` (the alias
/// target of `std::string`, which lives in the inline namespace `std::__cxx11`), and `std::vector<LuaSyntaxNode>` →
/// `vector<LuaSyntaxNode>`. Stripping arguments — which an earlier version did by taking `rsplit("::")`'s last piece and
/// then skipping anything with a `<` — lost the substitution and answered the *unparameterized* class.
fn without_the_namespace(class: &str) -> String {
    let mut depth = 0usize;
    let mut boundary = 0usize;
    let bytes = class.as_bytes();
    let mut index = 0usize;
    while index + 1 < bytes.len() {
        match bytes[index] {
            b'<' => depth += 1,
            b'>' => depth = depth.saturating_sub(1),
            b':' if depth == 0 && bytes[index + 1] == b':' => boundary = index + 2,
            _ => {}
        }
        index += 1;
    }
    class[boundary.min(class.len())..].to_string()
}

/// **Is this a template parameter's *name*?** — an identifier, not the keyword that introduced it.
///
/// A fact's `parameters` is a list of names (`["_Ty", "_Alloc"]`), and it used to be able to carry the *keywords*
/// instead — one measured declaration of `std::vector` in MSVC's `<vector>` recorded `["class", "class"]`, because the
/// name was read as "the last word of the parameter" and an **unnamed** parameter's last word is the keyword. That
/// list substitutes nothing and, worse, *won* the choice of which declaration's parameters to use, which is how
/// `std::vector<MarkEvent>::operator[]` answered `_Ty&` after two rounds of fixing the substitution itself.
///
/// The fact is fixed where it is built now (`template_parameters_in` reads the name from the **tokens**, so a keyword
/// cannot become one, and an unnamed parameter is an **empty slot** that keeps the arguments aligned). This remains
/// as the shape check a substitution needs: a list with nothing nameable is a list it cannot use.
fn is_a_parameter_name(name: &str) -> bool {
    !name.is_empty()
        && !matches!(
            name,
            "class" | "typename" | "struct" | "union" | "enum" | "concept"
        )
        && name
            .chars()
            .all(|character| character.is_alphanumeric() || character == '_')
}

/// **Can a substitution be driven by this list?** — at least one name, and every entry either a name or an empty slot.
///
/// The empty entry is a slot rather than a fact: an unnamed parameter (`template <typename, class T>`) cannot be
/// substituted into, because no spelling of a body equals the empty string, and its presence keeps the *later*
/// arguments aligned with their names. So a list that has names beside its slots is exactly a list a substitution can
/// use — and one that is all slots (`template <typename, typename> class vector;`) has nothing to substitute.
fn lists_usable_parameter_names(names: &[String]) -> bool {
    !names.is_empty()
        && names.iter().any(|name| !name.is_empty())
        && names
            .iter()
            .all(|name| name.is_empty() || is_a_parameter_name(name))
}

/// **`element_type` read through the member that names the base** — `using _Mybase = _Ptr_base<_Ty>;` and then
/// `class shared_ptr : public _Mybase`.
///
/// `members_of` walks a base clause, and a base clause that names an **alias** is not a class: measured on a fixture
/// with MSVC's own shape, `members_of("Handle<Item>")` listed `_Mybase: Some("Holder<Item>")`, `element_type` (from the
/// re-exposing `using typename _Mybase::element_type;`, with no type of its own) and `operator->` — and *none* of the
/// base's members. The alias's `type_of` is the base's spelling, already substituted with the use's arguments, so it is
/// the step this walk needs: one level of alias, then the same question.
fn an_element_type_through_the_members(
    index: &ProjectIndex,
    scopes: &crate::ScopeTree,
    root: &cpp_parser::CppSyntaxNode,
    path: &Path,
    class: &str,
    parameters: &[String],
    arguments: &[String],
    depth: usize,
) -> Option<String> {
    if depth > 3 {
        return None;
    }
    let Known::Yes(members) = members_of(index, scopes, root, path, class) else {
        if crate::probes::inference() {
            eprintln!("[inference] element_type: no member list for {class}");
        }
        return None;
    };

    // The class's own `element_type`/`value_type`, when the declaration that has the name also has a type.
    for name in ["element_type", "value_type"] {
        let Some(fact) = members
            .members
            .iter()
            .filter(|member| member.fact.name == name)
            .map(|member| &member.fact)
            .find(|fact| fact.type_of.is_some())
        else {
            continue;
        };
        let Some(written) = fact.type_of.as_deref() else {
            continue;
        };
        let substituted = crate::sema::types::substituted_spelling(written, parameters, arguments);
        let target = base_type_name(&substituted).to_string();
        if crate::probes::inference() {
            eprintln!(
                "[inference] element_type: {class}::{name} wrote {written:?} -> {substituted:?} -> {target:?}"
            );
        }
        if !target.is_empty()
            && !parameters.iter().any(|parameter| parameter == &target)
            && target != base_type_name(class)
        {
            return Some(target);
        }
    }

    // A member of kind `Type` whose target names another class — the alias of the base.
    for member in &members.members {
        if member.fact.kind != crate::DeclKind::Type {
            continue;
        }
        let Some(target) = member.fact.type_of.as_deref() else {
            continue;
        };
        if base_type_name(target) == base_type_name(class) {
            continue;
        }
        // **The target is written inside the class's own namespace and carries the class's arguments**: `_Mybase` is
        // `_Ptr_base<_Ty>` in `std`, and the declaration is filed as `std::_Ptr_base`. Asking the bare spelling found
        // nothing on a real project, and asking it *with* arguments found a class with no members — measured, in this
        // order, which is why both parts are removed here and the arguments stay in the substitution.
        let bare_target = without_arguments(target.trim()).to_string();
        let qualified = resolved_in_the_enclosing_scopes(index, scopes, path, class, &bare_target);
        let qualified = resolve_aliases(index, scopes, root, path, &qualified);
        if let Some(found) = an_element_type_through_the_members(
            index,
            scopes,
            root,
            path,
            &qualified,
            parameters,
            arguments,
            depth + 1,
        ) {
            return Some(found);
        }
    }

    // And the declared base clauses, for the ones that do name a class.
    for base in bases_of(index, scopes, root, path, class)
        .value()
        .unwrap_or_default()
    {
        let base = resolved_in_the_enclosing_scopes(index, scopes, path, class, base.trim());
        let base = resolve_aliases(index, scopes, root, path, &base);
        if let Some(found) = an_element_type_through_the_members(
            index,
            scopes,
            root,
            path,
            &base,
            parameters,
            arguments,
            depth + 1,
        ) {
            return Some(found);
        }
    }

    None
}

/// **What the index's own tables cost** — the answer to [`ProjectIndex::table_accounting`].
///
/// The facts live in `summaries` and `cooked` and are counted by [`ProjectIndex::accounting`]; this is the structure
/// around them: the inverted index, the include graph, and the four memos that outlive a request. Every number is an
/// estimate with a stated method — keys, payloads, one container header each, no spare capacity — so the sum is a
/// lower bound, which is the same convention [`crate::MemoryReport`] uses.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct TableCost {
    /// The inverted index: two posting maps, the definers, and the sorted spellings.
    pub names: crate::index::names::NameIndexCost,
    /// Include edges across the project — the sum of every file's set of includers.
    pub edges: usize,
    /// The include graph and the module map, in bytes.
    pub edge_bytes: usize,
    /// Cached member lists ([`ProjectIndex::member_lists`]).
    pub member_list_entries: usize,
    /// Members across those lists.
    pub member_lists: usize,
    /// Their estimated bytes.
    pub member_list_bytes: usize,
    /// Guard verdicts remembered ([`ProjectIndex::guard_answers`]).
    pub guard_entries: usize,
    /// Their estimated bytes.
    pub guard_bytes: usize,
    /// Visibility walks remembered, one per root asked.
    pub visibility_entries: usize,
    /// Their estimated bytes.
    pub visibility_bytes: usize,
    /// Conditional-include answers remembered.
    pub condition_entries: usize,
    /// Their estimated bytes.
    pub condition_bytes: usize,
    /// The file paths held twice, by order and by identity.
    pub path_bytes: usize,
}

impl TableCost {
    /// The whole of it, in bytes.
    pub fn total(&self) -> usize {
        self.names.bytes
            + self.edge_bytes
            + self.member_list_bytes
            + self.guard_bytes
            + self.visibility_bytes
            + self.condition_bytes
            + self.path_bytes
    }
}