cpp_code_analysis 0.4.0

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

use smol_str::SmolStr;
use std::path::Path;

use crate::Marked;
use crate::cache::SummaryKey;
use crate::guard::{Branch, Region, Visibility};
use crate::macros::MacroDef;

/// The key [`TranslationUnit::entered`] compares by, and the answer to "is this the same file spelled twice".
///
/// A path reaches these layers in the spelling whoever named it used: a directory scan keeps the caller's
/// (`C:\Users\…`), an `#include` that resolved through [`crate::IncludeResolver`] is normalized (`c:/users/…`), and a
/// cache entry is found by the normalized form either way. Comparing raw spellings made the same file two files.
fn frame_key(path: &std::path::Path) -> String {
    crate::paths::normalize_path(path, cfg!(windows))
}

/// **What a declaration is written with** — the modifiers every reader used to find by searching its text.
///
/// `override` and `final` are contextual identifiers, `[[maybe_unused]]` is an attribute, and `virtual`/`constexpr` are
/// keywords inside the specifier sequence — so a consumer answering "does this declaration say `override`" had to
/// slice the declaration's text and search it (`written.contains("override")`). The bits below are that question
/// answered **once**, when the summary is built, from the tokens the walk already had in hand: every consumer of the
/// summary reads a bit instead of re-reading text, and the answer cannot drift from the file.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
pub struct DeclModifiers(u32);

impl DeclModifiers {
    pub const VIRTUAL: Self = Self(1 << 0);
    pub const OVERRIDE: Self = Self(1 << 1);
    pub const FINAL: Self = Self(1 << 2);
    pub const CONSTEXPR: Self = Self(1 << 3);
    pub const CONSTEVAL: Self = Self(1 << 4);
    pub const CONSTINIT: Self = Self(1 << 5);
    pub const STATIC: Self = Self(1 << 6);
    pub const INLINE: Self = Self(1 << 7);
    pub const EXPLICIT: Self = Self(1 << 8);
    /// `[[maybe_unused]]`, and the reader's answer that this declaration is not dead code.
    pub const MAYBE_UNUSED: Self = Self(1 << 9);
    /// `[[nodiscard]]`.
    pub const NODISCARD: Self = Self(1 << 10);
    /// A function with a variadic parameter list — `void log(const char*, ...)` or a parameter pack.
    pub const VARIADIC: Self = Self(1 << 11);
    pub const DELETED: Self = Self(1 << 12);
    pub const DEFAULTED: Self = Self(1 << 13);
    /// **A member function declared `const`** — `T sum() const`. Written after the parameter list, which is why it was
    /// missing while `constexpr` was not: the specifier sequence holds one and the declarator's suffix the other.
    pub const CONST: Self = Self(1 << 14);
    /// `volatile`, in the same position and for the same reason.
    pub const VOLATILE: Self = Self(1 << 15);
    /// A **ref-qualifier**: `void f() &` is callable only on an lvalue, `void g() &&` only on an rvalue. `noexcept` and
    /// the `&`/`&&` of a *parameter type* are not this — see `function_suffix_in`.
    pub const LVALUE_REFERENCE: Self = Self(1 << 16);
    pub const RVALUE_REFERENCE: Self = Self(1 << 17);
    /// **The declaration is a definition** — it carries a function body, or it is `= default`/`= delete`. A
    /// declaration without the bit only declares; the distinction is what a "create the definition" edit needs.
    pub const DEFINED: Self = Self(1 << 18);
    /// **`= 0`** — a pure virtual function, whose body a derived class must supply.
    pub const PURE: Self = Self(1 << 19);

    pub const fn bits(self) -> u32 {
        self.0
    }

    pub const fn from_bits(bits: u32) -> Self {
        Self(bits)
    }

    pub const fn union(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }

    pub const fn contains(self, other: Self) -> bool {
        self.0 & other.0 == other.0
    }

    pub const fn is_empty(self) -> bool {
        self.0 == 0
    }
}
/// A declaration the file writes: enough to find it, name it, and say what kind of thing it is.
///
/// Deliberately not a syntax tree and not a type: the fields are the ones a *query* needs — where to jump, what to
/// call the symbol, what to filter by, and which branch it is on.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeclFact {
    /// **Is this declaration an enumerator?** — `Red` in `enum { Red };`.
    ///
    /// A field rather than a derivation, and the measurement is why: [`DeclKind`] has one variant for "a name
    /// that holds a value", so the index used to infer an enumerator from *the absence* of a written type plus
    /// the *presence* of a scope. Both halves fail for the shape C writes most — an **anonymous** `enum { … }`
    /// whose members have no scope at all — so `WILD_FREE` in neovim's `cmdexpand.h` was drawn as a `variable`
    /// where `cmdexpand.c` used it, while the same name's declaration card said "an enumerator of (an anonymous
    /// enum)". One name, two answers, and a theme that colours an enumerator with its enumeration.
    pub enumerator: bool,
    /// The name as written, without qualification: `Widget` in `ns::Widget`.
    ///
    /// **A `SmolStr`, because this is an identifier and not a document.** Up to 22 bytes live inside the value, so an
    /// identifier that short — nearly all of them — costs no allocation and no pointer chase. A summary is made of
    /// these: measured on `EmmyLuaCodeStyle`, 486 783 declarations over 1 761 files at 517 bytes each, and the field was
    /// a `String`, i.e. a 24-byte header plus one heap block per name.
    pub name: SmolStr,
    /// The **qualified** name of the scope the declaration was written in, without the name itself: `ns::C` for a
    /// member of that class.
    ///
    /// The one field that makes a flat list of declarations indexable. A name alone does not identify a
    /// declaration — two files may each declare `Widget`, and one file may declare `f` at file scope and again as
    /// a member — so a lookup needs the scope, and the qualified spelling is the scope's identity that survives
    /// being written to disk. A [`ScopeId`] would not: it is only meaningful inside the tree it came from.
    ///
    /// `None` for a declaration at file scope, which is what distinguishes `f` from `ns::C::f`. It is also `None`
    /// for a declaration inside a construct that has no qualified name — a local in a function body, a member of an
    /// anonymous class — because those genuinely have none, and an empty string would be a name that matches
    /// nothing while looking like an answer.
    ///
    /// [`ScopeId`]: crate::ScopeId
    pub scope: Option<SmolStr>,
    /// Was this declaration written inside a **function body, a block or a lambda**?
    ///
    /// The other half of [`DeclFact::scope`], and the reason it is a field rather than something a consumer can
    /// work out: a fact whose scope is `None` is either a declaration at *file* scope — `void helper();`,
    /// `extern int errno;`, which every file that includes this one can name — or a **local**, which nothing
    /// outside its own body can name at all. The two are indistinguishable from the rest of the fact, and the
    /// difference decides answers: a name lookup that answered with another file's local would be offering a name
    /// the user cannot see, and `std::vector`'s headers alone declare thousands of them (`__first`, `__n`, `_Tp`),
    /// so the wrong answer is not a corner case — it is most of what a completion would show.
    ///
    /// `true` for a declaration whose scope chain reaches a function body, a block or a lambda, however deeply it
    /// is nested in there — a local class, a local `typedef`, a variable inside a loop inside a member function.
    /// `false` at file scope, in a namespace, and in a class body, including a member function's *declaration* —
    /// the body is what makes a declaration local, not the entity it belongs to.
    ///
    /// # What a consumer is expected to do with it
    ///
    /// The index is a per-file list of declarations, so it cannot place a local in the function it belongs to;
    /// [`crate::ProjectIndex::definition`] therefore **skips** these facts when it looks a name up across files,
    /// because the scope tree of the file being edited is the only thing that can resolve one. A consumer with the
    /// file's own scopes in hand (a completion in the open buffer) lists locals from there and never needs this
    /// field; a consumer listing *another* file's declarations uses it to leave them out.
    pub local: bool,
    pub kind: DeclKind,
    /// **The modifiers the declaration writes** — see [`DeclModifiers`]. Answered once, at index time, from the
    /// tokens; the consumers that used to search the declaration's text (`use-override`, `unused`) read a bit now.
    pub modifiers: DeclModifiers,
    /// **The parameters this function frees**, as a bit per parameter index.
    ///
    /// A bit is set when the body **certainly** frees that parameter: an unconditional `delete p;`, `free(p)`,
    /// `std::destroy_at(p)`, or a call to a function whose own fact says it frees that argument. "Unconditional" is
    /// the whole discipline — a `delete` inside an `if` is not recorded, because a caller that uses the pointer
    /// afterwards is only *sometimes* wrong, and this analysis reports only what is certain.
    ///
    /// It exists for the question a call site cannot answer from its own file: `release(p); p->x;` where `release` is
    /// declared in a header. The check that reads it is `use-after-free`, and the alternative — following the callee's
    /// body at check time — is the one thing this layer must not do (a check that could parse would pay a parse per
    /// call site).
    ///
    /// Three limits, all deliberate:
    ///
    /// ```text
    ///   one level      the frees written in this body, not the ones behind another call
    ///   parameters     `delete this;` and a freed *global* are not recorded
    ///   certainty      a conditional free is not recorded, so a call site cannot report from it
    /// ```
    ///
    /// The first is a limit of *when* the summary is built: a file's fact is written while the project is being read,
    /// so the fact of a callee in another file may not exist yet. A second pass could close it, and until then this
    /// answers the case that matters — the helper whose whole job is to free.
    pub frees: u16,
    /// The type a variable-like declaration was written with, as the file spells it.
    ///
    /// The first field in a fact that is not simply "what the file says about this name" but "what the file says
    /// about the *type* of it", and it exists for one query: `widget.size` is answered by finding `Widget` and
    /// then `size` inside it, and nothing else in a fact says how to get from `widget` to `Widget`.
    ///
    /// Three limits, all deliberate:
    ///
    /// * **As written, not resolved.** `Widget`, `ns::Widget` and `std::vector<int>` are stored as spelled, so a
    ///   consumer resolves them with the qualified-name machinery that already exists — and gets `Unknown` where
    ///   that machinery cannot go, rather than a guess.
    /// * **Only for variables, fields and parameters.** A class or a function declares no type in this sense: a
    ///   class *is* one and a function *returns* one, and those spellings live in a different part of the syntax.
    ///   `None` is the honest answer for them.
    /// * **Declaration specifiers are stripped.** `static const Widget` records `Widget`, because a specifier is
    ///   not part of the type's name and a lookup by name is what this is for. `unsigned long` survives, because
    ///   there the words *are* the type.
    pub type_of: Option<SmolStr>,
    /// The type a **function** returns, as the file spells it.
    ///
    /// The other half of [`DeclFact::type_of`], and separate from it for the reason that field's documentation
    /// gives: a class *is* a type and a function *returns* one, so `Widget make();` has no `type_of` — `make` is
    /// not a `Widget` and has no members — while its `returns` is what the *call* `make()` has. Collapsing the two
    /// would make `make.size` resolve as if the function were the object.
    ///
    /// It exists for one query: `make().size` is answered by finding what `make` returns and then `size` inside
    /// that, and nothing else in a fact says how to get from a call to a type.
    ///
    /// Same limits as `type_of`: **as written**, so a consumer resolves it with the qualified-name machinery and
    /// gets `Unknown` where that cannot go; declaration specifiers stripped (`static inline Widget make()` records
    /// `Widget`); `None` for everything that is not a function.
    ///
    /// A **trailing return type wins**, and it is the reason this cannot be read out of the specifier sequence
    /// alone: `auto make() -> Widget` spells the type after the parameter list, so the specifiers say `auto`.
    /// `None` for a return type the file does not state — `auto make() { … }` is deduced, and `auto` is not a
    /// class anything can be looked up in.
    pub returns: Option<SmolStr>,
    /// **Does the file's own text state this declaration's type across a directive?**
    ///
    /// `bits/stl_bvector.h` writes `emplace_back`'s return type as `#if __cplusplus > 201402L … reference … #else
    /// void … #endif`, and the written reading — which cannot know which branch is live, because that needs the
    /// compiler configuration a summary is deliberately not keyed by — has no single type to report: [`DeclFact::returns`]
    /// and [`DeclFact::type_of`] are `None` for such a declaration instead of one branch's answer.
    ///
    /// This flag is how a consumer tells that apart from `auto` (also `None`, and nothing to ask) and from a
    /// declaration that simply states no type. A consumer holding a **rendering** — the reading where the directive is
    /// resolved — can answer properly, and the flag is the only thing that says it is worth asking. Measured over
    /// three standard-library headers (`facts_vs_rendering`): 12 of 1589 facts disagreed with the rendering about the
    /// return type before this flag existed, every one of them this shape.
    pub split_by_a_directive: bool,
    /// The whole declaration, for a "go to definition" highlight.
    pub range: cpp_parser::SourceRange,
    /// Just the name, which is what a reference search matches. Separate from `range` for the reason
    /// [`crate::Binding`] documents: collapsing them renames whole declarations.
    pub name_range: cpp_parser::SourceRange,
    /// Was this declaration read **without a diagnostic touching it**?
    ///
    /// `false` when a parse error fell inside the declaration this fact was written in. The tokens are all there
    /// and the node is well formed — the parser is total — but the reading around it was *recovered from*, so
    /// what this declaration says is not to be trusted. This is the record 's third
    /// invariant asks for: the parser is tolerant, so the layers above have to be able to see how much was
    /// recovered.
    ///
    /// # Why per fact, and not per file
    ///
    /// Measured on the closure of `<vector>` (279 files from one compiler): **5388 of 8499** declarations come
    /// from files that do not parse cleanly, and a per-file rule would throw all of them away — including the 157
    /// `std::` types that are indexed correctly today (`std::allocator`, `std::pair`, `std::tuple`). Of those
    /// 5388, only **214 — 4% —** are marked unclean here, and the 3111 declarations of the clean files are all
    /// clean: **8285 of 8499** declarations survive the question. The question is therefore about a declaration
    /// rather than about a file, and by a factor of twenty-five.
    ///
    /// # The range the question is asked about
    ///
    /// Not the fact's own range, which is the declarator: a diagnostic in the **type** is outside the declarator
    /// and inside the declaration, and the type is what a consumer reads off `type_of`. What is asked about is
    /// the innermost declaration node containing this fact's name. Measured, that costs 108 declarations over the
    /// declarator rule (106 against 214, both against 5388 for the file), and the 108 are exactly the ones worth
    /// having: by node kind, 89 are `Declaration` and 19 are `TemplateDecl` — the type part and the template
    /// header. The looser rule, "any declaration whose range contains the name", marks **2907** — one error in a
    /// class body would condemn every member of it — which is why the innermost one is the rule.
    ///
    /// # What it does not mean
    ///
    /// `true` is **not** a promise that the declaration is right. A recovery can land badly *before* a
    /// declaration and change where it belongs: the closing `}` of a block eaten by an error turns everything
    /// after it into locals, and those declarations' own tokens are untouched, so they are clean while their
    /// *scope* is wrong. A diagnostic that falls inside no declaration at all — an unexpected token at file
    /// scope, between two declarations — marks neither of them, and neither does one that lands in a declaration
    /// the walk produced no fact for, which is what a failed declarator usually does: the fact is then missing
    /// rather than unclean. The field claims exactly one thing, and it is the one thing the parser can answer:
    /// whether a diagnostic fell inside the declaration this fact was written in.
    pub clean: bool,
    pub guard: FactGuard,
    /// **Who may name this declaration** — the access an *access specifier* gave it in the class body it was
    /// written in.
    ///
    /// `None` for everything that is not a class member, and for a member whose class body the reading could not
    /// place: there is no access level to report for a namespace's name, and a guess would be worse than the
    /// admission — a consumer that treated `None` as "public" shows a name the reader may not write, and one that
    /// treated it as "private" hides half of every library.
    ///
    /// # Why it is recorded rather than asked
    ///
    /// Because the class body is in **another file**: a completion after `w.` on a header's class holds the
    /// cursor's file and the index's facts, and the `private:` label is in the header. The fact is already the
    /// thing that crosses that boundary, so the level travels with it — one byte on disk.
    ///
    /// # What a consumer is expected to do with it
    ///
    /// Offer a member when the reader can write it, and **only then**: [`crate::completion`] leaves out a private
    /// or protected member of a class the cursor is not in. Looking a private member *up* stays possible — a jump
    /// to a declaration the reader can see in the file is not the same question as offering a name they cannot
    /// write — which is why this is a field rather than a filter applied where the fact is built.
    pub access: Option<Access>,
    /// **Is this declaration exported from the module its file declares?**
    ///
    /// A module interface unit's declarations are visible to an importer **only** if exported: `export int f();`,
    /// anything inside `export { … }`, and everything a `export namespace n { … }` holds. This field is that
    /// reading, per declaration, and it is what stops a completion from offering a name that does not compile —
    /// measured on the module fixture (`tests/fixtures/modules`), whose `mathlib::hidden_helper` is written in the
    /// interface unit and deliberately not exported: it was offered to a file that says `import mathlib;` until this
    /// field existed.
    ///
    /// `false` for a file that declares no module, where "exported" means nothing: the visibility walk applies this
    /// field **only** to files it reached through an `import`, so an ordinary translation unit's declarations are
    /// unaffected whatever this says.
    pub exported: bool,
    /// **Is this declaration the one that defines what it names** — a class with a body, a function with a body, an
    /// `enum` with enumerators?
    ///
    /// The dimension the index did not have, and the one that makes MSVC's standard library answer wrongly: a header
    /// may say `struct _Ty;` in one place and `struct _Ty { … };` in another, and **both are facts with the same name
    /// and the same scope**. A query that takes the first — `members_of`, `definition` — can take the forward
    /// declaration, which has no members and no bases, and answer "this class has no member `load`" about a class whose
    /// definition the index holds.
    ///
    /// Read from the declaration's own node at index time: a class-like or enum declaration containing a class body, a
    /// function whose declaration contains a compound statement.
    pub definition: bool,
    /// **Everything a declaration carries that most do not** — the ten fields this struct used to hold inline.
    ///
    /// # The measurement this shape exists for
    ///
    /// `size_of::<DeclFact>()` was **424 bytes**, and 486 783 declarations over 1 761 files therefore cost **196 MB —
    /// 83 % of every summary in memory** — of which the text was 40 MB. A declaration's *rare* fields were most of the
    /// width: `parameters`, `parameter_defaults`, `constraints`, `bases`, `parameter_list`, `requires_clause`,
    /// `pattern`, `returns_in_the_class`, `in_namespace` and `reflection` are each a `Vec` or an `Option<String>` (24
    /// bytes) and are empty for an ordinary variable, enumerator or field. One `Option<Box<…>>` is eight, and the
    /// memory follows the facts that need it rather than the facts that do not.
    ///
    /// Read through the accessors below — `fact.parameters()` and not `fact.parameters()`, because the field is behind
    /// the box.
    pub detail: Option<Box<DeclDetail>>,
}

/// **The fields of a [`DeclFact`] that most declarations do not have** — boxed as a group, see [`DeclFact::detail`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DeclDetail {
    /// The **qualified** name of the namespace this declaration is written in, when that is not its scope.
    pub in_namespace: Option<String>,
    /// The class of a function declared out of line — `Widget` in `int Widget::size() const`.
    pub returns_in_the_class: Option<String>,
    /// The **named** bases of a class-like definition, in the order the file wrote them.
    pub bases: Vec<String>,
    /// A reflection annotation — `UCLASS(Blueprintable)` — when the declaration carries one.
    pub reflection: Option<ReflectionFact>,
    /// The template parameter names of a template declaration, and of a member of a class template.
    pub parameters: Vec<String>,
    /// The constraints a `template <…>` head writes after its parameters.
    pub constraints: Vec<String>,
    /// The `requires`-clause written after a function's parameter list, or in a template head.
    pub requires_clause: Option<String>,
    /// The default arguments of [`DeclDetail::parameters`], position for position.
    pub parameter_defaults: Vec<String>,
    /// A class template's written pattern with its arguments — `map<_Kty, _Ty>`.
    pub pattern: Option<String>,
    /// The parameter list as the file spells it, parentheses included.
    pub parameter_list: Option<String>,
}

impl DeclDetail {
    /// **The box, or nothing when the detail is empty.** A fact that needs none of these pays eight bytes for the
    /// option; one that needs any of them pays the box and the fields. Boxing every fact, empty or not, would put an
    /// allocation back on the 486 783 declarations this shape exists to make cheap.
    pub fn in_a_box(detail: DeclDetail) -> Option<Box<DeclDetail>> {
        if detail.is_empty() {
            None
        } else {
            Some(Box::new(detail))
        }
    }

    /// Is every field of this detail at its default — no bases, no parameters, no annotation?
    pub fn is_empty(&self) -> bool {
        self.in_namespace.is_none()
            && self.returns_in_the_class.is_none()
            && self.bases.is_empty()
            && self.reflection.is_none()
            && self.parameters.is_empty()
            && self.constraints.is_empty()
            && self.requires_clause.is_none()
            && self.parameter_defaults.is_empty()
            && self.pattern.is_none()
            && self.parameter_list.is_none()
    }
}

impl DeclFact {
    /// The boxed half, when this fact has one.
    pub fn detail(&self) -> Option<&DeclDetail> {
        self.detail.as_deref()
    }

    /// The boxed half, created if this fact has none — what a builder that fills one field needs.
    pub fn detail_mut(&mut self) -> &mut DeclDetail {
        self.detail.get_or_insert_with(Default::default)
    }

    pub fn in_namespace(&self) -> Option<&str> {
        self.detail()
            .and_then(|detail| detail.in_namespace.as_deref())
    }

    pub fn returns_in_the_class(&self) -> Option<&str> {
        self.detail()
            .and_then(|detail| detail.returns_in_the_class.as_deref())
    }

    pub fn bases(&self) -> &[String] {
        self.detail().map_or(&[], |detail| &detail.bases)
    }

    pub fn reflection(&self) -> Option<&ReflectionFact> {
        self.detail().and_then(|detail| detail.reflection.as_ref())
    }

    pub fn parameters(&self) -> &[String] {
        self.detail().map_or(&[], |detail| &detail.parameters)
    }

    pub fn constraints(&self) -> &[String] {
        self.detail().map_or(&[], |detail| &detail.constraints)
    }

    pub fn requires_clause(&self) -> Option<&str> {
        self.detail()
            .and_then(|detail| detail.requires_clause.as_deref())
    }

    pub fn parameter_defaults(&self) -> &[String] {
        self.detail()
            .map_or(&[], |detail| &detail.parameter_defaults)
    }

    pub fn pattern(&self) -> Option<&str> {
        self.detail().and_then(|detail| detail.pattern.as_deref())
    }

    pub fn parameter_list(&self) -> Option<&str> {
        self.detail()
            .and_then(|detail| detail.parameter_list.as_deref())
    }
}

/// Who may name a declaration — see [`DeclFact::access`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Access {
    /// `public:`, or a `struct`'s members before any label.
    Public,
    /// `protected:`.
    Protected,
    /// `private:`, or a `class`'s members before any label.
    Private,
}

impl Access {
    /// The word a file writes — `public`, `protected`, `private` — for a report or a test.
    pub fn words(self) -> &'static str {
        match self {
            Access::Public => "public",
            Access::Protected => "protected",
            Access::Private => "private",
        }
    }

    /// Is this level visible to a consumer that is **not** in the class and not derived from it?
    ///
    /// The rule [`crate::completion`] applies, stated here so that the two cannot drift.
    pub fn is_open_to_everyone(self) -> bool {
        matches!(self, Access::Public)
    }
}

/// What a file declares about **modules** — the reading [`crate::ModuleInfo`] makes of its tree, kept here so that
/// the index can answer "what does this file's `import` bring in" without parsing anything again.
///
/// # Why it is in the summary rather than looked up per query
///
/// Because the answer is needed by the *visibility* walk ([`crate::ProjectIndex::visible_files`]), which runs over
/// every file a cursor can see on every cross-file question. That walk holds summaries and nothing else — no trees,
/// no text — so a module edge it cannot read from a summary is an edge it cannot follow at all.
///
/// # What is *not* here yet, and why the omission is in this direction
///
/// `export`: an `export import m;` re-exports `m`'s names, and one without `export` does not. That distinction is
/// **not** modelled yet, so a name an importer cannot in fact write may be offered — see `plan-units.md` §35 step 3.
/// The other direction (hiding a name the importer *can* write) is the one this project refuses: a missing answer is
/// smaller than a wrong one, but a wrong answer here is a completion the reader only discovers by compiling.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ModuleReading {
    /// The module this file declares, without any partition: `my.mod` for `module my.mod;` and for
    /// `module my.mod:part;` alike. `None` for a file with no module declaration.
    pub module: Option<Box<str>>,
    /// Its partition, without the module and without the `:`.
    pub partition: Option<Box<str>>,
    /// Is this the unit importers see — `export module m;` rather than `module m;`?
    ///
    /// The one field that decides whether the file may be *reached* by an `import m;`: an implementation unit
    /// declares the module and is not what an importer gets, so resolving to one would attribute its declarations
    /// to a module that never exported them.
    pub is_interface: bool,
    /// The **modules** this file imports, in source order. Partitions (`import :part;`) and header units
    /// (`import <vector>;`) are deliberately not here: a partition belongs to the importing file's own module, and a
    /// header unit is a header — it is already reachable through the `#include` machinery, by the same search.
    pub imports: Vec<Box<str>>,
    /// **The headers this file imports as header units** — `import <vector>;`, `import "local.h";` — already
    /// **resolved** by the same search an `#include` goes through (`FileIndexer`'s resolver, at the moment the file
    /// is read).
    ///
    /// Resolved rather than spelt because the visibility walk holds summaries and can search nothing: a header unit
    /// whose header could not be found is **absent** from this list, and that is the honest state — nothing is known
    /// about it, rather than an empty header.
    ///
    /// The declarations of a header unit are all visible to an importer (a header unit exports what the header
    /// declares), so these are followed exactly like `#include`s and are **not** subject to [`DeclFact::exported`].
    pub header_units: Vec<std::path::PathBuf>,
    /// **The partitions of this file's own module that it imports** — `export import :area;` — already **resolved**
    /// to the file that declares them.
    ///
    /// A partition is not a module: `import :area;` is only legal inside `shapes`, and nothing outside may name it.
    /// But the names it exports **are** part of `shapes`'s interface when the import is an `export import`, so a
    /// reader of a file that says `import shapes;` must see them — and the file that declares them is one the
    /// visibility walk has to reach. Measured on the partition fixture
    /// (`tests/fixtures/modules/partitions.cpp`, built and run by `target/build_partitions.bat`): without this,
    /// `definition("perimeter")` resolved to the primary interface unit while `rectangle` and `square` — which the
    /// partition declares and `shapes.cppm` re-exports — answered "nothing declares it".
    ///
    /// Resolved rather than spelt, like [`ModuleReading::header_units`] and for the same reason: the walk holds
    /// summaries and can search nothing.
    pub partitions: Vec<std::path::PathBuf>,
}
///
/// The one kind of fact in a summary whose evidence is not in the file it describes. MSVC's `<vector>` writes
/// `_STD_BEGIN` on a line of its own and `namespace std {` nowhere at all — the braces that scope its 165
/// declarations are in `yvals_core.h` — so "everything here is in `std`" is a reading of *another file's* text.
///
/// # Why this is stored rather than recomputed
///
/// The cache key is the text and the compilation context (`cache.rs`), and it deliberately does not name the macro
/// environment, because a key that had to be computed after the parse would make the disk cache save writes instead
/// of parses. So a summary *can* be read under an environment that has since changed — and the answer to that is not
/// to pretend it cannot happen but to make it **checkable**: the body that licensed the reading is kept verbatim, so
/// a consumer that can ask the include graph again (`ProjectIndex::macro_environment`, and
/// [`crate::macros_from_the_closure_with_bodies`] for a whole closure) can compare the two and rebuild instead of
/// trusting. A consumer that cannot ask still knows where the answer came from, which is strictly more than a bare
/// `scope: "std"` gives it.
///
/// # What it is not
///
/// Not a claim that the name is *declared* here: no binding is created for a scope opened by a body
/// ([`crate::build_scopes`]), so a rename of `std` cannot reach the `_STD_BEGIN` invocation. This records the
/// reading, and the reading is all it records.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MacroScopeReading {
    /// Where the invocation is written in this file.
    pub range: cpp_parser::SourceRange,
    /// The macro's name, as this file spells it.
    pub name: String,
    /// The replacement list it was read as, verbatim — the evidence itself.
    pub body: String,
    /// The namespace it opened, outermost segment first; empty for `namespace {`.
    ///
    /// `None` for an invocation whose body is `}` — the closing half of a reading, which is why the two cases are
    /// distinguished by the option rather than by an empty list.
    pub opens: Option<Vec<String>>,
}

impl MacroScopeReading {
    /// Does this invocation open a scope — as opposed to closing one?
    pub fn opens_a_scope(&self) -> bool {
        self.opens.is_some()
    }
}

/// One entry in a file's **outline**: a declaration the file writes, and the declarations written inside it.
///
/// The fact travels whole rather than as a copy of the three fields a consumer happens to need today: an outline
/// entry is a declaration, and a caller that then asks "what kind", "where is the name", "what are its bases" is
/// asking about the same thing it is looking at.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OutlineSymbol {
    /// The declaration, with both ranges a consumer needs: [`DeclFact::range`] is the whole declaration (what a
    /// client folds or highlights) and [`DeclFact::name_range`] is the name (what it selects).
    pub fact: DeclFact,
    /// The declarations written **inside** this one, in source order.
    pub children: Vec<OutlineSymbol>,
}

impl FileSummary {
    /// **The file's declarations as a tree**, in source order — what an outline, a breadcrumb bar or a folding
    /// range is drawn from.
    ///
    /// # Which reading this is, and why it is not the cooked one
    ///
    /// The **raw** reading, deliberately. Every other query in this crate answers from the cooked one where it can,
    /// because a compiler's reading is the truth about what a name means — an outline is a claim about the **file**,
    /// and the two differ in both directions:
    ///
    /// * a declaration in a branch nobody takes is in an outline and was never compiled ✓ (this is the one reading
    ///   that *wants* the dead branches — a reader editing them is looking at them);
    /// * a type a macro declares is not: `DECLARE_HANDLE(HWND)`'s `HWND__` is in the index and in completions, and
    ///   an outline of `api.h` that listed it would be listing a name the file never writes.
    ///
    /// # The tree, from the facts themselves
    ///
    /// A declaration's [`DeclFact::scope`] is the **qualified name** of the scope it was written in, so a member's
    /// parent is the fact whose [`DeclFact::qualified_name`] equals it — one map lookup per fact, and a fact whose
    /// parent is not in this file is a root (`Widget`'s members are in `widget.h`, not in the file that includes
    /// it). Source order comes from [`DeclFact::range`]: a parent begins before everything written inside it, so one
    /// sorted pass places every fact under a parent that is already placed.
    ///
    /// Two facts of one qualified name — an overload — keep one entry in the map, so the second one's children (if
    /// it had any) would attach to the first: an overload writes no children of its own, and a name *is* what a
    /// scope's children are keyed by.
    ///
    /// # What is not in it
    ///
    /// **Locals** ([`DeclFact::local`]). An outline is the file's structure and not the inside of every function —
    /// and a summary cannot place a local in the function it belongs to anyway, since a local's scope is `None` by
    /// construction (see [`DeclFact::scope`]). A consumer that wants them has the file's own scope tree, which is
    /// what [`crate::FileView::scopes`] is for.
    pub fn outline(&self) -> Vec<OutlineSymbol> {
        outline_of(&self.declarations)
    }
}

/// **A list of declarations as a tree**, in source order — the builder behind [`FileSummary::outline`].
///
/// A free function because the facts do not have to come from a summary: the buffer's own parse produces the same
/// kind of list, and the session reaches for it when a file has just been edited and its summary is gone
/// (`Session::outline`). One builder, so the two readings cannot disagree about what a tree is.
pub fn outline_of(facts: &[DeclFact]) -> Vec<OutlineSymbol> {
    let mut facts: Vec<&DeclFact> = facts.iter().filter(|fact| !fact.local).collect();
    facts.sort_by_key(|fact| (fact.range.start_offset, fact.range.end_offset()));

    let mut roots: Vec<OutlineSymbol> = Vec::new();
    // Where each placed symbol is, by qualified name: the path of child indices from the root. A path rather
    // than a search, so that placing a fact is a walk down a few indices instead of a scan of the tree.
    let mut placed: std::collections::HashMap<String, Vec<usize>> =
        std::collections::HashMap::new();

    for fact in facts {
        let qualified = fact.qualified_name();
        let symbol = OutlineSymbol {
            fact: fact.clone(),
            children: Vec::new(),
        };

        let path = match fact
            .scope
            .as_ref()
            .and_then(|scope| placed.get(scope.as_str()))
        {
            Some(parent) => {
                let parent = parent.clone();
                let mut path = parent.clone();
                path.push(symbol_at(&mut roots, &parent).children.len());
                symbol_at(&mut roots, &parent).children.push(symbol);
                path
            }
            None => {
                roots.push(symbol);
                vec![roots.len() - 1]
            }
        };

        placed.insert(qualified, path);
    }

    roots
}

/// The symbol a path of child indices names — `[2, 0]` is the first child of the third root.
fn symbol_at<'a>(roots: &'a mut [OutlineSymbol], path: &[usize]) -> &'a mut OutlineSymbol {
    let (first, rest) = path.split_first().expect("a path has at least one index");
    let mut node = &mut roots[*first];

    for index in rest {
        node = &mut node.children[*index];
    }

    node
}

impl DeclFact {
    /// The declaration's full name, qualified by the scope it was written in.
    ///
    /// What a symbol search shows and what a lookup keys on. Joining is done here rather than stored, so the two
    /// halves cannot disagree — and a caller that wants the segments separately still has them.
    pub fn qualified_name(&self) -> String {
        match &self.scope {
            Some(scope) if !self.name.is_empty() => format!("{scope}::{}", self.name),
            Some(scope) => scope.to_string(),
            None => self.name.to_string(),
        }
    }

    /// The segments of [`DeclFact::qualified_name`], outermost first.
    ///
    /// For a consumer that needs to walk a qualification rather than print it — resolving `ns::C::f` one segment
    /// at a time is the ordinary case, and splitting a joined string at every step would be work done per query.
    pub fn qualified_segments(&self) -> Vec<&str> {
        let mut segments: Vec<&str> = Vec::new();

        if let Some(scope) = &self.scope {
            segments.extend(scope.split("::"));
        }
        if !self.name.is_empty() {
            segments.push(&self.name);
        }

        segments
    }

    /// **Is this declaration a destructor?** — `~Widget`.
    ///
    /// A destructor has no spelling at a *use*: `~Widget` is written where it is declared, and a call is implied by a
    /// scope ending. A consumer that counts uses of a name therefore has nothing to count, and one that offers an
    /// action on every function in a file should leave it out.
    pub fn is_a_destructor(&self) -> bool {
        is_a_destructor_name(&self.name)
    }

    /// **Is this declaration an overloaded operator?** — `operator+`, `operator()`, `operator bool`, `operator new`.
    ///
    /// The test is the character after `operator`: an operator's spelling continues with a symbol or a space, while an
    /// ordinary name that merely begins with those eight letters (`operator_helper`) continues with a letter, a digit
    /// or an underscore — and is a plain function, which this must not hide.
    ///
    /// What a consumer does with it is that consumer's decision. A *reference query* cannot attribute a use to an
    /// operator without overload resolution — `a + b` is spelled with a symbol and says nothing about which `+` it
    /// reaches — so a count of "the places this operator is used" is the whole project's every `+`, which is a number
    /// wrong in the direction a reader trusts.
    pub fn is_an_operator(&self) -> bool {
        is_an_operator_name(&self.name)
    }
}

/// See [`DeclFact::is_a_destructor`].
pub fn is_a_destructor_name(name: &str) -> bool {
    name.starts_with('~')
}

/// See [`DeclFact::is_an_operator`].
pub fn is_an_operator_name(name: &str) -> bool {
    name.strip_prefix("operator").is_some_and(|rest| {
        rest.is_empty() || rest.starts_with(|first: char| !first.is_alphanumeric() && first != '_')
    })
}

/// What kind of declaration a [`DeclFact`] is.
///
/// A **smaller** vocabulary than [`crate::BindingKind`] on purpose: this is what a summary stores, and a stored
/// value is read by consumers that were written before it. `Other` is not a failure — it is "a declaration is here,
/// and its kind is not one the index distinguishes", which still answers "jump to the definition".
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum DeclKind {
    Type,
    Function,
    Variable,
    Namespace,
    MacroLike,
    Other,
}

/// **One reflection annotation**, as the file wrote it.
///
/// ```cpp
/// UCLASS(Blueprintable, BlueprintType)
/// class MYGAME_API AMyActor : public AActor { … };
///
/// UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Game")
/// bool bIsReady = false;
/// ```
///
/// The macro's name and its specifiers, **in the order written and with the spelling the file used** (`Category =
/// "Game"` keeps its spaces and quotes). What a specifier *means* is the rule layer's question: `ue-specifier` checks the
/// name against the engine's vocabulary, and a hover shows the list. Storing the meaning here would freeze one engine
/// version's semantics into a summary that outlives it.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ReflectionFact {
    /// `UCLASS`, `USTRUCT`, `UENUM`, `UINTERFACE`, `UPROPERTY`, `UFUNCTION` — the macro as written.
    pub macro_name: String,
    /// The arguments between the parentheses, split at the top-level commas and trimmed: `["EditAnywhere", "Category =
    /// \"Game\""]`. An empty list is the ordinary `UPROPERTY()`.
    pub specifiers: Vec<String>,
}

impl ReflectionFact {
    /// **The annotation as one line** — `UCLASS(Blueprintable)`, `UPROPERTY(EditAnywhere, Category = "Game")`.
    ///
    /// Generated from the recorded parts rather than cut out of the file: the macro and the arguments are what the
    /// analysis read, and a rendering that puts them back together cannot disagree with what it decided the
    /// declaration is annotated with.
    pub fn said(&self) -> String {
        format!("{}({})", self.macro_name, self.specifiers.join(", "))
    }

    /// **The value a specifier was given**, when it has one: `Category = "Game"` answers `Some("\"Game\"")` for
    /// `"Category"`. The comparison ignores whitespace around the `=`, which the file may write either way.
    pub fn value_of(&self, name: &str) -> Option<&str> {
        self.specifiers.iter().find_map(|specifier| {
            let (key, value) = specifier.split_once('=')?;
            (key.trim() == name).then(|| value.trim())
        })
    }

    /// **The specifier names**, without their values: `["EditAnywhere", "Category"]`.
    pub fn names(&self) -> impl Iterator<Item = &str> {
        self.specifiers.iter().map(|specifier| {
            specifier
                .split_once('=')
                .map(|(key, _)| key.trim())
                .unwrap_or(specifier.as_str())
        })
    }
}

/// The **parameter list** of a `#define`, read back from the file it was written in.
///
/// The fact records where the replacement list starts and nothing else, so the parameter list is the
/// parenthesised group that ends where the body begins. That is exact rather than a search: the standard's
/// parameter list holds identifiers, commas, `...` and whitespace, and nothing else — no string literal, no
/// comment, no nesting beyond a parameter's own name. A balanced scan back to the matching `(` is therefore the
/// whole rule, and `None` (no `)` there, or no body at all) is the honest answer for an object-like macro.
fn parameters_before(source: &str, body_start: usize) -> Option<&str> {
    let before = source.get(..body_start)?.trim_end();
    let bytes = before.as_bytes();
    if bytes.last() != Some(&b')') {
        return None;
    }

    let mut depth = 0usize;
    let mut at = bytes.len();
    while at > 0 {
        at -= 1;
        match bytes[at] {
            b')' => depth += 1,
            b'(' => {
                depth -= 1;
                if depth == 0 {
                    return Some(&before[at..]);
                }
            }
            _ => {}
        }
    }

    None
}

/// A conditional definition's body, as the closure evidence carries it: the fact's `function_like`, the parameter
/// list when the file it came from had one, and the replacement list.
pub type ConditionalBody = (Box<str>, bool, Option<Box<str>>, Box<str>);

/// **One event read as the `#define` it was, at the place it was written.**
///
/// The pieces are the three the walk copied out of the writing file — the name, the parameter list and the
/// replacement list — and each is lexed where it sits, so the definition's ranges are **positions in that file**
/// rather than offsets in a line this crate wrote. That is what
/// [`crate::macros::MacroDef::written_in`] promises, and what makes "go to definition" on an inherited macro land
/// in the header instead of nowhere.
///
/// The layout is the one the file has, and it is why the offsets are exact rather than searched for: a
/// function-like macro's parameter list follows its name **immediately** (that is the whole difference between
/// `#define A(x) …` and `#define A (x) …`), and the replacement list is the substring `body_range` names. One
/// separator token is inserted between the two, because [`MacroBody`] keeps whitespace and a body's first token
/// must stay separated from the `)` — the same thing `definition_text` spells as a space.
///
/// `None` when the replacement list does not read as a definition, which is the `unreadable` count.
fn definition_written_at(event: &TuEvent, body: &str) -> Option<crate::macros::MacroDef> {
    let mut tokens: Vec<crate::token::Token> = Vec::new();
    let name_at = cpp_parser::SourceRange::new(event.at, event.name.len());
    tokens.push(crate::token::Token::new(
        cpp_parser::CppTokenKind::Identifier,
        &*event.name,
        name_at,
    ));

    if let Some(parameters) = event.parameters.as_deref() {
        // Where the file has it: right after the name. See the note on why that is exact.
        let at = event.at + event.name.len();
        tokens.extend(lex_in_place(parameters, at));
    }

    let body_range = event.body_range?;
    tokens.push(crate::token::Token::new(
        cpp_parser::CppTokenKind::Whitespace,
        " ",
        cpp_parser::SourceRange::new(body_range.start_offset, 0),
    ));
    tokens.extend(lex_in_place(body, body_range.start_offset));

    // The macro's own text in that file: its name and its replacement list. Not the whole directive — the
    // `#define` head is not part of what a fact records — which is what "reveal this macro" wants anyway.
    let range =
        cpp_parser::SourceRange::new(event.at, body_range.end_offset().saturating_sub(event.at));

    let mut definition = crate::macros::parse_define(&tokens, range)?;
    definition.written_in = Some(crate::macros::MacroFile::Frame(event.frame));
    Some(definition)
}

/// Lex a piece of a file's text **as if it were at `at`**: the tokens' ranges are shifted to where they are.
///
/// The piece is a substring the walk copied, so the shift is exact rather than a guess — see
/// [`definition_written_at`], which is the only caller.
fn lex_in_place(text: &str, at: usize) -> Vec<crate::token::Token> {
    let (tokens, _) = cpp_parser::lex(text, &cpp_parser::LexerConfig::default());
    tokens
        .iter()
        .map(|token| {
            crate::token::Token::new(
                token.kind,
                &text[token.range.start_offset..token.range.end_offset()],
                cpp_parser::SourceRange::new(at + token.range.start_offset, token.range.length),
            )
        })
        .collect()
}
/// The same three things while the walk is still collecting them, before the name is prepended.
type ConditionalBodyValue = (bool, Option<Box<str>>, Box<str>);

/// A `#define`, as the index needs it.
///
/// The body is **not** stored — only its shape, which is what the parser's rules ask for (`MacroBody`) and what the
/// analysis layer uses to decide whether an expansion is worth attempting. A caller that needs the tokens re-reads
/// the file: they are in the tree, and copying them into every cache entry would make the cache larger than the
/// project.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MacroFact {
    pub name: String,
    /// Whether this is the name becoming a macro or ceasing to be one.
    pub kind: MacroKind,
    pub function_like: bool,
    pub body: cpp_parser::MacroBody,
    /// Where the macro's **replacement list** is, in the file that defines it — the one piece of a body expansion
    /// needs and the fact did not carry.
    ///
    /// `range` above is the *name*, deliberately ("go to macro definition" jumps to the name, and a rename edits
    /// it); this is everything after the parameters, and it is what lets a consumer slice the body's **text** out of
    /// the defining file rather than re-deriving it by searching the directive — the mistake
    /// `MacroDef::name_range`'s own note warns about ("a search is a second implementation of the same rule, free to
    /// disagree with the one that assigned the name").
    ///
    /// `None` for an `#undef` (there is no body) and for a `#define` with an empty replacement list.
    pub body_range: Option<cpp_parser::SourceRange>,
    /// The macro's value, when its body is **one integer literal**: `#define _GLIBCXX_USE_CXX11_ABI 1`.
    ///
    /// The one piece of a body a condition can read. `#if NAME` on a macro expands it and re-reads the result, and
    /// `condition::macro_value` only accepts a single integer literal — so a body of two tokens, a body
    /// that is a name, and no body at all are the same answer to a condition, and storing any of them would be a
    /// longer way of saying `Unknown`. This is what makes `#if __cplusplus >= 201703L && _GLIBCXX_USE_CXX11_ABI`
    /// decidable once the file that defines the second name has been walked.
    ///
    /// Stored as the literal's **text**, so that reading it back needs no lexer: whoever reads it knows what it is
    /// — the same reason the fact stores a name's range rather than a way to find it.
    pub value: Option<Box<str>>,
    /// **The one name the body *is*, when the body is exactly one identifier** — `#define A B`.
    ///
    /// The second piece of a body a condition can read, and the one an index cannot otherwise recover: the body is
    /// stored as a [`cpp_parser::MacroBody`], which is a **shape** rather than tokens, so "which name did it
    /// alias" is not derivable from the summary. Set where the replacement list is in hand (see
    /// `macro_alias`), and read by `MacrosHere::alias_of`, which follows the chain by name.
    ///
    /// Why it is not a nicety: `vcruntime.h` writes `#define _STL_LANG __cplusplus`, and
    /// `#if _STL_LANG > 201402L` is undecidable while the alias is unreadable — so `_HAS_CXX17` is never defined,
    /// and neither is anything gated on it, including the `#include <atomic>` in `<memory>`.
    pub alias: Option<Box<str>>,
    /// Where the fact is, for "go to macro definition".
    pub range: cpp_parser::SourceRange,
    pub guard: FactGuard,
    /// Does this fact settle the name's macro state **whatever branch of its `#if` is taken**?
    ///
    /// False for a fact outside every conditional (there is nothing to settle), and false for the ordinary
    /// conditional fact, whose existence depends on a macro nobody has. True for the two shapes where the
    /// conditional *cannot* change the answer:
    ///
    /// ```text
    /// #ifndef NAME            the condition IS "NAME is not defined yet", and the body defines it:
    /// #define NAME 1          taken → defined here; not taken → it was already defined. Either way: a macro.
    /// #endif
    ///
    /// #if A                   every branch ends in the same kind of fact about the same name, and there
    /// #define NAME 1          is an `#else` — so one of them ran, and whichever it was, the name is a macro.
    /// #else
    /// #define NAME 2
    /// #endif
    /// ```
    ///
    /// `#ifdef NAME` whose body ends in `#undef NAME` is the mirror, and says the name is **not** a macro after
    /// the block. A single-branch `#if A` never settles anything, because the branch may not be taken at all — and
    /// a region nested inside an unsettled one settles nothing either, which is why this is computed for the whole
    /// chain of enclosing conditionals rather than for the innermost alone.
    ///
    /// # What it does *not* say
    ///
    /// **Not which `#define` is in force.** In the second shape the branches differ in what they define the name
    /// *as*, and in the first the name may have been defined by an earlier header that this file cannot see. So
    /// `macro_definition` — the question "where is this macro defined" — ignores this field, and the reference
    /// query, which asks the weaker "is this name a macro *here*", is what reads it. Two questions, two answers.
    ///
    /// # Why this is a fact and not a conclusion
    ///
    /// The invariant every field here is judged by is "would a change to another file make it stale?" — a resolved
    /// type would, a `FileId` would, an instantiation would. This one cannot: it is computed from **this file's own
    /// directives**, and no header can change how a file writes its `#if`s. That is also why it is stored rather
    /// than recomputed per query: the answer needs the branch structure, and a summary keeps only the regions.
    pub settles_the_name: bool,
}

/// Which of the two things a macro name's history is made of.
///
/// `#undef` is stored because a query that answers "where is this macro defined" has to be able to answer "it is
/// not a macro here" instead: a name `#undef`ed above the cursor is an ordinary identifier, and pointing at the
/// `#define` it used to have would be a wrong answer rather than a missing one. Both are *facts about the text* —
/// they say what the file does, not what any compilation concludes — so the same ordering rule settles them
/// together: whichever comes last in translation order wins, and it can be either kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MacroKind {
    /// `#define NAME ...`
    Definition,
    /// `#undef NAME`
    Undefinition,
}

impl MacroKind {
    /// Is this fact the name becoming a macro?
    pub fn is_definition(self) -> bool {
        matches!(self, MacroKind::Definition)
    }
}

/// An `#include`, resolved or not.
///
/// The *target* is stored as the **path** the resolver found, for the same reason [`FileSummary::path`] is: an
/// id is an index into a run's interner and means nothing once that run is over, while the path is what a
/// consumer opens and what a reverse-include map is built from. A header that did not resolve keeps its
/// spelling, because "this project includes something we cannot find" is a fact a consumer wants to see rather
/// than a gap to hide.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IncludeFact {
    pub form: IncludeForm,
    /// The spelling between the delimiters, as written.
    pub spelling: String,
    /// Where the include resolved to, when the resolver found it.
    pub resolved: Option<std::path::PathBuf>,
    /// Whether the directive was `#include_next`.
    ///
    /// Stored, although no *query* has ever wanted it, because the answer has to be **re-derivable**: a summary
    /// that says where an include resolved can only be trusted while re-running the search gives the same answer,
    /// and a search that skipped candidates differently is a different search. See [`IncludeFact::as_include`].
    pub is_next: bool,
    pub range: cpp_parser::SourceRange,
    pub guard: FactGuard,
}

impl IncludeFact {
    /// The directive this fact was made from, as the resolver takes one.
    ///
    /// The round trip back from a fact to a directive is what makes a stored `resolved` **checkable**: `#include`
    /// resolution depends on which paths *exist*, and that is a fact about the filesystem which no key computed
    /// from the text can name — so a cached summary is a candidate that has to be re-verified against the
    /// filesystem before it is used. That check is only faithful if every field the search reads is here, which is
    /// why [`is_next`](Self::is_next) is stored and not dropped.
    pub fn as_include(&self) -> crate::preprocess::directive::Include {
        crate::preprocess::directive::Include {
            form: self.form,
            target: Box::from(self.spelling.as_str()),
            is_next: self.is_next,
        }
    }
}

/// The macros a file's **direct includes** contribute, each in force from the end of its own `#include`.
///
/// This is the first half of the answer the positional half describes: the index
/// already stores, per file, where each macro is defined (`MacroFact`) and where each `#include` resolved
/// (`IncludeFact::resolved`) — this turns those two into the **positional** evidence the parser asks for, stamped
/// with the offset the include ended at.
///
/// Four rules, and each one is a decision rather than a detail:
///
/// * **direct includes only** — a header's own includes are *its* evidence, and following the graph here would need
///   the translation order to be read again, which is what `ProjectIndex` does for conditions;
/// * **the include's offset, not the macro's** — a macro becomes visible where it is brought in, which is what makes
///   the evidence positional at all;
/// * **unconditional facts only** — a `#define` inside an `#if` may not have run, and seeding it would be the flat
///   table's mistake in a new disguise (see the measured cost);
/// * **`#undef` is carried** — a name that stops being a macro is evidence too, and dropping it would leave the
///   earlier definition in force for the rest of the file.
///
/// This variant also carries the **replacement list as text**, when the caller can supply the defining file's
/// source — which is what expansion reads: `namespace __8 {` decides a namespace head, `, noexcept` a
/// parameter-list fragment, `virtual HRESULT STDMETHODCALLTYPE method` a declarator head.
///
/// The text is sliced out of the defining file by the fact's own range, so it stays **the file's text** — including
/// whatever whitespace and comments the body has — and nothing here re-spells a body.
pub fn macros_from_direct_includes_with_bodies<'a>(
    summary: &FileSummary,
    mut look_up: impl FnMut(&std::path::Path) -> Option<(&'a FileSummary, &'a str)>,
) -> Vec<cpp_parser::IncludedMacro> {
    let mut entries = Vec::new();

    for include in &summary.includes {
        let Some((included, source)) = include.resolved.as_deref().and_then(&mut look_up) else {
            continue;
        };
        // Where the name becomes visible: the end of the `#include` directive, which is where a consumer of the
        // tree would put a marker.
        let from_offset = include.range.start_offset + include.range.length;

        for fact in &included.macros {
            if !matches!(fact.guard, FactGuard::Unconditional) {
                continue;
            }

            // The body's **text**, sliced out of the file that defines it by the fact's own range — the piece
            // expansion reads. `None` when the body is empty (`#define FOO`), or when the range does not index
            // the source (a summary from a different revision of that file, which is the caller's to detect).
            let body_text = fact.body_range.and_then(|range| {
                source.get(range.start_offset..range.start_offset + range.length)
            });

            entries.push(if fact.kind.is_definition() {
                cpp_parser::IncludedMacro::defined_with_body_and_parameters(
                    from_offset,
                    &fact.name,
                    fact.function_like,
                    fact.body,
                    body_text,
                    fact.body_range
                        .and_then(|range| parameters_before(source, range.start_offset)),
                )
            } else {
                cpp_parser::IncludedMacro::undefined_at(from_offset, &fact.name)
            });
        }
    }

    entries
}

/// The macros a file's **whole include closure** contributes, each in force from the `#include` that brought it in.
///
/// [`macros_from_direct_includes_with_bodies`] is the honest minimum, and the measurement says it is not enough:
/// of the 21 remaining failures, **15 have a macro on their first-error line that the closure defines and no direct
/// include does** (`bits/refwrap.h` uses `_GLIBCXX_NOEXCEPT_PARM`, which `bits/c++config.h` defines — two includes
/// away through `bits/move.h`). Evidence that only ever reaches one hop answers for the wrong file.
///
/// So each direct include is walked **through its own closure**, and every macro found is in force from the offset
/// of that direct include — which is where a consumer of the tree would put a marker, and what keeps the answer
/// positional. Three things make this affordable rather than a second index:
///
/// * **one pass per direct include, names deduplicated before any text is sliced** — a closure defines the same
///   name in several files, and last-wins by translation order is the answer the preprocessor gives, so the
///   replacement lists that survive are one per *name*, not one per definition;
/// * **the walk stops at files already seen**, so an include cycle is not a hang;
/// * **nothing is re-spelled**: a body is the defining file's own bytes, sliced by the fact's range.
///
/// # Two channels
///
/// The evidence a file's include closure contributes — **two channels**, and the split is measured, not aesthetic.
///
/// `macros` is what says *whether a name is a macro here*: only unconditional definitions, because a name that is
/// a macro only inside a branch the file may not be in is not a fact about the file.
///
/// `conditional_bodies` is what a rule **reads**: the replacement list of a macro whose definition is conditional
/// but whose branch is in force. Feeding these into `macros` as well is what the first version did, and the census
/// said no — 3 files clean→failing, none the other way (`corecrt.h`, `swprintf.inl`, `types.h`, all three a
/// declaration headed by `__MINGW_EXTENSION`-style macro): several rules read *shape* **because** no table knows
/// the name, and an entry with an unreadable body switches exactly those rules off. Evidence is not monotone. A
/// body, on the other hand, can only ever *enable* a reading: no rule asks "is there a body" to refuse something.
pub struct ClosureEvidence {
    pub macros: Vec<cpp_parser::IncludedMacro>,
    /// `(name, replacement list)` — last definition in translation order wins, like everything else here.
    pub conditional_bodies: Vec<ConditionalBody>,
    /// Conditional facts the walk met, and how many of them the conditions put **in force**. Two numbers rather
    /// than one, because "nothing here was conditional" and "every condition was unanswerable" look the same in
    /// the evidence — and because the second number is what moves when the environment gets better at answering.
    pub conditional_facts: usize,
    pub facts_in_force: usize,
}

/// What the translation unit has defined **so far** — the state a condition written later is answered against.
///
/// This is the "边走边喂" half of: a condition is a question about what the unit had seen
/// when the preprocessor reached it, and the answer changes as the walk moves on. `#ifdef STDMETHOD` is false
/// before `objbase.h` and true after it, in the *same* translation unit.
///
/// Only **definedness** is carried, not values. A file's body is text whose meaning is the parser's business, so a
/// name the walk has seen defined answers `#ifdef`/`defined()` and leaves a *value* question (`#if FOO == 2`) to
/// the compilation's own table — which is a lost reading rather than a wrong branch, the direction this layer must
/// always fail in.
struct UnitState {
    /// What the unit has in force, as **definitions** rather than names — each carrying **where** it was
    /// written, because a definition is only in force from its own line (see [`UnitMacros::lookup`]).
    definitions: rustc_hash::FxHashMap<Box<str>, Binding>,
    /// **How many times the set in force has changed** — the clock the walk's branch memo is invalidated by.
    ///
    /// A region's condition is answered *at the offset of the fact that asks*, and that is not bookkeeping: which
    /// **branch** the position falls in is part of the question, and a `#define` written between two facts changes the
    /// answer for the ones below it. Between two such changes, an answer depends on nothing but *(region, branch)* —
    /// see the memo in `walk_one_file` for why that pair is the whole key.
    generation: u64,
}

/// One definition the unit has in force: what it says, and where it was said.
struct Binding {
    definition: std::sync::Arc<MacroDef>,
    /// The file that wrote it — a position means nothing without it, and only the file being walked can have
    /// written something *below* the condition being answered.
    defined_in: Box<std::path::Path>,
    defined_at: usize,
}

impl UnitState {
    fn define(
        &mut self,
        name: &str,
        definition: std::sync::Arc<MacroDef>,
        file: &std::path::Path,
        at: usize,
    ) {
        self.definitions.insert(
            name.into(),
            Binding {
                definition,
                defined_in: Box::from(file),
                defined_at: at,
            },
        );
        self.generation += 1;
    }

    fn undefine(&mut self, name: &str) {
        if self.definitions.remove(name).is_some() {
            self.generation += 1;
        }
    }
}

/// The `MacroDef`s a walk feeds into a translation unit's state, parsed **once per *(file, name)***.
///
/// Parsing is the cost of feeding definitions: a closure holds tens of thousands of `#define`s and every one of
/// them is read back out of the defining file's text. A definition does not depend on *which* file is being
/// seeded, so the cache is the difference between one parse per definition and one per definition per file —
/// 455 files in this corpus, which is the difference between seconds and minutes.
#[derive(Default)]
pub struct MacroDefinitions {
    /// Keyed by **where the definition is written** rather than by its name, and that is not a detail: a file may
    /// define the same name twice (`#define WIDTH 80` above an `#undef` and a second `#define WIDTH 120`), and a
    /// cache keyed by the name would hand the second fact the first one's definition — a wrong expansion rather than
    /// a missing one. A fact is identified by the range its name is written at, which is unique in its file.
    ///
    /// **The path is shared**, not owned per key: the same header defines hundreds of macros, and a `PathBuf` per
    /// entry was hundreds of copies of the same path — measured at 34 000 entries on a cold start, most of them
    /// pointing into about 400 files.
    parsed: std::collections::HashMap<
        (std::sync::Arc<std::path::Path>, usize),
        Option<std::sync::Arc<MacroDef>>,
    >,
    /// What the map holds, in the estimate [`MacroDefinitions::accounting`] makes — the number the budget below is
    /// deducted from.
    bytes: usize,
}

/// **How many bytes of `#define`s the cache keeps** — see [`MacroDefinitions`].
///
/// Before this bound the map grew for the life of the session: every definition an evaluation touched stayed, keyed
/// by `(path, offset)`, and a 1 273-file project reached 34 000 entries / 11.6 MB with nothing dropping them. The
/// table is cleared rather than evicted when it fills, because a definition is one `#define` line re-read from a
/// file that is already in memory: cheap to rebuild, and clearing is what keeps the bookkeeping honest (no weight
/// to maintain per entry on the hot path).
pub const MAX_DEFINITION_BYTES: usize = 32 * 1024 * 1024;

impl DeclFact {
    /// The bytes one declaration fact holds: the struct and the strings it owns.
    ///
    /// **A `SmolStr` is only counted when it is on the heap.** The struct is `size_of::<DeclFact>` whether a field is
    /// inline or not, so a name of 22 bytes or fewer costs nothing here — which is the reason the field is a `SmolStr`
    /// at all. Counting `len()` for those was how the first measurement of this change reported "no difference": the
    /// estimate charged an allocation that no longer happens.
    pub fn heap_bytes(&self) -> usize {
        std::mem::size_of::<DeclFact>()
            + on_the_heap(&self.name)
            + self.scope.as_ref().map_or(0, on_the_heap)
            + self.in_namespace().map_or(0, str::len)
    }
}

/// What a `SmolStr` costs **outside the struct** — nothing while it is inline, its length when it is not.
fn on_the_heap(text: &SmolStr) -> usize {
    if text.is_heap_allocated() {
        text.len()
    } else {
        0
    }
}

impl MacroFact {
    /// The bytes one macro fact holds. The body is a range into the file's own text, not a copy of it.
    pub fn heap_bytes(&self) -> usize {
        std::mem::size_of::<MacroFact>()
            + self.name.len()
            + self.value.as_ref().map_or(0, |text| text.len())
            + self.alias.as_ref().map_or(0, |text| text.len())
    }
}

impl IncludeFact {
    /// The bytes one include fact holds.
    pub fn heap_bytes(&self) -> usize {
        std::mem::size_of::<IncludeFact>()
            + self.spelling.len()
            + self
                .resolved
                .as_ref()
                .map_or(0, |path| path.as_os_str().len())
    }
}

impl FileSummary {
    /// **What this summary costs in memory** — the struct, its facts, and the strings they own.
    ///
    /// The estimate every consumer of [`crate::MemoryReport`] is built on: it counts the vectors' *contents*, not
    /// their spare capacity, so it is a lower bound. Measured against the resident set, the difference is the
    /// allocator's slack — which is itself worth seeing, and is why the report prints both.
    pub fn heap_bytes(&self) -> usize {
        std::mem::size_of::<FileSummary>()
            + self.path.as_os_str().len()
            + self
                .declarations
                .iter()
                .map(DeclFact::heap_bytes)
                .sum::<usize>()
            + self.macros.iter().map(MacroFact::heap_bytes).sum::<usize>()
            + self
                .includes
                .iter()
                .map(IncludeFact::heap_bytes)
                .sum::<usize>()
            + self.guards.regions.len() * std::mem::size_of::<cpp_parser::SourceRange>()
            + self
                .macro_readings
                .iter()
                .map(|reading| {
                    std::mem::size_of::<MacroScopeReading>()
                        + reading.name.len()
                        + reading.body.len()
                })
                .sum::<usize>()
            + self.use_filter.len()
            + self.modules.module.as_ref().map_or(0, |name| name.len())
            + self.modules.partition.as_ref().map_or(0, |name| name.len())
            + self
                .modules
                .imports
                .iter()
                .map(|name| name.len())
                .sum::<usize>()
            + (self.modules.header_units.len() + self.modules.partitions.len())
                * std::mem::size_of::<std::path::PathBuf>()
    }
}

impl MacroDefinitions {
    /// **What the definition cache is holding** — `(entries, bytes)`.
    ///
    /// The map has **no cap**: every `#define` ever read back for an evaluation stays, keyed by
    /// `(path, offset)` — and the key owns the path, so one entry per definition is a path per
    /// definition. It is invalidated per file ([`MacroDefinitions::forget`]), never evicted.
    pub fn accounting(&self) -> (usize, usize) {
        let mut bytes = 0usize;
        for (key, definition) in &self.parsed {
            bytes += std::mem::size_of::<(
                (std::path::PathBuf, usize),
                Option<std::sync::Arc<MacroDef>>,
            )>();
            bytes += key.0.as_os_str().len();
            if let Some(definition) = definition {
                bytes += std::mem::size_of::<MacroDef>() + definition.name.len();
                if let Some(params) = &definition.params {
                    bytes +=
                        params.len() * std::mem::size_of::<crate::preprocess::macros::Parameter>();
                }
            }
        }
        (self.parsed.len(), bytes)
    }
}

impl MacroDefinitions {
    /// The definition behind one fact, read from the file that wrote it.
    ///
    /// The `#define` is **put back together** from what the fact carries — its name, and the rest of its logical
    /// line, which is the parameter list and the body — and read by the ordinary `#define` reader, so a definition
    /// fed into a condition cannot mean something different from the same line read in the file. The offsets in the
    /// result are relative to that reconstructed line, which is all the evaluator does with them.
    fn definition_of(
        &mut self,
        path: &std::path::Path,
        source: &str,
        fact: &MacroFact,
    ) -> Option<std::sync::Arc<MacroDef>> {
        let key = (std::sync::Arc::from(path), fact.range.start_offset);
        // **The key allocates, and it stays that way because the measurement said the allocation is
        // 1 s of a 250 s index.** A counter was put here to answer "what fraction of lookups are
        // hits" — five million lookups per index at 98.7%, so the waste is real and the fix is not
        // obvious: a pointer-keyed index would be the cheap answer and the unsafe one, because a
        // path that is replaced could then hand one file's definition to another.
        if let Some(known) = self.parsed.get(&key) {
            return known.clone();
        }

        let definition = read_back_a_define(source, fact).map(std::sync::Arc::new);

        // **The budget, checked on the way in.** A definition is one `#define` line re-read from a file already in
        // memory, so dropping the whole table costs less than tracking a weight per entry on this path — which is
        // the hottest path in the index (five million lookups per run are hits).
        if self.bytes > MAX_DEFINITION_BYTES {
            self.parsed.clear();
            self.bytes = 0;
        }
        self.bytes += std::mem::size_of::<(
            (std::sync::Arc<std::path::Path>, usize),
            Option<std::sync::Arc<MacroDef>>,
        )>();
        self.bytes += std::mem::size_of::<MacroDef>();
        if let Some(definition) = &definition {
            self.bytes += definition.name.len();
        }
        self.parsed.insert(key, definition.clone());

        definition
    }

    /// Forget everything read out of a file whose text changed.
    ///
    /// Necessary rather than tidy: the keys are **offsets in that file**, so after an edit an old entry can be
    /// reached by a *different* fact that happens to start where the old one did — the cache would then hand back a
    /// definition nobody wrote. The whole file's entries go, not only the edited definition's: every offset after
    /// the edit moved.
    pub fn forget(&mut self, path: &std::path::Path) {
        let before = self.parsed.len();
        self.parsed.retain(|(held, _), _| held.as_ref() != path);
        if self.parsed.len() != before {
            // An exact subtraction is not worth a per-entry walk: the estimate is a bound, and the next
            // `definition_of` call checks it anyway.
            self.bytes = self.parsed.len() * 96;
        }
    }

    /// How many distinct definitions have been read back — the number a caller watches to see the cache work.
    pub fn len(&self) -> usize {
        self.parsed.len()
    }

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

    fn get_or_read(
        &mut self,
        path: &std::path::Path,
        source: &str,
        fact: &MacroFact,
    ) -> Option<std::sync::Arc<MacroDef>> {
        self.definition_of(path, source, fact)
    }
}

/// `#define NAME(params) body`, read back out of the file's own text.
///
/// A `\`-newline is **removed**, not copied: translation phase 2 does that before anything reads the line, and a
/// splice left in the middle of a body makes the body unreadable — the evaluator meets a line-continuation token
/// between two operands and answers `Unknown`. Measured, and it is what kept `STDMETHOD` out of `commdlg.h` for
/// three batches: `WINAPI_FAMILY_DESKTOP_APP` is written across two lines in `winapifamily.h`, so
/// `#if WINAPI_FAMILY_PARTITION (WINAPI_PARTITION_APP)` — the guard around `combaseapi.h`'s C++ `#define
/// STDMETHOD` — could never be answered.
fn read_back_a_define(source: &str, fact: &MacroFact) -> Option<MacroDef> {
    let raw = source.get(fact.range.start_offset..)?;

    // The fact's range may start at the **name** or at the directive — both spellings exist in the index — so the
    // line is taken from wherever `#define` ends, and the keyword is put back exactly once.
    let rest = match raw.strip_prefix('#') {
        Some(after_the_hash) => {
            let after_the_hash = after_the_hash.trim_start();
            match after_the_hash.strip_prefix("define") {
                Some(after_the_keyword) => after_the_keyword.trim_start(),
                None => raw,
            }
        }
        None => raw,
    };

    let bytes = rest.as_bytes();

    let mut logical = String::new();
    let mut index = 0;
    while index < bytes.len() {
        match bytes[index] {
            b'\\' if bytes.get(index + 1) == Some(&b'\n') => index += 2,
            b'\\'
                if bytes.get(index + 1) == Some(&b'\r') && bytes.get(index + 2) == Some(&b'\n') =>
            {
                index += 3;
            }
            b'\n' => break,
            _ => {
                let character = rest[index..].chars().next()?;
                logical.push(character);
                index += character.len_utf8();
            }
        }
    }

    let line = format!("#define {logical}");
    let mut errors = Vec::new();
    let mut lexer =
        cpp_parser::CppLexer::new(&line, cpp_parser::LexerConfig::default(), &mut errors);
    let tokens: Vec<crate::token::Token> = lexer
        .tokenize()
        .into_iter()
        .map(|token| {
            let text = &line[token.range.start_offset..token.range.end_offset()];
            crate::token::Token::new(token.kind, text, token.range)
        })
        .collect();

    // `parse_define` reads from the **name**: the directive's own `#` and `define` are the directive scanner's
    // business and not the definition reader's, so the two leading significant tokens are dropped here.
    let mut significant = 0usize;
    let mut from = 0usize;
    for (index, token) in tokens.iter().enumerate() {
        if crate::token::is_trivia(token.kind) {
            continue;
        }

        significant += 1;
        from = index + 1;
        if significant == 2 {
            break;
        }
    }

    crate::macros::parse_define(tokens.get(from..)?, fact.range)
}

/// The table a condition inside the unit is answered against: what the walk has seen, over what the compilation
/// started with.
#[derive(Clone, Copy)]
struct UnitMacros<'a> {
    seed: &'a Marked,
    state: &'a UnitState,
    /// The file the condition being answered was written in, and the offset it was written at. `None` asks the
    /// question **without a position** — "what does the unit say now, at the end of what has been read" — which is
    /// what the expansion *inside* a body wants.
    here: Option<(&'a std::path::Path, usize)>,
}

impl crate::condition::MacroValues for UnitMacros<'_> {
    fn lookup(&self, name: &str) -> crate::condition::Lookup<'_> {
        // **What the walk's own evaluator is told about a name.**
        //
        // The cook and the walk decide the same guards through different code, and when they disagree nothing outside
        // shows it: a guard the walk reads as `None` silently drops every fact inside it, and the only symptom is
        // content missing from a stream much later. `CPPLS_TRACE_LOOKUP=NAME` prints this path's answer.
        //
        // **The trace comes from `crate::probes`, which reads its variable once.** This is the hottest function in a
        // warm index — `a_guard_holds` was measured at 271 s of a 465 s index, and every identifier of every
        // condition of every guard arrives here — so reading the environment per call was a lock of the process on
        // the hottest path in the program. Measured: hoisting that one read took `a_guard_holds` from **271,479 ms**
        // to **192,350 ms**, and dropping the `to_string_lossy` beside it took it to **165,312 ms**.
        if let Some(wanted) = crate::probes::lookup_name()
            && wanted == name
        {
            let from_state = self.state.definitions.get(name).map(|binding| {
                // **The shape, not just the name.** A definition whose parameter list or body did not survive the
                // walk is a definition the expander cannot use: `NAME (x)` stops being a call, and an `#if` that
                // asks for a *value* gets an identifier with none. Printing only "defined" hid that for several
                // rounds — the lookup answered `Defined` while the guard still came out `None`.
                let params = match &binding.definition.params {
                    None => "object-like".to_string(),
                    Some(list) => format!(
                        "fn-like({:?})",
                        list.iter()
                            .map(|held| held.name.as_ref())
                            .collect::<Vec<_>>()
                    ),
                };
                let body: Vec<&str> = binding
                    .definition
                    .body
                    .significant()
                    .map(|token| token.text())
                    .collect();
                format!(
                    "state(defined_in={} at={} {params} body={:?})",
                    binding.defined_in.display(),
                    binding.defined_at,
                    body.join(" ")
                )
            });
            let from_seed = match self.seed.lookup(name) {
                crate::condition::Lookup::Defined(_) => "seed:Defined".to_string(),
                crate::condition::Lookup::DefinedWithoutAValue => {
                    "seed:DefinedWithoutAValue".to_string()
                }
                crate::condition::Lookup::Undefined => "seed:Undefined".to_string(),
                crate::condition::Lookup::Unanswered => "seed:Unanswered".to_string(),
            };
            println!(
                "cppls-lookup: {name} state={} {from_seed}",
                from_state.as_deref().unwrap_or("none")
            );
        }

        if let Some(binding) = self.state.definitions.get(name) {
            // **A definition written below this condition has not happened yet.** An include guard is
            // `#ifndef X / #define X`, so a table read at the end of the file answers "`X` is defined" — and that
            // makes the guard's own region inactive and every fact inside it invisible. Measured: it is what kept
            // `combaseapi.h`'s `STDMETHOD` out of `commdlg.h` after the condition itself had been made answerable
            //.
            let written_below = self
                .here
                .is_some_and(|(file, at)| &*binding.defined_in == file && binding.defined_at >= at);

            if !written_below {
                return crate::condition::Lookup::Defined(&binding.definition);
            }
        }

        // **A name neither the walk nor the compiler knows is undefined.** The state above is the walk's own table —
        // complete for everything this translation unit has read so far — so "absent" is C++'s `0` and
        // `defined(X)` is false. `Unanswered` is for a table that *cannot* see the whole program, and this one can.
        //
        // Measured on libstdc++: `bits/version.h` claims its feature-test macros with
        // `#if defined(__glibcxx_want_all) || defined(__glibcxx_want_print)`. `__glibcxx_want_all` is defined
        // nowhere, the `Unanswered` it got made the whole `||` **Unknown**, the region was judged inactive, and the
        // `#define __cpp_lib_print` inside it was dropped by the walk — so `print`'s whole body (under
        // `#ifdef __cpp_lib_print`) existed in no reading at all, and every hover and completion for `std::println`
        // answered nothing. The trace that named it: `state=none seed:Unanswered`.
        match self.seed.lookup(name) {
            crate::condition::Lookup::Unanswered => crate::condition::Lookup::Undefined,
            other => other,
        }
    }

    /// **Forwarded to the seed, because this is the table every condition in the walk is evaluated against.**
    ///
    /// A builtin operator is a question about the **compiler**, and the compiler's answers live on
    /// [`crate::Marked`] — the seed. Without this, the answer is the trait's default `None`, which becomes
    /// `Unknown`, and a condition that asks one is silently undecidable.
    ///
    /// # What it cost, measured
    ///
    /// `_HAS_MSVC_ATTRIBUTE(x)` is `__has_cpp_attribute(msvc::x)`, so every `#if _HAS_MSVC_ATTRIBUTE(…)` in the STL
    /// is a question about an attribute — and every one of them came out `None` on this path:
    ///
    /// ```text
    /// cook   __has_cpp_attribute(msvc::known_semantics)          -> Some(1)
    /// walk   _HAS_MSVC_ATTRIBUTE ( known_semantics )             -> None
    /// ```
    ///
    /// The walk then judged each guard false, so the `#define`s inside them — `_MSVC_KNOWN_SEMANTICS`,
    /// `_MSVC_INTRINSIC`, `_NO_SPECIALIZATIONS_MSG` and the rest of that family — **were never recorded at all**.
    /// That is why later queries answered `positional=no-binding`: the fact was not hidden, it had never been made.
    ///
    /// This is the same mistake as [`crate::preprocess::PositionalMacros`]'s note describes, on the other path: an
    /// implementation sitting one layer below the only caller that asks.
    fn builtin_operator(&self, name: &str, operand: &str) -> Option<crate::condition::Value> {
        self.seed.builtin_operator(name, operand)
    }
}

/// The macros a file's own include closure contributes.
///
/// `definitions` is the cache of parsed `#define`s the walk feeds into a unit's state; one cache serves every file
/// seeded from the same corpus, which is what keeps the feeding affordable (see [`MacroDefinitions`]).
pub fn macros_from_the_closure_with_bodies<'a>(
    summary: &'a FileSummary,
    look_up: impl FnMut(&std::path::Path) -> Option<(&'a FileSummary, &'a str)>,
    seed: &Marked,
    definitions: &mut MacroDefinitions,
) -> ClosureEvidence {
    {
        // This path builds no unit (it only collects evidence), so its contributions are never shared: a fresh
        // table per call is the honest owner, and nothing is kept beyond it.
        let cache = crate::index::walk_cache::WalkCache::new();
        walk_the_translation_unit(summary, None, None, look_up, seed, definitions, &cache)
    }
}

/// The macros in force in a translation unit **before the point where it includes this file** — what a *header*
/// needs, and the one thing its own closure structurally cannot give it.
///
/// `commdlg.h:577` writes `STDMETHOD(QueryInterface) (…) PURE;` and never sees a `#define` of `STDMETHOD`: its own
/// includes are `winapifamily.h`, `_mingw_unicode.h`, `prsht.h`, `pshpack1.h`, `poppack.h`, and the definition
/// arrives because `windows.h:108` includes `commdlg.h` **after** `objbase.h` — the *includer's order* is the
/// translation unit, and a per-file walk stops at the file's own edge. Measured: the seed for that line is empty,
/// which is why the reading rules could not fix the file.
///
/// The entries are seeded at offset **0** and not at the includer's offsets: the offsets of a *different* file mean
/// nothing here, and every macro the unit had in force before the inclusion is in force from this file's first
/// token on. What this file does to those names afterwards is its own facts' business, which the parser reads
/// itself.
pub fn macros_in_force_before_the_include<'a>(
    includer: &'a FileSummary,
    before: usize,
    look_up: impl FnMut(&std::path::Path) -> Option<(&'a FileSummary, &'a str)>,
    seed: &Marked,
    definitions: &mut MacroDefinitions,
) -> ClosureEvidence {
    {
        let cache = crate::index::walk_cache::WalkCache::new();
        walk_the_translation_unit(
            includer,
            Some(before),
            Some(0),
            look_up,
            seed,
            definitions,
            &cache,
        )
    }
}

/// Walk a file's includes — or, with `only_before`, only the ones written **before** that offset — and collect what
/// the closure they reach defines.
///
/// # Why the walk carries a state
///
/// A condition is a question about what the translation unit had **seen** when the preprocessor reached it:
/// `#ifdef STDMETHOD` in `commdlg.h` is false until `objbase.h` has been read, and
/// `#if WINAPI_FAMILY_PARTITION (WINAPI_PARTITION_APP)` in `combaseapi.h` is a question about a macro
/// `winapifamily.h` defines. Answering every condition against one fixed table — which is what this walk did
/// before — reports `Unknown`, and an `Unknown` branch is a `#define` that never becomes evidence. That is why
/// nothing from `combaseapi.h` reached `commdlg.h`.
///
/// So the walk visits the closure in **include order** (depth first: the first `#include` of a file is read
/// before its second, and before the file's own next sibling) and feeds every definition it puts in force into
/// [`UnitState`]. Only **definedness** is carried, never values: a file's body is text whose meaning the parser
/// owns, so a name the walk has seen defined answers `#ifdef`/`defined()` and leaves a *value* question to the
/// compilation's own table — a lost reading rather than a wrong branch.
///
/// `all_from` moves every entry onto one offset, which is what reading a file *inside* another one needs; without it
/// each entry lands where its own `#include` ended.
fn walk_the_translation_unit<'a>(
    summary: &'a FileSummary,
    only_before: Option<usize>,
    all_from: Option<usize>,
    mut look_up: impl FnMut(&std::path::Path) -> Option<(&'a FileSummary, &'a str)>,
    seed: &Marked,
    definitions_of: &mut MacroDefinitions,
    cache: &crate::index::walk_cache::WalkCache,
) -> ClosureEvidence {
    let mut walked = Walked::default();
    let mut unit = UnitState {
        definitions: Default::default(),
        generation: 0,
    };

    // **One visited set for the whole unit, not one per top-level include.** It is what makes the re-entry guards
    // fire at all: `walk_one_file` skips a second read only when `already_read` is true, and a fresh set per include
    // made it false at every top-level include's first entry into a file — so a guarded header included by five
    // others was read five times, and every header it includes five times more. Measured on `Util/src/Url.cpp` with
    // the walk census: **380 538 entries over 117 distinct files** (ratio 3 252) and a walk that did not finish in
    // minutes at 6 GB; with one set it is 117 entries.
    //
    // The unguarded header keeps being re-read, which is the deliberate half: `bits/version.h` is included by every
    // libstdc++ header for the feature-test macros that header asks for, it has no guard, and skipping it dropped
    // `__cpp_lib_print`. The two skips in `walk_one_file` are `#pragma once` and the `#ifndef X / #define X` idiom,
    // and both are *unit-wide* facts, not per-include ones.
    let mut seen: std::collections::HashSet<&std::path::Path> = std::collections::HashSet::new();
    for include in &summary.includes {
        // The includes are facts in source order, so the first one at or past the limit ends the walk.
        if only_before.is_some_and(|limit| include.range.start_offset >= limit) {
            break;
        }

        let Some(root) = include.resolved.as_deref() else {
            continue;
        };
        let from_offset = all_from.unwrap_or(include.range.start_offset + include.range.length);

        walk_one_file(
            root,
            from_offset,
            None,
            0,
            0,
            &mut seen,
            &mut look_up,
            seed,
            definitions_of,
            &mut unit,
            &mut walked,
            false, /* this path builds no unit, so nothing to share */
            cache,
        );
    }

    walked.into_evidence()
}

/// **A translation unit walked once, kept as a timeline any file inside it can be read from.**
///
/// # The problem this exists for
///
/// The per-file reading — "walk *this* file's include closure and hand it the result" — costs one full walk of the
/// closure **per file**, and the census says what that is: 255 files of the Windows SDK corpus, 2 489 142 macro
/// entries materialised, **17 618 794 conditional facts evaluated**, 147 s of a 174 s run. Every header's `#if`s
/// are answered ~255 times, because each file's environment is built as if it were the only one.
///
/// # What a preprocessor does instead
///
/// It walks the unit **once** and keeps, per identifier, the history of its macro directives — each carrying the
/// **location** (file + offset) it was written at (clang: `IdentifierInfo`'s directive chain, whose entries hold a
/// `SourceLocation`; a query is "walk the chain and stop at this location"). Every later question is a *position*
/// in that one walk: a header's macro state is the state at the point it was included, not a separate walk.
///
/// This type is that timeline. `events` is the whole unit's macro history in walk order; `frames` records where
/// each file was entered, so a file's view is its **inherited prefix** (`entry_seq`), its **own facts**, and the
/// facts of the files it includes (visible from the offset the `#include` ended at). No walk is repeated, no body
/// is copied, and a condition is evaluated once for the whole corpus instead of once per file.
///
/// # Frames, and why the subtree is an interval
///
/// Frames are created in **DFS preorder** — a file's dependencies are walked before the next sibling — so the
/// subtree of frame `f` is exactly the frame indices `f..tout[f]`, and "is this event visible from that file" is
/// an integer comparison rather than a walk up the parent chain.
pub struct TranslationUnit {
    pub(crate) events: Vec<TuEvent>,
    pub(crate) frames: Vec<TuFrame>,
    /// **The name index**: one entry per macro name the walk saw, holding its events' indices in walk order.
    ///
    /// This is what makes a file's environment a *view* rather than a map. Without it, answering "what is `_STD`
    /// here" means looking at every event in the unit; with it, the question is a hash and a walk of that name's
    /// own history — and a name's history is short, because a header defines a name once.
    ///
    /// The key is the **shared** `Arc<str>` the event already holds, so indexing the unit allocates no strings;
    /// [`std::borrow::Borrow`] is what lets a query with a `&str` find it without building a key.
    ///
    /// Derived state, like [`TranslationUnit::paths`]: it is a function of `events`, so it is built by the
    /// constructors rather than stored in the cache format.
    pub(crate) by_name: std::collections::HashMap<std::sync::Arc<str>, Vec<u32>>,
    /// **The unit's [UnitDefinitions], built at most once** — the second pass asks for them again for every slice
    /// that reuses this timeline, and building them is a walk of every event with an Arc per definition.
    ///
    /// A pure function of the unit, which is why it can live here: nothing in the unit changes after the walk.
    /// Measured: the pass asked for ~8 units' definitions per slice, 81 slices, ~2.6 ms each — 1.7 s of a 5.8 s
    /// second pass.
    /// **The frame paths**: for each frame, the frames it is nested in, each with the offset in that ancestor at
    /// which this frame's text becomes live — `(outermost include's ancestor, offset)`, nearest ancestor first.
    ///
    /// One entry per (frame, ancestor) pair, so the whole table is a few thousand `(u32, usize)` for a corpus and
    /// it answers [`TranslationUnit::offset_in`] without walking the parent chain — a query the parser makes for
    /// every name it asks about, in every file.
    ///
    /// Derived state: the parents and the `from_in_parent` offsets already say all of it.
    pub(crate) paths: Vec<Vec<(u32, usize)>>,
    /// The frame a file was entered as, the **first** time the walk reached it. A file included twice is walked
    /// once (see `walk_one_file`), so a second entry has no frame of its own.
    ///
    /// **Keyed by the normalized spelling**, because the same file reaches a walk in more than one:
    /// a project file is listed by a directory scan as `C:\Users\…\LSP.h` and included by its
    /// neighbours as `c:/users/…/lsp.h`, and a cache entry is keyed by the normalized form — so one
    /// unit can be written under one spelling and read back under the other.
    entered: std::collections::HashMap<String, u32>,
    /// The same two counters [`ClosureEvidence`] reports, for the same reason: they say whether the corpus was
    /// conditional at all and whether the environment could answer.
    pub conditional_facts: usize,
    pub facts_in_force: usize,
    /// **The `#define`s the walk decided are *not* compiled**, by file and directive offset.
    ///
    /// The walk evaluates every guarded macro fact against the unit's own state ([`UnitMacros`]) — the same
    /// evaluation the cook uses, and the only one that knows what the compilation defines. A fact it skips is a
    /// `#define` a compiler would not have read, and the counters above say *how many* there were; this says
    /// **which**, because a consumer needs to act on it.
    ///
    /// What acts on it: a file's **summary**, which is built from the raw reading and keeps every `#define` with the
    /// region it was written in. Left alone, a consumer decides that region a second time against a different
    /// environment and answers differently. Measured on `vcruntime.h`, which writes `_STL_LANG` once per branch of
    /// `#ifdef __cplusplus`: the walk takes the `_MSVC_LANG` branch and skips the `#else`'s `0L`, while a lookup over
    /// the raw facts answers `0L` — for a file the compiler reads as C++20.
    ///
    /// Not in the cache format: a stored timeline is rebuilt from its events, and this is a function of them **and
    /// the environment that walked them** — a field that was *written* could disagree with what it derives from.
    pub(crate) dead_macros: std::collections::HashMap<std::path::PathBuf, Vec<usize>>,
}

/// One macro fact of the unit, with **where** it was written and **which frame** it belongs to.
///
/// `pub(crate)` for the codec, which writes these records to the cache: the type is the unit's own shape, and the
/// alternative — a second struct in the codec that mirrors it — is a second place for a field to be forgotten.
#[derive(Clone, Debug)]
pub(crate) struct TuEvent {
    pub(crate) name: std::sync::Arc<str>,
    /// `None` for an `#undef`.
    pub(crate) function_like: Option<bool>,
    /// The shape of the replacement list, as the parser reads it.
    pub(crate) body: Option<cpp_parser::MacroBody>,
    /// The replacement list as text — **shared**, see [`cpp_parser::IncludedMacro::body_text`].
    pub(crate) body_text: Option<std::sync::Arc<str>>,
    pub(crate) parameters: Option<std::sync::Arc<str>>,
    /// Where the **replacement list** is, in the file that wrote it.
    ///
    /// Kept so that a definition this unit hands to the cooker can carry **real positions**: the body's text is
    /// already here, and with its range the tokens lexed from it land where they were written instead of inside a
    /// line this crate reconstructed ([`crate::macros::MacroDef::written_in`]). `None` for an `#undef` and for a
    /// `#define` whose replacement list is empty — there is nothing to place.
    pub(crate) body_range: Option<cpp_parser::SourceRange>,
    pub(crate) frame: u32,
    /// The offset **inside the file that wrote it**.
    pub(crate) at: usize,
    /// Was the fact unconditional? The two channels of [`ClosureEvidence`], which is a measured distinction and
    /// not this type's to collapse.
    pub(crate) unconditional: bool,
}

impl TuEvent {
    /// **Is this event an `#undef`?** — the shape [`TimelineBuilder::record`] writes for one, and only for one.
    ///
    /// A definition carries both its `function_like` answer and its body, unconditionally (`then_some` on a
    /// definition is always `Some`); an `#undef` carries neither. That is why this is not "no body": a definition
    /// whose replacement list nobody stored still has its `MacroBody`.
    pub(crate) fn is_an_undef(&self) -> bool {
        self.function_like.is_none()
    }
}

/// Where one file was entered, and how much of the timeline was already behind it.
#[derive(Clone, Debug)]
pub(crate) struct TuFrame {
    pub(crate) file: std::path::PathBuf,
    pub(crate) parent: Option<u32>,
    /// Where this file's text comes into force **in its parent**: the end of the `#include` that brought it in.
    pub(crate) from_in_parent: usize,
    /// How many events the walk had emitted when this frame was entered — everything before it is in force from
    /// offset 0 of this file, which is what a header's own first line sees.
    pub(crate) entry_seq: u32,
    /// The end of this frame's subtree, as a frame index (see the type's note on preorder).
    pub(crate) tout: u32,
    /// **The file writes `#pragma once`** — see [`SummaryGuards::visit_once`]. Carried on the frame because the
    /// renderer walks frames rather than summaries, and a file that is only directives has no tokens of its own to
    /// carry the pragma into the stream.
    pub(crate) visit_once: bool,
}

/// The timeline under construction — the sink [`Walked`] records into while the one walk runs.
#[derive(Default)]
struct TimelineBuilder {
    events: Vec<TuEvent>,
    frames: Vec<TuFrame>,
    entered: std::collections::HashMap<String, u32>,
}

impl TimelineBuilder {
    /// Open a frame for a file the walk is about to read, and return its id.
    fn enter(
        &mut self,
        file: &std::path::Path,
        parent: Option<u32>,
        from_in_parent: usize,
        visit_once: bool,
    ) -> u32 {
        let id = self.frames.len() as u32;
        self.frames.push(TuFrame {
            file: file.to_path_buf(),
            parent,
            from_in_parent,
            visit_once,
            entry_seq: self.events.len() as u32,
            // Closed by `leave`; a frame that is never left is the last one, and its subtree runs to the end.
            tout: u32::MAX,
        });
        self.entered.entry(frame_key(file)).or_insert(id);
        id
    }

    fn leave(&mut self, frame: u32) {
        self.frames[frame as usize].tout = self.frames.len() as u32;
    }

    /// Record one fact the walk put in force.
    fn record(&mut self, frame: u32, fact: &MacroFact, source: &str, unconditional: bool) {
        let body_text = fact
            .body_range
            .and_then(|range| source.get(range.start_offset..range.start_offset + range.length))
            .map(std::sync::Arc::from);
        let parameters = fact
            .body_range
            .and_then(|range| parameters_before(source, range.start_offset))
            .map(std::sync::Arc::from);

        self.events.push(TuEvent {
            name: std::sync::Arc::from(&*fact.name),
            function_like: fact.kind.is_definition().then_some(fact.function_like),
            body: fact.kind.is_definition().then_some(fact.body),
            body_text,
            parameters,
            body_range: fact.body_range,
            frame,
            at: fact.range.start_offset,
            unconditional,
        });
    }
}

impl TranslationUnit {
    /// **What this unit costs in memory** — frames, events, the name index, and the definitions cache.
    ///
    /// A unit is a *timeline*: one event per `#define`/`#undef` in the whole closure, each holding shared name and
    /// body strings. It is kept whole in the unit table (`MAX_UNITS` of them), which is what makes the number worth
    /// measuring: on a header-heavy closure it is megabytes, and sixty-four of them is not a number to guess.
    pub fn heap_bytes(&self) -> usize {
        let mut bytes = std::mem::size_of::<TranslationUnit>();
        for frame in &self.frames {
            bytes += std::mem::size_of::<TuFrame>() + frame.file.as_os_str().len();
        }
        for event in &self.events {
            bytes += std::mem::size_of::<TuEvent>()
                + event.name.len()
                + event.body_text.as_ref().map_or(0, |text| text.len())
                + event.parameters.as_ref().map_or(0, |text| text.len());
        }
        for key in self.entered.keys() {
            bytes += key.len() + std::mem::size_of::<u32>();
        }
        bytes
    }

    /// Walk a translation unit **once**, from the file that starts it.
    ///
    /// `look_up` answers for a path with the file's summary and its text, the same contract the per-file walks
    /// take; a file it cannot answer for is outside the analysis and defines nothing (see `walk_one_file`).
    pub fn walk<'a>(
        root: &'a FileSummary,
        mut look_up: impl FnMut(&std::path::Path) -> Option<(&'a FileSummary, &'a str)>,
        seed: &Marked,
        definitions_of: &mut MacroDefinitions,
        share: bool,
        cache: &crate::index::walk_cache::WalkCache,
    ) -> Self {
        let mut walked = Walked {
            timeline: Some(TimelineBuilder::default()),
            ..Walked::default()
        };
        let mut unit = UnitState {
            definitions: Default::default(),
            generation: 0,
        };
        let mut seen: std::collections::HashSet<&std::path::Path> =
            std::collections::HashSet::new();

        // The root is walked by the same function every included file is: it *is* a file of the unit, and a
        // second entry point for it would be a second place for the include order to be got wrong.
        let _root_key = walk_one_file(
            &root.path,
            0,
            None,
            0,
            0,
            &mut seen,
            &mut look_up,
            seed,
            definitions_of,
            &mut unit,
            &mut walked,
            share,
            cache,
        );

        let timeline = walked.timeline.take().expect("just built");
        let mut built = TranslationUnit::from_parts(
            timeline.events,
            timeline.frames,
            walked.conditional_facts,
            walked.facts_in_force,
        );
        // **The walk's own decision, kept.** `from_parts` cannot know it — it is a function of the events *and the
        // environment that walked them* — so the walk hands it over rather than deriving it again. See
        // [`TranslationUnit::dead_macros`].
        built.dead_macros = walked.dead_macros;
        built
    }

    /// Rebuild a timeline from its parts — the decoder's constructor, and the only caller that may hand this type
    /// a `frames` vector it did not build itself.
    ///
    /// Three fields are recomputed here rather than stored, because all three *are* statements about the parts:
    /// `entered` is "the frame each file was first entered as" (the frames say it), the name index is a function of
    /// the events, and the frame paths are a function of the parents and their offsets. The cache format stores the
    /// parts and nothing else — see [`crate::summary_codec`], whose whole contract is that a field is written only
    /// when it cannot be derived, since a derived field that was *written* could disagree with what it derives
    /// from.
    pub(crate) fn from_parts(
        events: Vec<TuEvent>,
        frames: Vec<TuFrame>,
        conditional_facts: usize,
        facts_in_force: usize,
    ) -> Self {
        let mut entered: std::collections::HashMap<String, u32> = std::collections::HashMap::new();
        for (index, frame) in frames.iter().enumerate() {
            entered
                .entry(frame_key(&frame.file))
                .or_insert(index as u32);
        }

        let mut by_name: std::collections::HashMap<std::sync::Arc<str>, Vec<u32>> =
            std::collections::HashMap::new();
        for (index, event) in events.iter().enumerate() {
            // Walk order, which is the order the queries rely on: the last entry of a name's list is the last fact
            // the walk put in force for it.
            by_name
                .entry(std::sync::Arc::clone(&event.name))
                .or_default()
                .push(index as u32);
        }

        let mut paths: Vec<Vec<(u32, usize)>> = Vec::with_capacity(frames.len());
        for frame in &frames {
            // Nearest ancestor first, and each one's offset is the `from_in_parent` of the **child** on the path —
            // that is the frame whose text is this frame's, so a fact written here is in force in that ancestor
            // from exactly that offset. Read off the ancestor already built, so the whole table is one pass.
            let mut path = Vec::new();
            let mut offset = frame.from_in_parent;
            let mut parent = frame.parent;
            while let Some(ancestor) = parent {
                path.push((ancestor, offset));
                let reached = &frames[ancestor as usize];
                offset = reached.from_in_parent;
                parent = reached.parent;
            }
            paths.push(path);
        }

        TranslationUnit {
            events,
            frames,
            by_name,
            paths,
            entered,
            conditional_facts,
            facts_in_force,
            // **Empty when a stored timeline is read back**, and that is a statement about the cache rather than
            // about the walk: the decision belongs to the environment that made it, and a decode has no environment.
            // A caller that needs it re-walks — which is what the store does when it rebuilds a summary.
            dead_macros: std::collections::HashMap::new(),
        }
    }

    /// How many macro facts the unit's walk put in force — the size of the timeline.
    pub fn len(&self) -> usize {
        self.events.len()
    }

    /// **Read every definition this unit carries, once** — with the positions it was written at.
    ///
    /// This is what replaced the per-file configuration build. Cooking a file used to walk its whole environment
    /// — every name the unit knows — parse each definition and copy the result into a table of that file's own,
    /// which the census measured at **4.1 s** for 255 files of the SDK corpus, on top of the map the environment
    /// itself built (1.7 s). The definitions are the *same* definitions every time: a fact's identity is its name,
    /// its parameters and its body, and none of those depend on which file is asking. Only the **offset** does,
    /// and the offset is resolved per query by [`MacroView`].
    ///
    /// So a run reads the unit once and every file's cook is a lookup. Nothing here is per file, and the counters
    /// below are therefore counted **once for the unit** rather than once per file: they say how much of the
    /// unit's vocabulary expansion cannot use, where the per-file version counted each unusable fact once per file
    /// that could see it (`without_a_body` × 200 is not a measurement of the corpus).
    ///
    /// # The positions are the file's, not a reconstruction's
    ///
    /// A definition is read out of the fact's **own** parameter list and replacement list — the two substrings the
    /// walk copied out of the file that wrote them — and lexed with their offsets shifted to where they sit:
    /// `TuEvent::body_range` for the body, and the name plus its length for the parameter list. So a body
    /// token's range is where the token is, `written_in` says which file that is
    /// ([`crate::macros::MacroFile::Frame`]), and a consumer can act on the answer instead of on an offset in a
    /// line this crate wrote. Definitions that arrive without a position ([`crate::macros::MacroFile`]'s third
    /// case) still exist — the closure path's `MacroEnvironment` carries text only — and they say so.
    /// **[TranslationUnit::definitions].** No longer cached: building the table is a slot per event and no lexing, so
    /// a cache in front of it bought nothing — and the one this replaced could not be expressed any more, because the
    /// table borrows the unit's events.
    pub fn definitions_cached(&self) -> UnitDefinitions<'_> {
        self.definitions()
    }

    pub fn definitions(&self) -> UnitDefinitions<'_> {
        // **A slot per event, nothing lexed.** A body is read the first time the cook asks for it, which is what makes
        // this table cheap to build and is why the cache that used to sit in front of it is gone — see
        // [`UnitDefinitions::of`] for the measurement.
        let mut by_event: Vec<
            Option<std::sync::OnceLock<Option<std::sync::Arc<crate::macros::MacroDef>>>>,
        > = (0..self.events.len()).map(|_| None).collect();
        let mut function_like_without_parameters = 0usize;
        let mut without_a_body = 0usize;
        let mut in_force_without_a_parameter_list = 0usize;

        for (index, event) in self.events.iter().enumerate() {
            let Some(body) = event.body_text.as_ref() else {
                // A fact with no replacement list is not a definition this reader can paste — but only the
                // **definition** channel counts it: the in-force channel is defined by having a body.
                if event.unconditional && event.function_like.is_some() {
                    without_a_body += 1;
                }
                continue;
            };
            let _ = body;

            if !event.unconditional {
                // The in-force channel: a body a condition settled, usable only when the caller classified the
                // macro as object-like or carried its parameter list — see `Configuration`'s note.
                match event.function_like {
                    Some(false) => {}
                    Some(true) if event.parameters.is_some() => {}
                    _ => {
                        in_force_without_a_parameter_list += 1;
                        continue;
                    }
                }
            } else {
                // The definition channel: a definition whose parameter list nobody carried cannot be pasted, and
                // one whose shape the walk could not read is not a definition at all.
                match (event.function_like, event.body) {
                    (Some(true), _) if event.parameters.is_none() => {
                        function_like_without_parameters += 1;
                        continue;
                    }
                    (Some(_), Some(_)) => {}
                    _ => continue,
                }
            }

            // **Classification only** — the body is lexed when the slot is first asked for. The event index is all a
            // slot needs to carry, because this table borrows the events.
            by_event[index] = Some(std::sync::OnceLock::new());
        }

        UnitDefinitions {
            unit: self,
            by_event,
            function_like_without_parameters,
            without_a_body,
            in_force_without_a_parameter_list,
            unreadable: std::sync::atomic::AtomicUsize::new(0),
        }
    }

    /// The path of a frame — how a [`crate::macros::MacroFile::Frame`] becomes something a consumer can open.
    pub fn frame_file(&self, frame: u32) -> Option<&std::path::Path> {
        self.frames
            .get(frame as usize)
            .map(|frame| frame.file.as_path())
    }

    /// How many of those facts carry a **replacement list**, and how many are in the **in-force** channel.
    ///
    /// The two numbers the census prints beside the entry count, because "the evidence arrived" and "the evidence
    /// arrived with bodies" are different states of the world and the second is what expansion needs. They are
    /// answered here rather than left to a caller to re-derive: a caller that counted them itself would be a
    /// second implementation of what an event is.
    pub fn bodies(&self) -> (usize, usize) {
        let with_a_body = self
            .events
            .iter()
            .filter(|event| {
                event
                    .body_text
                    .as_deref()
                    .is_some_and(|text| !text.trim().is_empty())
            })
            .count();
        let in_force = self
            .events
            .iter()
            .filter(|event| !event.unconditional)
            .count();
        (with_a_body, in_force)
    }

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

    /// The files the walk entered, in the order it entered them.
    pub fn files(&self) -> impl Iterator<Item = &std::path::Path> {
        self.frames.iter().map(|frame| frame.file.as_path())
    }

    /// Every macro fact the unit put in force **in one file**, in walk order, as `(name, offset in that file)`.
    ///
    /// The timeline itself rather than a view of it, and the difference is the whole contract of
    /// [`TranslationUnit::environment_of`]: this is what the file **wrote**, that is what the file **sees**. A
    /// caller asking "what does this header define" wants this one; a caller asking "is this name a macro here"
    /// wants the environment. Both are real questions about one record, which is why the record keeps the file and
    /// the offset of every fact rather than only the ones a view happens to use.
    pub fn facts_of<'unit>(
        &'unit self,
        path: &'unit std::path::Path,
    ) -> impl Iterator<Item = (&'unit str, usize)> {
        let frame = self
            .frames
            .iter()
            .position(|frame| frame.file == path)
            .map(|index| index as u32);

        self.events
            .iter()
            .filter(move |event| Some(event.frame) == frame)
            .map(|event| (&*event.name, event.at))
    }

    /// The environment of a file **as this unit sees it**, or `None` when the unit never reaches it.
    ///
    /// `None` is the honest answer for a file nothing includes: nothing in this translation unit says what it
    /// sees, and inventing a context for it is what the earlier per-file census did with a heuristic.
    pub fn environment_of(&self, path: &std::path::Path) -> Option<MacroView<'_>> {
        let &frame = self.entered.get(&frame_key(path))?;
        Some(self.environment_at(frame))
    }

    /// The environment of the file the unit starts with.
    pub fn root_environment(&self) -> MacroView<'_> {
        self.environment_at(0)
    }

    /// One file's environment as **a position in this timeline** — no walk, no copy of the bodies, and no map.
    ///
    /// The three kinds of event a file's environment is made of, and the offset each is in force from:
    ///
    /// * the facts of the files it **includes**, from the offset the `#include` ended at — a definition three
    ///   includes down is in force in this file from the **outermost** `#include` on the path, which is
    ///   [`TranslationUnit::offset_in`]'s question;
    /// * everything the walk had already emitted when this file was entered (the **inherited prefix**), from
    ///   offset 0 — the state a header's first line sees, which is what the old one-hop includer lookup was
    ///   approximating and what the real translation unit knows exactly;
    /// * and **not** the file's own facts.
    ///
    /// The exclusion is the caller's contract and not an optimisation: a file's own `#define`s are what *it* says,
    /// and the parser reads them itself out of the text it is parsing (that is what `MacroNames` is). Handing them
    /// back as "the includes contributed this" would double-count them, and — worse — would say a name is a macro
    /// from its own `#define` line in a branch the reader cannot evaluate. What the environment is *for* is what
    /// the file cannot see by looking at itself.
    ///
    /// # Why this is a view and not a map
    ///
    /// It used to build a `MacroEnvironment`: one entry per name in force, each with the offset it applies from.
    /// That is the whole environment materialised per file, and the census measured what it costs — **1.7 s of a
    /// 13.8 s run** for 255 files of the Windows SDK corpus, in map builds alone, with every file paying for the
    /// names it never asks about. A view answers the *same* questions out of the unit's name index, lazily: a query
    /// is a hash of the name and a walk of that name's own (short) history, which is what the parser does per token
    /// and all it ever needed.
    ///
    /// The answers are not merely equivalent, they are the same rule: for one name, everything visible to a file
    /// has an offset that **does not decrease** in walk order — the inherited prefix is all at offset 0, and the
    /// includes are walked in text order — so "the last one in walk order" *is* "the last one in force", and the
    /// final binding is the only one that can be in force at any offset. That is the same collapse the map did
    /// (last wins per name), read at the offset it is asked about instead of frozen at build time.
    fn environment_at(&self, frame: u32) -> MacroView<'_> {
        MacroView { unit: self, frame }
    }

    /// The offset in `consumer` at which `frame`'s text becomes live: the `#include` end of the **outermost**
    /// frame on the path from `consumer` to `frame`.
    ///
    /// Read out of the precomputed frame paths ([`TranslationUnit::paths`]) rather than walked per query: this is
    /// on the parser's per-token path (the offset of every inherited fact is this answer), and a chain walk per
    /// query would trade a map build for a pointer chase.
    fn offset_in(&self, frame: u32, consumer: u32) -> usize {
        self.paths[frame as usize]
            .iter()
            .find(|(ancestor, _)| *ancestor == consumer)
            .map(|(_, offset)| *offset)
            // A frame outside the consumer's subtree never gets here — the caller's interval test is what keeps it
            // out — so this is the root, and offset 0 is the only answer that means anything.
            .unwrap_or(0)
    }

    /// **Cook the whole unit into one stream** — every file the walk reached, in the order a compiler reads them.
    ///
    /// This is the other half of the readings: cooking one file at a time answers "does this header read on its
    /// own" ([`TranslationUnit::environment_of`] is the state, `cook_with` is the cook), and this answers "does
    /// the program read". The order is the walk's own (frames are in DFS preorder, which is include order) and the
    /// splice points are `from_in_parent` — the offset in the parent where the `#include` that brought the child
    /// in ended.
    ///
    /// `definitions` is the unit's once-read definition table ([`TranslationUnit::definitions`]) and `seed` is
    /// what the compilation predefines; `sources` is where the *text* comes from, which is the caller's business
    /// (a disk provider, an editor's buffers, a test's fixtures). A file the caller has no text for is a hole:
    /// counted in [`RenderedUnit::missing`] and its includes are still stitched, because a compilation that is
    /// missing one header still reads the ones below it.
    pub fn cook_the_unit(
        &self,
        sources: &dyn crate::preprocess::macros::UnitSources,
        definitions: &UnitDefinitions,
        seed: Option<&crate::macros::MacroTable>,
        use_in_force_bodies: bool,
        search: Option<&dyn crate::preprocess::cooked::HeaderSearch>,
    ) -> RenderedUnit {
        let mut out = RenderedUnit {
            files: self.frames.iter().map(|frame| frame.file.clone()).collect(),
            file_lengths: self
                .frames
                .iter()
                .map(|frame| {
                    sources
                        .source_of(&frame.file)
                        .map(|text| text.len())
                        .unwrap_or_default()
                })
                .collect(),
            ..RenderedUnit::default()
        };
        let mut cook = UnitCook {
            unit: self,
            sources,
            definitions,
            seed,
            use_in_force_bodies,
            search,
            // Which frames each frame includes, in the order it includes them. Frames are created in preorder, so
            // a parent's children are already in include order and pushing in index order keeps it.
            children: {
                let mut children: Vec<Vec<u32>> = vec![Vec::new(); self.frames.len()];
                for (index, frame) in self.frames.iter().enumerate() {
                    if let Some(parent) = frame.parent {
                        children[parent as usize].push(index as u32);
                    }
                }
                children
            },
            state: crate::preprocess::cooked::CookingState::default(),
        };

        // **The frame tree**, when the unit trace is on: what the renderer will walk, in the order it walks it. A
        // disagreement with cl.exe's `#line` sequence is a disagreement about include order, and this is our half of
        // that comparison — `cl /E` on the same interface unit is the other, and it costs 0.4 s.
        if crate::probes::units() && !self.frames.is_empty() {
            for (index, frame) in self.frames.iter().enumerate() {
                eprintln!(
                    "[frame] {index:3} {} parent {:?} at {}",
                    frame.file.file_name().unwrap_or_default().to_string_lossy(),
                    frame.parent,
                    frame.from_in_parent
                );
            }
        }

        if !self.frames.is_empty() {
            cook.stitch(0, &mut out);
        }
        out
    }
}

/// One unit's cook, in progress: the invariants [`TranslationUnit::cook_the_unit`] was handed, and the include
/// tree the stitch walks.
///
/// A struct rather than six arguments because the stitch is recursive and every frame needs all of them — the
/// alternative is the same list at every call, which is how a recursion ends up disagreeing with itself.
struct UnitCook<'unit> {
    unit: &'unit TranslationUnit,
    sources: &'unit dyn crate::preprocess::macros::UnitSources,
    definitions: &'unit UnitDefinitions<'unit>,
    seed: Option<&'unit crate::macros::MacroTable>,
    use_in_force_bodies: bool,
    /// **What `__has_include` is answered from** — the include search, or `None` when the caller has none and the
    /// operator must answer `Unknown` rather than guess. See [`crate::preprocess::cooked::HeaderSearch`].
    search: Option<&'unit dyn crate::preprocess::cooked::HeaderSearch>,
    /// For each frame, the frames it includes, in include order.
    children: Vec<Vec<u32>>,
    /// **The macros the cook has executed so far** — one table for the whole program, in the order the text wrote
    /// them. See [`crate::preprocess::cooked::CookingState`]: a preprocessor has one table, not a view per file.
    state: crate::preprocess::cooked::CookingState,
}

impl UnitCook<'_> {
    /// Cook one frame and splice each include's stream in where the `#include` ended.
    /// **Cook one frame into the stream**, in the order a preprocessor reads it: the text before an `#include`, then
    /// the included file, then the text after it.
    ///
    /// The table is the program's ([`crate::preprocess::cooked::CookingState`]), carried across frames, so a `#define`
    /// from a header is in force for what follows the `#include` — which a whole-file cook cannot show, because it
    /// finishes the file before the include is stitched.
    fn stitch(&mut self, frame: u32, out: &mut RenderedUnit) {
        // Copied out first: the stitch borrows `self` mutably for its table, and these are plain handles.
        let included: Vec<u32> = self.children[frame as usize].clone();
        let unit = self.unit;
        let sources = self.sources;
        let definitions = self.definitions;
        let seed = self.seed;
        let use_in_force_bodies = self.use_in_force_bodies;
        let search = self.search;

        let Some(text) = sources.source_of(&unit.frames[frame as usize].file) else {
            // A file nobody has the text of: the includes it names are still stitched (the walk reached them through
            // it), and the hole is counted rather than cooked as an empty file.
            out.missing += 1;
            for &child in &included {
                self.stitch(child, out);
            }
            return;
        };

        let (tokens, _) = cpp_parser::lex(text, &cpp_parser::LexerConfig::default());
        // **The frame's own environment is the floor.** What the program's cook has already executed sits on top of it
        // in `self.state`: a name the rendering has passed is answered by the table, one it has not reached by the view
        // — a change of state, not of policy. The view is a local because the renderer borrows it: it is two words,
        // and `FileMacros` reads it through the trait rather than owning it.
        let frame_view = unit.environment_at(frame);
        let initial = crate::preprocess::cooked::FileMacros::new(
            &frame_view,
            definitions,
            seed,
            use_in_force_bodies,
        );
        let directory = unit.frames[frame as usize]
            .file
            .parent()
            .unwrap_or_else(|| Path::new("."));

        let mut from = 0usize;
        let mut produced = 0usize;
        let mut depth = 0i64;
        for &child in &included {
            let at = unit.frames[child as usize].from_in_parent;
            // The first token at or after the `#include`: everything before it is text the include does not cover.
            let boundary = tokens
                .iter()
                .position(|token| token.range.start_offset >= at)
                .unwrap_or(tokens.len())
                .max(from);
            let cook = crate::preprocess::cooked::cook_with_search_and_state(
                text,
                &tokens[from..boundary],
                &initial,
                &mut self.state,
                search,
                directory,
            );
            produced += cook.tokens.len();
            depth += self.emit(frame, &cook, out);
            self.stitch(child, out);
            from = boundary;
        }
        let cook = crate::preprocess::cooked::cook_with_search_and_state(
            text,
            &tokens[from..],
            &initial,
            &mut self.state,
            search,
            directory,
        );
        produced += cook.tokens.len();
        depth += self.emit(frame, &cook, out);

        // **A file whose text goes in but whose braces do not balance** would swallow every file spliced after it, so
        // this is the count that finds the file — **recorded rather than acted on**. See [`RenderedUnit::unbalanced`]
        // for why the text goes in anyway.
        if depth != 0 {
            out.unbalanced
                .push(unit.frames[frame as usize].file.clone());
        }

        // **`#pragma once`, for a file that has nothing else to carry it.** A file with tokens of its own already has
        // the pragma in them; what is missing is the header that is **nothing but directives** — `yvals_core.h` and
        // its neighbours — whose `#pragma once` would otherwise never reach the stream. A compiler keeps the line, and
        // it is how a reader sees *which files a compilation read*: measured on `#include <vector>`, `cl.exe` emits 54
        // of them. It is emitted after the segments because whether the file produced a token is only known once they
        // have been cooked; for a file with no token at all, "after" and "before" are the same place.
        if unit.frames[frame as usize].visit_once && produced == 0 {
            let here = cpp_parser::SourceRange::new(0, 0);
            out.break_line_before_next();
            for spelling in ["#", "pragma", "once"] {
                out.push(spelling, frame, here, None);
            }
            out.break_line_before_next();
        }
    }

    /// **Emit one cooked segment of `frame`**: its messages, its tokens and its `#pragma` lines.
    ///
    /// Returns the segment's brace balance; the caller sums the segments into the file's own, which is the count
    /// [`RenderedUnit::unbalanced`] is made of.
    fn emit(
        &self,
        frame: u32,
        cook: &crate::preprocess::cooked::CookedStream,
        out: &mut RenderedUnit,
    ) -> i64 {
        // **What this file said**, in its own coordinates: a `#error` in a branch nobody compiles is not said, and the
        // range each message carries is the directive's own — a position in *this* file, not in the rendering.
        for (kind, message, at) in &cook.messages {
            out.messages.push(UnitMessage {
                file: self.unit.frames[frame as usize].file.clone(),
                fatal: matches!(kind, crate::DirectiveKind::Error),
                message: message.clone(),
                at: *at,
            });
        }

        let mut depth = 0i64;
        let mut lines = cook.pragma_lines.iter().peekable();
        for (index, token) in cook.tokens.iter().enumerate() {
            match token.text() {
                "{" => depth += 1,
                "}" => depth -= 1,
                _ => {}
            }
            // **Where the token stands in this file** — the call site for an expansion, the token's own range for text
            // the file wrote. Both are positions in *this* file; see `ExpandedToken::diagnostic_range`.
            let at = token.diagnostic_range();
            // **What decides the separator**: for the file's own text, byte adjacency in that file (the range test in
            // [`RenderedUnit::push`]); for what the cook produced, the expander's own answer — its ranges are the call
            // site's, so every token of one expansion would answer "not adjacent" and be spelled apart.
            let space_before = match token.origin {
                crate::preprocess::expand::Origin::Source => None,
                _ => Some(token.space_before),
            };
            while lines.next_if(|line| line.end <= index).is_some() {}
            // A `#pragma` is a line of its own — see [`crate::CookedStream::pragma_lines`].
            if lines.peek().is_some_and(|line| line.start == index) {
                out.break_line_before_next();
            }
            out.push(token.text(), frame, at, space_before);
            if lines.peek().is_some_and(|line| line.end == index + 1) {
                out.break_line_before_next();
            }
        }
        depth
    }
}

/// **A unit's definitions, read once** — what [`TranslationUnit::definitions`] produces, and what every file's
pub struct UnitDefinitions<'unit> {
    /// **Where the bodies are**, borrowed rather than copied: a definition is built from its event's own name,
    /// parameter list and replacement list, and all three already live in the unit.
    ///
    /// Lazy on purpose. The table used to lex **every** `#define` of the closure while the unit was prepared —
    /// measured on `import std;` at **78.8 M allocations**, more than the whole analysis — while the cook only ever asks
    /// for the bodies of macros it actually meets. A slot is filled on the first ask and remembered, so a name asked for
    /// twice is lexed once.
    unit: &'unit TranslationUnit,
    /// Parallel to `TranslationUnit::events`: the definition a fact becomes as a `#define` line, or `None` when that
    /// fact is not one this reader can put back together.
    by_event: Vec<Option<std::sync::OnceLock<Option<std::sync::Arc<crate::macros::MacroDef>>>>>,
    /// Definitions whose parameter list the evidence does not carry — a function-like macro that cannot be
    /// substituted into, so it is not in the table. Counted for the unit; see [`TranslationUnit::definitions`].
    pub function_like_without_parameters: usize,
    /// Definitions with no replacement list stored at all: nothing to expand.
    pub without_a_body: usize,
    /// Definitions whose replacement list did not read as a macro definition. Counted when the slot is first asked
    /// for, because that is when the definition is finally read — see [`UnitDefinitions::of`].
    unreadable: std::sync::atomic::AtomicUsize,
    /// Bodies that arrived through the in-force channel and could not be used — nobody said whether the macro
    /// takes parameters. See `Configuration::in_force_without_a_parameter_list`.
    pub in_force_without_a_parameter_list: usize,
}
impl UnitDefinitions<'_> {
    /// The bytes this table holds: one slot per event, and the definitions the slots have built.
    pub fn heap_bytes(&self) -> usize {
        let mut bytes = std::mem::size_of::<UnitDefinitions<'_>>()
            + self.by_event.capacity()
                * std::mem::size_of::<
                    Option<std::sync::OnceLock<Option<std::sync::Arc<crate::macros::MacroDef>>>>,
                >();
        for definition in self.by_event.iter().flatten().filter_map(|cell| cell.get()) {
            let Some(definition) = definition else {
                continue;
            };
            bytes += std::mem::size_of::<crate::macros::MacroDef>() + definition.name.len();
            if let Some(params) = &definition.params {
                bytes += params.len() * std::mem::size_of::<crate::preprocess::macros::Parameter>();
            }
        }
        bytes
    }

    /// **The definition the fact at `index` spells, built the first time it is asked for.**
    ///
    /// The body is lexed here rather than when the unit was prepared: on `import std;` the table holds tens of thousands
    /// of definitions and the cook meets a fraction of them, so the eager version lexed replacement lists nothing would
    /// ever expand. A slot remembers its answer — including "this one does not read" — so a second ask costs nothing.
    pub(crate) fn of(&self, index: u32) -> Option<&std::sync::Arc<crate::macros::MacroDef>> {
        let cell = self.by_event.get(index as usize)?.as_ref()?;
        cell.get_or_init(|| {
            let event = self.unit.events.get(index as usize)?;
            let body = event.body_text.as_deref()?;
            let built = definition_written_at(event, body).map(std::sync::Arc::new);
            if built.is_none() {
                self.unreadable
                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            }
            built
        })
        .as_ref()
    }

    /// How many facts of the unit spell a definition this reader could use.
    pub fn len(&self) -> usize {
        self.by_event.iter().filter(|it| it.is_some()).count()
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// **How many replacement lists did not read as a macro definition**, among the slots asked for so far — see
    /// [`Self::of`], which is where the count is made.
    pub fn unreadable(&self) -> usize {
        self.unreadable.load(std::sync::atomic::Ordering::Relaxed)
    }
}

/// **One file's environment, as a position in the unit's timeline** — the borrowed half of
/// `TranslationUnit::environment_at`.
///
/// A view is two words: the unit and the frame. Opening one is free, and that is the point: the census built 255
/// environments per corpus (1.7 s of materialised maps) for callers that ask about a handful of names each, and a
/// file's macro state is not a *thing* the unit owns — it is where the file sits in the walk.
///
/// The three questions a view answers, and the rule behind all of them:
///
/// * the file's **own** facts are invisible here (the parser reads those out of the text itself);
/// * a fact of a file this one **includes** is in force from the offset the outermost `#include` on the path ended
///   at — one `#include` is what a file's own text can name, however deep the definition was written;
/// * a fact from **before this file was entered** is in force from offset 0, which is what a header's first line
///   sees;
/// * and everything else — a later sibling, a file the unit reaches after this one — is not visible at all.
///
/// For one name, the offsets of everything it can see **do not decrease in walk order** (all of the inherited
/// prefix is at offset 0, and the walk follows `#include`s in text order), so the *last* visible fact for a name is
/// the only one that can be in force, and asking "what is it at this offset" is one comparison. That is what makes
/// a query a hash and a short walk rather than a materialised history — and it is why this answers exactly what the
/// map it replaced answered, which `tests/translation_unit.rs` asserts question by question.
///
/// `Copy` because a view **is** its two words: a caller that has one — to report about, to cook with — hands it on
/// without giving up its own, which is what a caller holding two readings of one file does.
#[derive(Clone, Copy)]
pub struct MacroView<'unit> {
    unit: &'unit TranslationUnit,
    frame: u32,
}

/// **What a name is at one position in one file** — the question a preprocessor asks and the one this crate could
/// not previously answer about a file it had only *read*.
///
/// Everything needed to answer it was already here; what was missing was a public door. The only way to ask it was to
/// **copy the file, inject an `#error` probe, and read the compiler's complaint** — and that probe changes the thing
/// being measured. Measured, and the reason this type exists:
///
/// ```text
/// the real `xtr1common`                      → cl emits [[msvc::no_specializations(...)]] 17 times
/// a copy with `#error` probes inserted       → cl says the attribute is NOT supported (0)
/// ```
///
/// A copy is not the file: an include guard, an include order, or a `#pragma push_macro` further up all move when
/// the text moves. So the answer has to come from the analysis's own timeline, which is what this reads.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MacroAt {
    /// Whether the name is a macro there. `false` covers both "undefined" and "`#undef`ed above this line".
    pub defined: bool,
    /// **The shape** of the replacement list, when the walk recovered one.
    ///
    /// A [`cpp_parser::MacroBody`] rather than the body's text, because that is what a later parse needs to know:
    /// whether the name expands to a type, a statement, an expression or nothing. The text is in
    /// [`MacroAt::body_text`], which is what a *reader* wants. `None` with [`MacroAt::defined`] true is a name the
    /// walk saw defined but whose shape it could not read — an honest gap rather than a claim that the body is empty.
    pub body: Option<cpp_parser::MacroBody>,
    /// **The replacement list as written** — what answers "so what does this name expand to?".
    pub body_text: Option<String>,
    /// Whether the definition takes arguments.
    pub function_like: bool,
    /// Where the binding in force was written: the file, and the offset in it. `None` when the binding came from
    /// outside the unit — a compiler builtin or a command-line `-D`.
    pub written_in: Option<std::path::PathBuf>,
    /// The line in [`MacroAt::written_in`], one-based.
    pub written_at_line: Option<usize>,
}

impl TranslationUnit {
    /// **What `name` is, at byte `offset` of `file`, as this unit read it.**
    ///
    /// `None` when the file is not part of this unit's walk — which is a different answer from "not defined", and the
    /// distinction a caller needs in order to know whether it asked a question the unit can answer at all.
    ///
    /// # Why the offset is required
    ///
    /// A file's macro state is a **timeline**: `#define` and `#undef` take effect where they are written, and an
    /// include contributes its own definitions at the point it is included. Asking without a position means asking
    /// about the end of the file, which is how a name that `xtr1common:22` had `#undef`ed still read as defined — see
    /// [`crate::preprocess::cooked::attribute_support`], where that mistake cost the `[[msvc::…]]` attributes.
    pub fn macro_at(&self, file: &std::path::Path, name: &str, offset: usize) -> Option<MacroAt> {
        // **The file is matched the way this crate matches every path**, not by `Path` equality: a caller reaching for
        // a header from an `#include <...>` spelling hands over forward slashes and whatever case it typed, while the
        // walk recorded the path the filesystem gave it. Comparing raw paths made every question about a system header
        // answer "this session's walk never reaches that file" — the one answer that is not a reading of anything.
        // [`TranslationUnit::entered`] is keyed by the normalized spelling now, so this is a lookup rather than the
        // scan it used to be (the scan was written when the field was keyed raw).
        let frame = *self.entered.get(&frame_key(file))?;
        let view = self.environment_at(frame);

        // **A file this walk recorded facts for at all**, which is not the same as "a file it entered".
        //
        // A header that is *only* directives — every `#define` and `#if` and no declaration — contributes no token to
        // the rendering, and the unit's timeline can end up with no event of its frame. Measured, on a three-line
        // repro and again on MSVC's `yvals_core.h`:
        //
        // ```text
        // the cooked stream        FEATURE_FLAG is 1, VISIBLE_MACRO is defined   ← correct, and what parsing uses
        // this query               FEATURE_FLAG is "not a macro"                 ← wrong
        // ```
        //
        // The stream is right because a cook reads such a file through its own table; this query reads the unit's
        // timeline, which for that shape holds nothing. `None` says so, and the caller reports "no reading" instead of
        // a confident `false` — a tool whose answers are used to decide what to fix must not invent one.

        // **A file's own facts are visible to it, and `MacroView::the_binding` cannot say so.**
        //
        // That method exists for the parser, which reads a file's own definitions **from its own parse** and so wants
        // the walk to report only inherited ones: `offset_of` answers `None` for an event of this very frame, and
        // `last_visible` turns that into "not visible". Asking through it produced the absurdity this code was written
        // to fix —
        //
        // ```text
        // at vadefs.h:30      _CRT_PACKING  →  not a macro      ← defined at :18, in this file
        // at vcruntime.h:100  _CRT_PACKING  →  #define 8        ← from another file, and visible
        // ```
        //
        // So both halves are read and the later one wins, which is the rule the whole table follows:
        //
        // * **this file's own last fact at or before `offset`**, out of the unit's name history, which is in walk
        //   order — a fact written by this file is in force from where it is written;
        // * **the inherited one**, if any, from `the_binding`, which knows about the files this one includes.
        // **Every event here was in force when it was fed.** The walk decides a conditional fact's guard before it
        // records anything, and a fact whose guard it decided against is *not* recorded at all — it is what
        // `RenderedUnit::dead_macros` hands on. So requiring `unconditional` here threw away a file's own
        // `#define`s behind an `#if` that was taken, and answered `defined: false` for them:
        //
        // ```text
        // same.h   #define SAME 1
        //          #ifdef SAME
        //          #define OWN_INSIDE 1     ← in the unit's events, `unconditional: false`
        //          #endif
        // macro_at(same.h, "OWN_INSIDE")  →  defined: false        (before this change)
        // ```
        //
        // Found by the effect model's oracle and narrowed to this one predicate; `tests/nested_conditional.rs`
        // is the reproduction, and it is the reason the predicate is gone rather than widened.
        let own = self
            .by_name
            .get(name)
            .into_iter()
            .flatten()
            .rev()
            .map(|index| &self.events[*index as usize])
            .find(|event| view.applies_here(frame, offset, event));

        let inherited = view.the_binding(name);

        // The event in force, taken as the **later** of the two candidates: the file's own last fact at or before the
        // position, and whatever the inclusive walk says is in force there.
        let event: &TuEvent = match (own, inherited) {
            (Some(own), None) => own,
            (None, Some((at, event))) if at <= offset => event,
            (None, Some(_)) => {
                return Some(MacroAt {
                    defined: false,
                    body: None,
                    body_text: None,
                    function_like: false,
                    written_in: None,
                    written_at_line: None,
                });
            }
            (Some(own), Some(_)) => own,
            (None, None) => {
                // **A file whose own frame has no events at all is a file this walk cannot speak about** — every
                // directive it wrote either produced nothing or was decided against. `None` rather than `false`,
                // because "nothing was recorded here" and "this name is not a macro here" are different answers and
                // only the second is one this unit made. See the note at the top of this function.
                if !self.events.iter().any(|event| event.frame == frame) {
                    return None;
                }
                return Some(MacroAt {
                    defined: false,
                    body: None,
                    body_text: None,
                    function_like: false,
                    written_in: None,
                    written_at_line: None,
                });
            }
        };

        let defined = event.body.is_some() || event.function_like.is_some();
        Some(MacroAt {
            defined,
            body: event.body,
            body_text: event.body_text.as_ref().map(|text| text.to_string()),
            function_like: event.function_like.is_some_and(|held| held),
            written_in: Some(self.frames[event.frame as usize].file.clone()),
            written_at_line: None,
        })
    }
}

impl<'unit> MacroView<'unit> {
    /// The file this view is of.
    pub fn file(&self) -> &'unit std::path::Path {
        &self.unit.frames[self.frame as usize].file
    }

    /// **Is this fact in force here, at `offset`?** — [`TranslationUnit::macro_at`]'s test, which needs the facts
    /// [`MacroView::offset_of`] deliberately hides.
    ///
    /// [`MacroView::offset_of`] answers `None` for an event of the file being asked about, because the only caller it
    /// was written for — the parser — reads a file's own definitions **from that file's own parse** and wants the
    /// walk to report inherited facts alone. A caller asking "what is this name *here*" wants the opposite, and has to
    /// make the same three-way decision with the own case included.
    ///
    /// The trap is the middle case: an event carries `at` in **its own file's** coordinates, so comparing it against
    /// the offset being asked about compares two different rulers. Which is what the previous version did —
    /// `event.frame == frame && event.at <= offset` — and a cross-file event that survived the frame test carried a
    /// number from another file into the comparison. It was right by luck for a fact inherited from an include and
    /// wrong for a fact the file wrote itself.
    fn applies_here(&self, frame: u32, offset: usize, event: &TuEvent) -> bool {
        let held = &self.unit.frames[frame as usize];

        if event.frame == frame {
            // The file's own text: its offsets are the ones being asked about.
            return event.at <= offset;
        }

        if event.frame > frame && event.frame < held.tout {
            // A file this one includes — the interval test is the frame subtree, since frames are in DFS preorder.
            // The fact is in force from the `#include` that brought it in, **in this file's coordinates**.
            return self.unit.offset_in(event.frame, frame) <= offset;
        }

        // Anything else was written after this file was left, which is not visible here at all.
        false
    }
    /// The offset in **this file** at which the event at `index` comes into force, or `None` when this file cannot
    /// see it at all.
    fn offset_of(&self, index: usize, event: &TuEvent) -> Option<usize> {
        let frame = &self.unit.frames[self.frame as usize];

        if event.frame == self.frame {
            // The file's own text — see the type's note.
            None
        } else if event.frame > self.frame && event.frame < frame.tout {
            // A file this one includes: the interval test is the frame's subtree (frames are in DFS preorder), so
            // this is a descendant, and the offset is found by walking the precomputed path.
            Some(self.unit.offset_in(event.frame, self.frame))
        } else if (index as u32) < frame.entry_seq {
            // Emitted before this file was entered: the inherited prefix, in force from its first line.
            Some(0)
        } else {
            // A sibling's subtree, or something the walk reached after this file was left: not visible here.
            None
        }
    }

    /// The **last** fact for `name` this file can see that `wanted` accepts, with the offset it applies from.
    ///
    /// The search runs the name's own history backwards, which is the whole cost of a query: a name's events are
    /// appended in walk order, so the first one that is visible is the one in force. A name defined once — almost
    /// every name — costs one visibility test.
    ///
    /// The history arrives as a slice so that a caller **enumerating the whole environment** passes the one it is
    /// already holding: hashing a name to find a list the caller has in hand is work a per-file loop must not do
    /// twice, and `for_each_definition` runs for every name in the unit, in every file.
    fn last_visible(
        &self,
        indices: &[u32],
        wanted: impl Fn(&TuEvent) -> bool,
    ) -> Option<(usize, u32)> {
        indices.iter().rev().find_map(|&index| {
            let event = &self.unit.events[index as usize];
            if !wanted(event) {
                return None;
            }
            self.offset_of(index as usize, event).map(|at| (at, index))
        })
    }

    /// [`MacroView::last_visible`] for a caller that has a name and not the history — the query path.
    fn last_visible_of(
        &self,
        name: &str,
        wanted: impl Fn(&TuEvent) -> bool,
    ) -> Option<(usize, u32)> {
        self.last_visible(self.unit.by_name.get(name)?, wanted)
    }

    /// The fact that settles what `name` **is** in this file, on the channel that says what a name is.
    ///
    /// The definition channel, the last visible fact of it, and — with it — whether that fact is a definition at
    /// all: an `#undef`, or a `#define` whose shape the walk could not read, is a fact about the name whose
    /// *definition* is `None`. See [`cpp_parser::IncludedMacro::undefined_at`], which is where that distinction
    /// lives.
    fn the_binding(&self, name: &str) -> Option<(usize, &'unit TuEvent)> {
        // **The same predicate as [`MacroView::visible_binding`], and for the same reason.** This asked for
        // `event.unconditional` alone, so a `#define` behind an `#if` that the walk *decided true* was invisible to
        // the parser's view — it is a conditional fact, and being conditional is not the same as being out of force.
        // The cook path was fixed long ago (`visible_binding`, whose note is the measurement); this one was not, and
        // it is the inherited half of the defect `tests/nested_conditional.rs` reproduces: a file could not see what
        // another file defined behind a guard that held.
        let (at, index) = self.last_visible_of(name, |event| {
            event.unconditional || event.body.is_some() || event.is_an_undef()
        })?;
        Some((at, &self.unit.events[index as usize]))
    }

    /// The **in-force** channel: the last visible fact whose replacement list this file can read.
    ///
    /// Any fact with a body text, whether or not it was written inside a condition: only facts the walk decided *in
    /// force* are recorded at all, so `unconditional` is not the question here — having a body is.
    fn the_body_in_force(&self, name: &str) -> Option<&'unit TuEvent> {
        let (_, index) = self.last_visible_of(name, |event| event.body_text.is_some())?;
        Some(&self.unit.events[index as usize])
    }

    /// [`MacroView::the_binding`] as **the timeline index** of that fact, with the offset it applies from.
    ///
    /// The index rather than the event because the cooker needs to reach what the fact was *parsed into*
    /// ([`UnitDefinitions`]), and that parse is per event rather than per file: one definition reaches every file
    /// that sees it, and re-parsing it per file is what the census measured at seconds of a run.
    ///
    /// # Why a fact a condition settled counts as a binding here
    ///
    /// This asked for `event.unconditional` alone, and that is **not** the same question as "is this fact in force":
    /// a `#define` inside `#if GUARD` is recorded as a *conditional* fact, and when the walk found `GUARD` true it is
    /// as much in force as one written at file scope. Skipping those lost the definition entirely.
    ///
    /// Measured, and it is what the whole `[[msvc::…]]` family came down to. A three-line repro:
    ///
    /// ```cpp
    /// // h2.h
    /// #if _HAS_MSVC_ATTRIBUTE(known_semantics)      // evaluates true, so the walk records the fact
    /// #define KM [[msvc::known_semantics]]
    /// #endif
    ///
    /// // g3.cpp
    /// #include "h2.h"
    /// KM int a;                                     // cl: [[msvc::known_semantics]] int a;
    /// ```
    ///
    /// We expanded nothing and left `KM` in the stream, for the reason `CPPLS_TRACE_MACRO=KM` printed:
    /// `in_force=no positional=no-binding seed=no`. The definition was in the timeline — the walk recorded it — and
    /// this filter is what hid it. The same masked every conditional definition in a compiler's own headers, which is
    /// why `_STL_STRINGIZE` (48 recordings) and the `_MSVC_*` attribute macros all read as undefined.
    ///
    /// A conditional fact with **no** body is a binding only when it is an `#undef` — see [`TuEvent::is_an_undef`].
    ///
    /// **An `#undef` in force is a binding, and this is the half that was missing.** The filter used to be
    /// `unconditional || body.is_some()`, and an `#undef` has neither: it is written inside an `#if` and it writes
    /// no replacement list. So the *earlier* definition of the name stayed "visible" and the cook expanded it —
    /// measured on a production project whose precompiled header takes the SDK's `min`/`max` away inside
    /// `#if defined(_WIN32)`: a `std::min(a, b)` at the use was cooked into
    /// `std::((( a ) < ( b )) ? ( a ) : ( b ))`, and the file was reported as *expected `;` after expression* on a
    /// line a compiler accepts. [`UnitDefinitions::of`] answers `None` for an undef, so the name falls through to
    /// the compiler's own seed — which is exactly "not a macro here".
    pub(crate) fn visible_binding(&self, name: &str) -> Option<(usize, u32)> {
        self.last_visible_of(name, |event| {
            event.unconditional || event.body.is_some() || event.is_an_undef()
        })
    }

    /// [`MacroView::the_body_in_force`] as the timeline index of that fact.
    ///
    /// **An `#undef` in force takes the body away**, and it has to be looked for here rather than skipped: the last
    /// fact in force for a name is what the name means, so a body collected from an earlier `#if`-guarded `#define`
    /// is gone the moment a later `#if`-guarded `#undef` of it is in force. `last_visible_of` filters, so an undef
    /// that is filtered out is indistinguishable from one that never happened — the name keeps a body the
    /// compilation took away, and the cook expands it. Measured on a production project: `std::min(a, b)` became
    /// `std::((( a ) < ( b )) ? ( a ) : ( b ))` and the file was reported as a syntax error.
    pub(crate) fn visible_body_in_force(&self, name: &str) -> Option<u32> {
        let (_, index) = self.last_visible_of(name, |event| {
            !event.unconditional && (event.body_text.is_some() || event.is_an_undef())
        })?;
        let event = &self.unit.events[index as usize];
        event.body_text.is_some().then_some(index)
    }

    /// **The part of a file's rendering that is its environment, as one number** — the identity of a reading.
    ///
    /// # What a rendering depends on
    ///
    /// A file's rendering is a function of two things: its own text, and the `#define`s in force where it sits. The
    /// text is [`crate::cache::content_hash`]; this is the second half, and it has to be **exact in one direction**:
    /// two readings that would render the same text must agree, and two whose environment differs in a macro the
    /// file can reach must not be taken for one another.
    ///
    /// # Why the closure, and not the whole table
    ///
    /// The whole table is not *this file's* environment. Two translation units that both include `<vector>` differ in
    /// a hundred macros defined after it, and hashing all of them would make every header's rendering unique to its
    /// program — which is the repetition this number exists to remove. What can affect the file is the definition of
    /// each name it writes, and the definition of each name those definitions mention: `_STD_BEGIN` stands for
    /// `namespace std {`, and a name inside a body is one the expansion of that body will look up.
    ///
    /// ```text
    /// #define A(x) B(x)        the file writes A  →  A's body mentions B  →  B's definition is part of the
    /// #define B(y) y + 1       environment too, because expanding A reaches it
    /// ```
    ///
    /// So the names come from the file's own identifier tokens and the closure is walked from there, by name.
    /// Sorting by name is what makes the number independent of the order the walk took.
    ///
    /// # What is deliberately not hashed
    ///
    /// The **seed** (`-D`, the compiler's predefines): it is a property of the compilation, and the compilation is
    /// already the key's other half ([`SummaryKey::context_hash`]). A name the environment does not define
    /// contributes nothing — "not defined here" is the same fact however the absence came about.
    pub fn environment_fingerprint(
        &self,
        source: &str,
        tokens: &[cpp_parser::CppTokenData],
    ) -> u64 {
        let mut pending: Vec<&str> = tokens
            .iter()
            .filter(|token| token.kind == cpp_parser::CppTokenKind::Identifier)
            .map(|token| &source[token.range.start_offset..token.range.end_offset()])
            .collect();
        let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new();
        // `(name, function-like, parameters, body)`, the four facts that make up a definition.
        let mut entries: Vec<(&str, Option<bool>, Option<&str>, Option<&str>)> = Vec::new();

        while let Some(name) = pending.pop() {
            if !seen.insert(name) {
                continue;
            }
            let Some((_at, event)) = self.the_binding(name) else {
                continue;
            };
            entries.push((
                name,
                event.function_like,
                event.parameters.as_deref(),
                event.body_text.as_deref(),
            ));
            // **What the body mentions is part of the environment too.** The body is text, and the expander lexes it
            // before it substitutes anything, so this is the same lexer reading the same bytes.
            let Some(body) = event.body_text.as_deref() else {
                continue;
            };
            let parameters = event.parameters.as_deref();
            for token in cpp_parser::lex(body, &cpp_parser::LexerConfig::default()).0 {
                if token.kind != cpp_parser::CppTokenKind::Identifier {
                    continue;
                }
                let word = &body[token.range.start_offset..token.range.end_offset()];
                // A parameter is the macro's own piece of text, not a name the environment answers: `#define B(y)
                // y + 1` says nothing about a macro called `y`.
                if parameters.is_some_and(|list| mentions_a_word(list, word)) {
                    continue;
                }
                pending.push(word);
            }
        }

        entries.sort_unstable_by(|left, right| left.0.cmp(right.0));
        let mut bytes: Vec<u8> = Vec::new();
        for (name, function_like, parameters, body) in entries {
            bytes.extend_from_slice(name.as_bytes());
            bytes.push(0);
            bytes.push(match function_like {
                Some(true) => b'f',
                // A definition whose replacement list the walk could not read is still a fact about the name, and a
                // different one from the same name being a macro with a body.
                Some(false) => b'o',
                None => b'u',
            });
            for part in [parameters, body] {
                bytes.extend_from_slice(part.unwrap_or("").as_bytes());
                bytes.push(0);
            }
        }
        crate::cache::fnv1a64(&bytes)
    }
}

/// **Does this parameter list name `word`?** — asked by [`MacroView::environment_fingerprint`] of a body's
/// identifiers, and deliberately a word comparison: `x` is a parameter of `f(x)`, while `max` is not a parameter of
/// `f(x)` however much of `max` it shares.
fn mentions_a_word(parameter_list: &str, word: &str) -> bool {
    parameter_list
        .split(|character: char| !(character.is_alphanumeric() || character == '_'))
        .any(|candidate| candidate == word)
}

impl cpp_parser::MacroFacts for MacroView<'_> {
    fn kind_of(&self, name: &str, offset: usize) -> Option<cpp_parser::SymbolKind> {
        let (at, event) = self.the_binding(name)?;
        if at > offset {
            // Defined, but later than the offset being asked about: not a macro *here*.
            return None;
        }
        match (event.function_like, event.body) {
            (Some(function_like), Some(body)) => Some(cpp_parser::SymbolKind::Macro {
                function_like,
                body,
            }),
            // An `#undef`, or a definition whose shape the index could not read: the name is a fact, the shape is
            // not. See the type's note on the two channels.
            _ => None,
        }
    }

    fn body_text_of(&self, name: &str, offset: usize) -> Option<&str> {
        let (at, event) = self.the_binding(name)?;
        match (at <= offset, event.function_like, event.body) {
            (true, Some(_), Some(_)) => event.body_text.as_deref(),
            _ => None,
        }
    }

    fn parameters_of(&self, name: &str, offset: usize) -> Option<&std::sync::Arc<str>> {
        let (at, event) = self.the_binding(name)?;
        match (at <= offset, event.function_like, event.body) {
            (true, Some(_), Some(_)) => event.parameters.as_ref(),
            _ => None,
        }
    }

    fn body_text_in_force(&self, name: &str) -> Option<&str> {
        self.the_body_in_force(name)
            .and_then(|event| event.body_text.as_deref())
    }

    fn parameters_in_force(&self, name: &str) -> Option<&str> {
        self.the_body_in_force(name)
            .and_then(|event| event.parameters.as_deref())
    }

    fn body_in_force_is_object_like(&self, name: &str) -> bool {
        matches!(
            self.the_body_in_force(name)
                .map(|event| event.function_like),
            Some(Some(false))
        )
    }

    fn knows(&self, name: &str) -> bool {
        self.the_binding(name).is_some()
    }

    fn is_empty(&self) -> bool {
        self.unit.by_name.values().all(|indices| {
            self.last_visible(indices, |event| event.unconditional)
                .is_none()
                && self
                    .last_visible(indices, |event| {
                        !event.unconditional && event.body_text.is_some()
                    })
                    .is_none()
        })
    }

    /// How many names this file sees a fact about, of the channel that says what a name is.
    ///
    /// Counted rather than stored: a view owns nothing, and the number is a measurement (the census prints it),
    /// not something a query needs.
    fn len(&self) -> usize {
        self.unit
            .by_name
            .values()
            .filter(|indices| {
                self.last_visible(indices, |event| event.unconditional)
                    .is_some()
            })
            .count()
    }

    /// Every definition this file sees — **one per name**, the last visible fact of the definition channel.
    ///
    /// One per name because that is what the map it replaced held: a name's earlier facts are shadowed, and a
    /// consumer building a table out of these wants the definition, not the history. Emitted in no particular
    /// order (the unit's name index is a hash map), which is what the previous implementation did too.
    fn for_each_definition<'s>(&'s self, visit: &mut dyn FnMut(cpp_parser::DefinitionFacts<'s>)) {
        for (name, indices) in &self.unit.by_name {
            let Some((at, index)) = self.last_visible(indices, |event| event.unconditional) else {
                continue;
            };
            let event = &self.unit.events[index as usize];
            let (Some(function_like), Some(_)) = (event.function_like, event.body) else {
                continue;
            };
            visit(cpp_parser::DefinitionFacts {
                name,
                at,
                function_like,
                parameters: event.parameters.as_ref(),
                body_text: event.body_text.as_ref(),
            });
        }
    }

    fn for_each_body_in_force<'s>(&'s self, visit: &mut dyn FnMut(cpp_parser::BodyFacts<'s>)) {
        for (name, indices) in &self.unit.by_name {
            let Some((_, index)) = self.last_visible(indices, |event| {
                !event.unconditional && event.body_text.is_some()
            }) else {
                continue;
            };
            let event = &self.unit.events[index as usize];
            let Some(body) = event.body_text.as_ref() else {
                continue;
            };
            visit(cpp_parser::BodyFacts {
                name,
                function_like: event.function_like,
                parameters: event.parameters.as_ref(),
                body,
            });
        }
    }
}

/// **A whole translation unit cooked into one stream** — what a compiler parses, and the map back to the files.
///
/// # Why this exists
///
/// Cooking one file at a time answers "does this header read on its own", and the readings it produced (254 of
/// 255, 452 of 455) are the ones this project has been driving up. It cannot answer "does the *program* read":
/// a declaration in `vector` and a use in the source are two different streams, and nothing in either one says
/// they belong together. This is that stream.
///
/// # How it is stitched
///
/// The walk already knows the order — frames are in DFS preorder, which *is* include order — and each frame
/// records `from_in_parent`: the offset in its parent where its text comes into force, which is where the
/// `#include` that brought it in ended. So the unit's text is the root's cooked tokens, with each child's stream
/// spliced in at its own offset, recursively. A file the walk reached **once** appears **once**, whatever number
/// of `#include`s named it — the guard idiom means the second inclusion would contribute nothing anyway.
///
/// # What the map says
///
/// One [`UnitSpan`] per token of `text`, in order, each naming the **file it stands in** and the place in that
/// file a consumer should act on. The two are not the same thing, and the difference is the reason the map
/// exists: a token produced by expanding a macro *stands* in the file that invoked it, while the text it was
/// written in is inside some `#define` — see [`UnitSpan::written`].
#[derive(Debug, Clone, Default)]
pub struct RenderedUnit {
    /// The tokens of every file the unit reached, in the order a compiler would read them.
    pub text: String,
    /// **Every file the *walk* entered**, in the order it entered them — which is not `files`.
    ///
    /// `files` names the files that contributed **tokens** to the stream, and this names the files the walk read,
    /// including the ones that contribute none: a header of nothing but `#define`s and `#if`s (`bits/version.h`,
    /// `yvals_core.h`) is read by the preprocessor and writes no token to the program.
    ///
    /// It exists because the key this rendering is filed under folds *the walk's* files. Without the list, a stored
    /// rendering cannot reproduce its own key, and no cache can find it without re-walking the closure — measured at
    /// **70.7 ms** for the standard library's 256 files, on every program read.
    pub walked: Vec<std::path::PathBuf>,
    /// **The `#define`s the walk decided are *not* compiled, by file** — the offsets of the directives it skipped.
    ///
    /// The walk evaluates every guarded fact against the unit's own state ([`UnitMacros`]), which is the same
    /// evaluation the cook uses and the only one that knows what the compilation defines. A fact it skips is a
    /// `#define` a compiler would not have read — and the file's **summary** kept it anyway, because a summary is
    /// built from the raw reading and records every `#define` with the region it was written in.
    ///
    /// Leaving it in the summary is what makes a consumer **decide the region a second time**, with a different
    /// environment, and get a different answer. Measured on `vcruntime.h`, which writes `_STL_LANG` once per branch
    /// of `#ifdef __cplusplus`: the walk takes the `_MSVC_LANG` branch and skips the `#else`'s `0L`, while a lookup
    /// over the raw facts answers `0L` — for a file the compiler reads as C++20.
    ///
    /// Offsets rather than facts because that is what a summary can be filtered by, and because the decision is
    /// about a **directive**, which is a position in a file.
    pub dead_macros: std::collections::HashMap<std::path::PathBuf, Vec<usize>>,
    /// **The `#error` and `#warning` lines the compilation would have said**, in file order.
    ///
    /// A message is not program text, so the stream keeps no token for it — this is the only channel by which it
    /// survives, and it exists so that a caller can **ask a header a question**: put a `#error` at a position, render,
    /// and see whether it fires. That is how a real chain's branch is found when two layers disagree, and it is the
    /// question this crate kept answering by copying a header — which demonstrably does not work, because a copy's
    /// include guard, include order and `#pragma push_macro`s all move when the text moves.
    pub messages: Vec<UnitMessage>,
    /// One entry per token of `text`, in the same order.
    pub spans: Vec<UnitSpan>,
    /// The files the walk entered, in the order it entered them — what a span's `file` indexes.
    pub files: Vec<std::path::PathBuf>,
    /// **How long each file's own text is**, parallel to [`RenderedUnit::files`].
    ///
    /// The table that makes [`RenderedUnit::written_span`]'s answer checkable: the file it names and the range it
    /// gives are both about *that file's* text, so the range has to end at or before this length. A file the caller
    /// had no text for has length 0 — and a range in it is then impossible rather than merely unlikely.
    pub file_lengths: Vec<usize>,
    /// **The stream's own brace balance**: `{` minus `}` over every token in it.
    ///
    /// One number, and it separates two failures that look identical from outside: a stream that does not balance
    /// (a file's text opened a brace it never closed, so everything spliced after it is inside) and a *balanced*
    /// stream whose scopes the walk still pairs wrongly. The first is a fact about the rendering, the second about
    /// the reader, and no amount of looking at a wrong scope name tells them apart.
    pub braces: i64,
    /// How many files the unit reached that the caller had **no text** for.
    ///
    /// A hole rather than an empty file: the stream is missing whatever that file would have contributed, and a
    /// consumer that needs to know whether what it read is the whole program asks this.
    pub missing: usize,
    /// **Files whose own text does not balance its braces** — recorded, and **no longer dropped**.
    ///
    /// # Why this field exists
    ///
    /// A brace opened in one file and closed in another is not a defect in C++ — a header that opens a namespace
    /// for its includer to close is a real idiom — but in a **program** stream it is a hazard, and it is the hazard
    /// that made this field exist: measured on a real project, `CodeAnalysis/sourceannotations.h` (the Windows
    /// SDK's `/analyze` header, the one file a census has never read cleanly) opens `namespace vc_attributes {` and
    /// the close is not in the text we rendered. Everything spliced after it — `<cstdio>`, `<string>`, the whole
    /// standard library — then read as `vc_attributes::std`, and a reader asking about `std::size_t` got "the index
    /// has no such name" while the file in front of them declared it.
    ///
    /// # What used to be done about it, and why that was the wrong shape
    ///
    /// The frame's own tokens were **left out of the stream** (its includes were still spliced, being files with
    /// their own text) and the file was named here. That is the plan's gate ①, and §4 rule 1 is written against it:
    /// *"任何一层都不允许因为'不确定'而放弃已经确定的答案."* Dropping a file's text because its braces do not
    /// balance throws away every declaration in it — a file with one unbalanced brace and eight hundred good
    /// declarations contributed **none** of them — and it is the same all-or-nothing shape as the `crossings == 0`
    /// gate that used to sit one layer up.
    ///
    /// # What is done instead
    ///
    /// **Nothing in this crate.** The text goes **in** unmodified, and the crossing is refused where it is created:
    /// [`cpp_parser::ParserConfig::with_file_boundaries`], set from [`RenderedUnit::file_boundaries`] by whoever
    /// parses the unit. The parser's body loops stop at a boundary, so the `{` one file left open is closed at the
    /// end of that file rather than paired with a `}` another file wrote — no file is dropped, no pair is
    /// neutralised, and no second parse is needed.
    ///
    /// This paragraph used to describe a repair in `FileIndexer::index_unit_rendering` — find the crossed pair,
    /// neutralise it, read the file again on its own. That was the *analysis* layer absorbing a **grammar** defect,
    /// and it was deleted on purpose (see the note in `index/mod.rs`, and the sibling note on
    /// [`RenderedUnit::file_boundaries`], which was written for exactly this and went uncalled). The layer that
    /// pairs braces is the layer that must not pair them across files.
    ///
    /// # This corpus never needed it
    ///
    /// Measured on MSVC's standard library, so that the rule is not mistaken for an MSVC defect: a **94-file** unit
    /// rooted at `<memory>` reports `unbalanced: 0` and a stream balance of `0`, and `vcruntime.h`'s own text holds
    /// three `{` and three `}`. The `/analyze` header above is the shape this exists for; MSVC's headers are not it.
    ///
    /// A file named here is still a file worth looking at: its text genuinely does not balance, which is either a
    /// real idiom (the open/close-across-includes shape above) or a defect in the file. What changed is that the
    /// answer to "which" is now visible in the index instead of being priced in silence.
    ///
    /// # The root cause is elsewhere, and is still registered
    ///
    /// An identifier nobody defines evaluates to **0** in `#if`, so `#if defined(_PREFAST_)` is decidable — and
    /// answering `Unknown` there is what pulls the `/analyze` header into a program that never asks for it. That is
    /// §3.2 item 1 (the builtin macro table), and it is the fix that stops this file being in the program at all.
    pub unbalanced: Vec<std::path::PathBuf>,
    /// The next token starts a new line: a `#pragma` directive ends at its newline, and `text` has no other.
    pub(crate) pending_break: bool,
    /// The **file and file-range of the token appended last**, for the separator rule in
    /// [`RenderedUnit::push`]: two tokens that touch in the same file were one spelling there, and rendering them
    /// apart is what would make `a >> b` unreadable as a shift.
    pub(crate) previous: Option<(u32, cpp_parser::SourceRange)>,
}

/// **One `#error` or `#warning` the compilation would have said**, with where it was written.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnitMessage {
    /// The file that wrote it — a member of [`RenderedUnit::files`].
    pub file: std::path::PathBuf,
    /// `true` for `#error`, `false` for `#warning`.
    pub fatal: bool,
    /// The message, as written.
    pub message: String,
    /// The byte offset of the directive **in that file**, so a caller can say where it is.
    pub at: usize,
}

/// One token's place in a unit's rendering, and where it came from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnitSpan {
    /// Where the spelling is in [`RenderedUnit::text`].
    pub cooked: cpp_parser::SourceRange,
    /// Which file of [`RenderedUnit::files`] the token **stands in**.
    pub file: u32,
    /// The place in that file a consumer should act on.
    ///
    /// The token's own range for a token the file wrote, and the **outermost call site** for one that came out of
    /// a macro body — the text the reader can see, rather than a line inside a `#define` three headers up. See
    /// `ExpandedToken::diagnostic_range`, which is where that choice is documented.
    pub written: cpp_parser::SourceRange,
}

impl RenderedUnit {
    /// **Where each file begins in the rendering**, as offsets into [`RenderedUnit::text`] — the boundaries between
    /// the files a translation unit was stitched from.
    ///
    /// The first token of each file that contributes one, in order; the first file's own start is omitted, because
    /// offset 0 is a boundary everything already has. A file that contributes **no token** — a header that is only
    /// `#define`s, whose whole body the preprocessor consumed — has no boundary, and that is right: it opened no
    /// scope either, so nothing needs closing at its end.
    ///
    /// # What this is for, and why nothing calls it yet
    ///
    /// It exists so a parser of this text can be told where one file ends and the next begins, and can therefore
    /// close a scope one file left open instead of letting it hold the next file. **That rule does not work as a
    /// tree-builder rule**, which was measured rather than assumed:
    ///
    /// ```text
    /// boundary None → TranslationUnit → NamespaceDecl → CompoundStat → Declaration
    /// boundary 0    → TranslationUnit → NamespaceDecl → CompoundStat → Declaration
    /// boundary 39   → TranslationUnit → NamespaceDecl → CompoundStat → Declaration
    /// ```
    ///
    /// Boundary `0` is satisfied by the first token, so it closes whatever is open at the start of the stream — and
    /// the shape does not move. The reason is that the holder is a `CompoundStat`: the brace of `namespace first {`
    /// was paired by the **grammar** with the `}` that ends the file, so the leak is a scope-pairing decision made
    /// while the tokens were being read, not an imbalance in the event stream that closing a node can repair.
    ///
    /// So the fix belongs in the grammar's own scope handling, and this stays as the piece such a fix will need:
    /// the offsets are a fact about the rendering, computed once, and nothing about them depends on how the parser
    /// chooses to use them. See `Session`'s tests
    /// (`a_file_that_does_not_balance_costs_nothing_but_a_name`) for what is currently true and asserted.
    pub fn file_boundaries(&self) -> Vec<usize> {
        let mut boundaries = Vec::new();
        let mut seen = vec![false; self.files.len()];

        // The spans are in cooked order, so the first time a file appears is where it begins.
        for span in &self.spans {
            if let Some(slot) = seen.get_mut(span.file as usize)
                && !*slot
            {
                *slot = true;
                if span.cooked.start_offset != 0 {
                    boundaries.push(span.cooked.start_offset);
                }
            }
        }

        boundaries
    }

    /// Where a token of the rendering was written, by its offset in the rendering: the file, and the range in it.
    pub fn written_at(&self, cooked_offset: usize) -> Option<(u32, cpp_parser::SourceRange)> {
        let index = self
            .spans
            .partition_point(|span| span.cooked.end_offset() <= cooked_offset);
        self.spans.get(index).map(|span| (span.file, span.written))
    }

    /// The file a token of the rendering stands in, as a path.
    pub fn file_at(&self, cooked_offset: usize) -> Option<&std::path::Path> {
        let (file, _) = self.written_at(cooked_offset)?;
        self.file_of(file)
    }

    /// **Which file's cook produced the token at this offset** — the file it *stands in*.
    ///
    /// The question every caller that has to divide a stream between files is really asking, and the one
    /// [`RenderedUnit::written_at`] *looks* like it answers. It does not: the second field there is
    /// [`UnitSpan::written`], a **navigation hint** — for a token expanded out of a `#define` in another header it
    /// is a position in *that* header, so reading the file out of it names the file the body was written in rather
    /// than the file the token stands in.
    ///
    /// Measured, and it is why eight files of MSVC's standard library were quarantined as leaked:
    /// `brace_crossings` divided the stream with `written_at(..).map(|(file, _)| file)`, so a `{` written in a
    /// header's `#define` and its matching `}` written by the *invoking* file — one scope, one file — looked like a
    /// brace pair spanning two files. `<memory>`, `<atomic>`, `<variant>`, `<any>`, `<functional>`, `<bitset>`,
    /// `<chrono>` and `<format>` were taken out of the program for it, and the members of `std::unique_ptr`,
    /// `std::atomic` and `std::variant` went with them.
    pub fn file_standing_at(&self, cooked_offset: usize) -> Option<u32> {
        let index = self
            .spans
            .partition_point(|span| span.cooked.end_offset() <= cooked_offset);
        self.spans.get(index).map(|span| span.file)
    }

    /// Where a **span** of the rendering was written: the file it stands in, and the range to act on there.
    ///
    /// [`RenderedUnit::written_at`] answers for one token; this is what a *fact* needs, because a declaration is a
    /// span and a reader wants the whole of it. The two ends are asked separately and the answer is the span
    /// between them, which is the same arithmetic
    /// [`RenderedCooked::written_span`](crate::preprocess::cooked::RenderedCooked::written_span) does for one
    /// file's rendering.
    ///
    /// The two ends can stand in **different** files — a macro invocation that expands to text from two headers,
    /// or a declaration whose body came out of one and whose name was written in another — and there the honest
    /// answer is the first token's place: a range the reader can see, rather than a span across two texts.
    ///
    /// # Why this is the token's file and not its hint's
    ///
    /// `span.file` is which file's cook produced the token — the file it **stands in**, and the only thing that can
    /// say which file a declaration is in. `span.written` is a *navigation hint*, so reading the file out of it
    /// would be reading it out of the wrong field.
    ///
    /// That distinction turns out **not** to be a live bug, and the reason is worth recording because it is what
    /// [`RenderedUnit::span_lands_in`] now guards: `ExpandedToken::diagnostic_range` already answers with the
    /// **outermost call site** for a token that came out of a macro body — a position in the invoking file rather
    /// than the `#define` — so a hint is a range in the file the token stands in and the two fields agree.
    /// `a_declaration_starts_in_the_file_it_stands_in` is the shape that separates them, and it is asserted rather
    /// than argued because nothing else enforces it.
    pub fn written_span(
        &self,
        range: cpp_parser::SourceRange,
    ) -> Option<(u32, cpp_parser::SourceRange)> {
        let (file, first) = self.written_at(range.start_offset)?;
        let (last_file, last) = self.written_at(range.end_offset().saturating_sub(1))?;

        if last_file != file || last.end_offset() <= first.start_offset {
            return Some((file, first));
        }

        Some((
            file,
            cpp_parser::SourceRange {
                start_offset: first.start_offset,
                length: last.end_offset() - first.start_offset,
            },
        ))
    }

    /// **Does this span's answer land in the file the answer names?**
    ///
    /// The invariant [`RenderedUnit::written_span`]'s contract implies and that nothing performed: a range that
    /// names a file it does not fit in is a wrong answer of a kind measured on this project — a 93 971-byte class
    /// body filed under a 1.2 KB header, with the name, the scope and the range all correct for the file it named.
    /// [`crate::file_what_was_found`] counts what fails this rather than filing it.
    pub fn span_lands_in(&self, file: u32, written: cpp_parser::SourceRange) -> bool {
        match self.file_lengths.get(file as usize) {
            Some(&length) => written.end_offset() <= length,
            None => false,
        }
    }

    /// The path a span's file index names.
    pub fn file_of(&self, file: u32) -> Option<&std::path::Path> {
        self.files
            .get(file as usize)
            .map(std::path::PathBuf::as_path)
    }

    /// How many tokens the unit's stream has.
    pub fn len(&self) -> usize {
        self.spans.len()
    }

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

    /// How many files the stream actually carries a token from.
    ///
    /// Not [`RenderedUnit::files`]'s length: a header whose whole body is inside a branch nobody takes
    /// contributes no token, and one nobody had text for contributes a hole.
    pub fn files_with_tokens(&self) -> usize {
        let mut seen = vec![false; self.files.len()];
        for span in &self.spans {
            if let Some(slot) = seen.get_mut(span.file as usize) {
                *slot = true;
            }
        }
        seen.into_iter().filter(|it| *it).count()
    }

    /// Append one token — the separator rule `CookedStream::render` uses, so the two renderings spell the same
    /// text for the same tokens.
    ///
    /// `pub(crate)` rather than private because this crate's tests build a unit token by token to check the mapping,
    /// and a test that spelled the text itself would be testing its own spelling rather than this rule.
    ///
    /// # A space only where the source had one
    ///
    /// This used to put a space between every pair. That is safe in one direction — a space can only *split* a
    /// spelling, never merge two — and it is **not** safe in the other, which is the one that bit: layout can also
    /// change a parse by making a pair that *was* adjacent stop being so. The lexer leaves the `>`-family in pieces
    /// (`cpp_parser::CppLexer::tokenize`) and the grammar puts `>` `>` back together by **byte adjacency**, so
    /// spelling `a >> b` as `a > > b` hands the parser two greater-thans it will not join.
    ///
    /// Measured on the cooked `<vector>` stream: **0 diagnostics → 77**, the first at byte 4127, where the file
    /// writes `is_same_v<_Ty1, _Ty2>>` and the rendering wrote `_Ty2 > >`.
    ///
    /// # `space_before`, and why a macro expansion cannot be spaced by ranges
    ///
    /// `written` answers "did these two touch" for a token the file wrote literally: it carries its own range. One out
    /// of a macro body carries the **invocation** instead, and *every* token of one expansion carries the same
    /// invocation — so `previous.end_offset() == written.start_offset` is false for each pair, and the rule above
    /// spelled an expansion with a space between every token. That is the same failure the note above is about, one
    /// layer down: `#define strisshr(ts) ((ts)->shrlen >= 0)` in Lua 5.5.0's `lobject.h:420` came out as
    /// `( ( s ) -> shrlen > = 0 )` in the program reading of `ldebug.c`, the parser reported `expected primary
    /// expression` against the `=`, and 15 errors followed it.
    ///
    /// The expander already answers the question — [`crate::ExpandedToken::space_before`] compares the two tokens in
    /// whatever coordinate system they share and falls back to "would joining them merge" (`>` `=` does not) — so this
    /// takes it as `space_before: Some(…)` and falls back to the range test only for text the file wrote (`None`).
    pub(crate) fn push(
        &mut self,
        text: &str,
        file: u32,
        written: cpp_parser::SourceRange,
        space_before: Option<bool>,
    ) {
        if !self.text.is_empty() {
            let touching = match space_before {
                Some(space) => !space,
                None => self.previous.is_some_and(|(previous_file, previous)| {
                    previous_file == file && previous.end_offset() == written.start_offset
                }),
            };

            if self.pending_break {
                self.text.push('\n');
            } else if !touching {
                self.text.push(' ');
            }
        }
        self.previous = Some((file, written));
        self.pending_break = false;
        match text {
            "{" => self.braces += 1,
            "}" => self.braces -= 1,
            _ => {}
        }
        let start = self.text.len();
        self.text.push_str(text);
        self.spans.push(UnitSpan {
            cooked: cpp_parser::SourceRange::new(start, self.text.len() - start),
            file,
            written,
        });
    }

    /// Put the next token on a line of its own. See [`crate::CookedStream::pragma_lines`].
    pub(crate) fn break_line_before_next(&mut self) {
        self.pending_break = true;
    }

    /// **The same program without the tokens of `left_out` files** — the stream a fenced parse reads. Everything else
    /// is the original, in the original order; a left-out file's includes were spliced as files of their own and
    /// stay.
    ///
    /// # This is no longer what the indexer does, and the reason is the whole of M0
    ///
    /// It **is** still the right way to answer "what would this program be without that file", and its contract —
    /// the length is preserved, so the original span table still maps every fact — is the one
    /// [`RenderedUnit::neutralized`] shares. What changed is that the unit reader **stopped asking that question**:
    /// taking a file out of a program because one of its braces was mis-paired costs every declaration in the file,
    /// and measured on a real project that is how `<format>` and `<type_traits>` came to be missing from an index
    /// that had read them. The reader now gives up the **pairing** instead ([`RenderedUnit::neutralized`]) and reads
    /// the file on its own as well. `tests/translation_unit.rs` is where this is still exercised.
    ///
    /// # The tokens are blanked, not removed, and that is the whole point
    ///
    /// The text that comes out is **the same length** as the text that went in: every token of a left-out file is
    /// replaced by as many spaces as it occupied, byte for byte, and every other byte is copied as it stands. So an
    /// offset in the result is the same offset in the original — which is what lets a fact found in the blanked
    /// text be mapped back through [`RenderedUnit::written_span`], whose spans are still the original ones. This is
    /// documented on [`RenderedUnit::only`] as the property a file's own reading depends on, and `without` is the
    /// other half of the same contract.
    ///
    /// # What removing them cost
    ///
    /// The version before this one *deleted* the left-out tokens and rebuilt the span table as it went, which is
    /// the same thing the compiler does and was wrong here for a reason that has nothing to do with parsing:
    /// **the parse that follows maps its declarations back through the original span table**, so deleting six
    /// kilobytes from the middle of a 2 MB stream moved every later offset by six kilobytes and filed every
    /// declaration after it under the wrong file. Measured on a project that includes `<string>`:
    /// `basic_string`'s 93 971-byte class body — written in `<xstring>` — was filed under
    /// `<__msvc_formatter.hpp>`, the file whose *forward declaration* of the same name stands 6 100 bytes earlier.
    /// The reading looked right: the name was right, the scope was right (`std`), the reported range was right for
    /// its own file, and the file was another file's. Nothing else in the pipeline could notice.
    ///
    /// Spaces rather than removal also keeps the **braces** where they were, so the second parse sees the same
    /// token positions as the first and its scope pairing is comparable. Trivia is dropped by the parser either
    /// way, so a blanked file contributes nothing but its length.
    ///
    /// # The one remaining caller
    ///
    /// `tests/translation_unit.rs`'s `taking_a_file_out_of_the_stream_keeps_the_offsets`, which is where the three
    /// properties above are asserted. Nothing in the pipeline calls this any more: the cook no longer drops an
    /// unbalanced file ([`RenderedUnit::unbalanced`]) and the reader no longer drops a file whose brace crossed
    /// ([`RenderedUnit::neutralized`]). It stays because "what would this program be without that file" is a
    /// question the next mechanism will ask again, and because deleting a function whose contract is documented and
    /// tested is how the *reason* for not using it gets forgotten.
    pub fn without(&self, left_out: &std::collections::BTreeSet<u32>) -> RenderedUnit {
        let mut out = self.empty_like();
        let mut bytes = self.text.as_bytes().to_vec();

        for span in &self.spans {
            if !left_out.contains(&span.file) {
                continue;
            }
            for byte in &mut bytes[span.cooked.start_offset..span.cooked.end_offset()] {
                *byte = b' ';
            }
        }

        out.text = String::from_utf8(bytes).expect("only spaces replaced bytes of a UTF-8 stream");
        // **The spans are the original ones**, so an offset in this text is an offset in that one. That is a
        // stronger statement than the one `only` makes — it is the same table, not a copy — and it is what the
        // caller's mapping depends on.
        out.spans = self.spans.clone();
        out
    }

    /// **Only the tokens `file` itself wrote** (a token a macro of its own produced counts) — what a file whose brace
    /// had to be given up is read from, so that its own scopes are all its own.
    ///
    /// Its spans are the original ones, so a fact found here maps back through
    /// [`RenderedUnit::written_span`] exactly as it would from the whole program.
    pub fn only(&self, file: u32) -> RenderedUnit {
        let mut out = self.empty_like();
        for span in &self.spans {
            if span.file == file {
                if span.cooked.start_offset > 0
                    && self.text.as_bytes()[span.cooked.start_offset - 1] == b'\n'
                {
                    out.break_line_before_next();
                }
                // **The spacing this stream already has**, which is the only answer available here: the tokens are
                // copied out of `self.text`, and whether two of them touched is spelled in that text.
                let touching = span.cooked.start_offset > 0
                    && !self.text[..span.cooked.start_offset].ends_with(' ');
                out.push(
                    &self.text[span.cooked.start_offset..span.cooked.end_offset()],
                    span.file,
                    span.written,
                    Some(!touching),
                );
            }
        }
        out
    }

    fn empty_like(&self) -> RenderedUnit {
        RenderedUnit {
            files: self.files.clone(),
            // The lengths travel with the files: every one of these streams answers about the same texts, and a
            // `written_span` answer is only checkable while the two agree.
            file_lengths: self.file_lengths.clone(),
            missing: self.missing,
            unbalanced: self.unbalanced.clone(),
            ..RenderedUnit::default()
        }
    }
}

/// What one walk collects, in the order it was walked.
#[derive(Default)]
struct Walked<'a> {
    /// `(where the name becomes visible, the fact, the file that wrote it)` in translation order, last wins.
    entries: Vec<(usize, &'a MacroFact, &'a str)>,
    /// **The state changes this walk made, in order** — what a contribution replays instead of re-deciding.
    changes: Vec<crate::index::walk_cache::StateChange>,
    /// **How many guarded facts each frame wrote**, by frame id.
    ///
    /// `facts_in_force` is derivable from the events (every event is an in-force fact), but `conditional_facts` counts
    /// the guarded facts that were **not** in force too, and those leave no event. A contribution has to carry this
    /// file's own share, and a map would be a hash lookup on the hottest line in the walk — so it is a `Vec` indexed
    /// by frame id, which `enter` already makes small and dense.
    conditional_by_frame: Vec<usize>,
    /// **Files a spliced contribution entered**, owned rather than borrowed: `seen` holds the caller's `&'a Path`s and
    /// a contribution holds `PathBuf`s, so the question is asked of both.
    spliced: std::collections::HashSet<std::path::PathBuf>,
    /// Bodies of definitions a condition guards that came out **in force** — the second channel.
    /// The body, the fact's `function_like`, and the parameter list — the two things expansion needs and reading
    /// does not. A function-like body **with** its parameters is expandable; without them it is not.
    conditional_bodies: std::collections::BTreeMap<Box<str>, ConditionalBodyValue>,
    conditional_facts: usize,
    facts_in_force: usize,
    /// **The `#define`s this walk decided are not compiled**, by file and offset.
    ///
    /// The decision is made here, against the unit's own state ([`UnitMacros`]) — the same evaluation the cook uses
    /// and the only one that knows what the compilation defines. It has to be handed on, because the file's
    /// **summary** was built from the raw reading and kept every `#define` with the region it was written in; a
    /// consumer that reads the summary instead decides the region again with a different environment and answers
    /// differently. See [`RenderedUnit::dead_macros`].
    dead_macros: std::collections::HashMap<std::path::PathBuf, Vec<usize>>,
    /// **Includes the walk did not enter because their guard was not in force.**
    ///
    /// Counted rather than silent, for the same reason [`Walked::conditional_facts`] is: it is the size of the
    /// difference between the closure this walk builds and "every file any `#include` names", and a reading that
    /// entered a file a compiler does not read is a reading of a different program.
    includes_skipped: usize,
    /// **The timeline, when this walk is building one** — every fact the walk puts in force is also recorded
    /// there, with the file and offset it was written at and the frame it belongs to. `None` for the per-file
    /// walks, which collapse their result into one file's evidence and throw the order away.
    ///
    /// A field on this struct rather than a second walk, because the rules that decide *what is in force* — the
    /// include order, the merge of macros and includes by offset, the guard evaluation — are the expensive and
    /// error-prone part, and a second copy of them is where the next exception gets missed.
    timeline: Option<TimelineBuilder>,
}

impl<'a> Walked<'a> {
    /// The two channels, and the preprocessor's rule for a name defined twice: the later definition wins.
    fn into_evidence(self) -> ClosureEvidence {
        let mut by_name: std::collections::BTreeMap<&str, (usize, &MacroFact, &str)> =
            std::collections::BTreeMap::new();
        for (from_offset, fact, source) in self.entries {
            by_name.insert(&fact.name, (from_offset, fact, source));
        }

        let macros = by_name
            .into_values()
            .map(|(from_offset, fact, source)| {
                let body_text = fact.body_range.and_then(|range| {
                    source.get(range.start_offset..range.start_offset + range.length)
                });

                if fact.kind.is_definition() {
                    cpp_parser::IncludedMacro::defined_with_body_and_parameters(
                        from_offset,
                        &fact.name,
                        fact.function_like,
                        fact.body,
                        body_text,
                        fact.body_range
                            .and_then(|range| parameters_before(source, range.start_offset)),
                    )
                } else {
                    cpp_parser::IncludedMacro::undefined_at(from_offset, &fact.name)
                }
            })
            .collect();

        ClosureEvidence {
            macros,
            conditional_bodies: self
                .conditional_bodies
                .into_iter()
                .map(|(name, (function_like, parameters, body))| {
                    (name, function_like, parameters, body)
                })
                .collect(),
            conditional_facts: self.conditional_facts,
            facts_in_force: self.facts_in_force,
        }
    }
}

/// Walk **one file in translation order**: its macros and its includes **merged by offset**, descending into each
/// `#include` at the point it is written.
///
/// That order is the whole point, and getting it wrong is invisible until a condition depends on it: a header
/// includes `winapifamily.h` at its top and asks `#if WINAPI_FAMILY_PARTITION (…)` sixty lines later, so a walk
/// that read a file's macros *before* its includes judges that condition against a table which does not have the
/// macro yet. Measured: that is exactly why `combaseapi.h`'s `STDMETHOD` never came into force, and therefore
/// never reached `commdlg.h`.
#[allow(clippy::too_many_arguments)]
/// **Where one file's contribution starts**, captured at its entry so the tail can record a delta rather than the
/// whole timeline. See `index::walk_cache`.
struct Bases {
    key: u64,
    events: usize,
    changes: usize,
    dead: usize,
}

/// **The macro name an include guard tests** — `_GLIBCXX_CXX_CONFIG` for a file that opens with
/// `#ifndef _GLIBCXX_CXX_CONFIG`.
///
/// Read from the region's stored condition rather than from the file's first line: `guards.own_guard` already names
/// the region the idiom opens, and the branch that opens it holds exactly the name (`GuardBranch::condition` is "the
/// name for `#ifdef`/`#ifndef`"). `None` for a guard this cannot read, which makes the caller read the file again —
/// the safe direction, because a re-read whose guard *is* in force costs a walk of skipped facts and nothing else.
fn guard_name_of(file: &FileSummary, region: u32) -> Option<&str> {
    let conditional = file.guards.conditionals.get(region as usize)?;
    let first = conditional.branches.first()?;
    if !matches!(
        first.kind,
        crate::DirectiveKind::Ifdef | crate::DirectiveKind::Ifndef
    ) {
        return None;
    }

    let name = first.condition.as_deref()?.trim();
    (!name.is_empty() && !name.contains(char::is_whitespace)).then_some(name)
}
/// **How deep `#include`s may nest** — a preprocessor's own limit, and the one thing that ends a cycle of *unguarded*
/// headers. GCC's is 200 (`-fmax-include-depth` is the knob for a deeper one); this is that number, and it is a bound
/// rather than a visited-set because a preprocessor genuinely re-reads a file every time it is included.
const MAX_INCLUDE_DEPTH: usize = 200;

fn walk_one_file<'a>(
    path: &'a std::path::Path,
    from_offset: usize,
    parent: Option<u32>,
    from_in_parent: usize,
    // How deep in `#include`s this file is — 0 for the root, bounded by `MAX_INCLUDE_DEPTH`.
    depth: usize,
    seen: &mut std::collections::HashSet<&'a std::path::Path>,
    look_up: &mut impl FnMut(&std::path::Path) -> Option<(&'a FileSummary, &'a str)>,
    seed: &Marked,
    definitions_of: &mut MacroDefinitions,
    unit: &mut UnitState,
    walked: &mut Walked<'a>,
    share: bool,
    cache: &crate::index::walk_cache::WalkCache,
) -> Option<u64> {
    // **A preprocessor re-reads an included file every time it is included, and the file's own text is what makes
    // the repeat contribute nothing.** The `#ifndef X / #define X` idiom is a *condition in the file*, evaluated like
    // any other: it says false the second time, so the body is skipped. Skipping the second read in the walk instead
    // is only the same thing for a file that is idempotent by construction — `#pragma once`, which the index records
    // as `guards.visit_once`.
    //
    // The difference is not theoretical, and it is why `import std;` had no `std::println`: libstdc++'s
    // `bits/version.h` is deliberately **unguarded** — every libstdc++ header includes it to add the feature-test
    // macros *that header* asks for (`#define __glibcxx_want_print` then `#include <bits/version.h>`) — so a walk
    // that entered it once, from `<version>`, never defined `__cpp_lib_print` for `print`, and `print`'s whole body
    // (inside `#ifdef __cpp_lib_print`) was dropped: its summary held **0 declarations**, and every `std::println`
    // answered `NotDeclaredHere`.
    //
    // Two things still stop a second read: `#pragma once` (below, once the summary is in hand), and a **bound on the
    // nesting depth** — a cycle of unguarded headers is the one shape the file's own rule cannot end. GCC's
    // `#include` nesting limit is 200, and this is that number.
    if walked.spliced.contains(path) {
        if crate::probes::splice() {
            eprintln!("leave early (already spliced): {}", path.display());
        }
        return None;
    }

    let already_read = !seen.insert(path);
    if crate::probes::splice() {
        eprintln!(
            "enter: {} | already seen {}, depth {depth}, spliced {}, timeline {}",
            path.display(),
            already_read,
            walked.spliced.contains(path),
            walked.timeline.is_some(),
        );
    }
    if depth >= MAX_INCLUDE_DEPTH {
        walked.includes_skipped += 1;
        return None;
    }

    let Some((file, source)) = look_up(path) else {
        // A file this walk cannot read is a file **outside the analysis**: none of the files the caller indexed.
        // Pretending it defines nothing is the reading every walk here has always taken — a name nobody saw is
        // `Undefined`, which is what lets `#ifndef GUARD` open a header at all.
        //
        // Marking the unit incomplete instead — "this file may define anything" — was tried and measured: it turns
        // every `#ifndef` of every header into `Unknown`, and the conditional evidence the corpus produces
        // collapses from millions of facts to tens of thousands. The honest answer for one file must not cost the
        // whole unit's evidence.
        return None;
    };

    // **`#pragma once`, and the include guard: the two ways the file itself decides a second read.**
    //
    // `#pragma once` is recorded as `guards.visit_once`. The guard idiom (`#ifndef X / #define X`) is not special to
    // a preprocessor — it is a condition, and on the second read it is false, so the body is not read. The walk
    // **knows** the idiom (`guards.own_guard` is the region it opens) and the region holds the name it tests, so the
    // second read is a hash lookup rather than a walk of a body whose every fact would be skipped anyway.
    //
    // That is not an optimisation: without it, re-entry is **exponential**. The libstdc++ closure is a DAG with heavy
    // fan-in (`bits/c++config.h` is included by some two hundred headers), so a walk that re-reads bodies walks the
    // DAG's number of *paths*, not its number of files. Measured: the first attempt at re-entry died on an 8 GB
    // allocation while indexing `import std;`.
    if already_read && file.guards.visit_once {
        return None;
    }
    if already_read
        && let Some(own) = file.guards.own_guard
        && let Some(name) = guard_name_of(file, own)
        && unit.definitions.contains_key(name)
    {
        return None;
    }

    let defined_in_force = |name: &str| unit.definitions.contains_key(name);
    crate::index::walk_census::entered(path, source, defined_in_force);

    // **The sharing key, and the splice** — §4.3. The key is the file and the *projection*: the
    // values of the names its conditions read, measured at 37× reuse. Contributions are kept honest
    // by being cleared whenever a summary is invalidated, so no content hash is carried — see
    // `index::walk_cache`. **Off until the order is right.** A contribution currently keeps its
    // state changes and its include edges in two lists, and the splice replays all of the changes
    // before recursing the edges — but the walk interleaves them **by offset**: a `#define` written
    // after an `#include` must take effect after it. Measured: one semantics test failed
    // (`a_declaration_only_a_macro_makes_is_found_once_the_session_has_cooked_the_file`), which is
    // what an order error looks like from the outside. **`share` is the caller's answer to "is this
    // unit complete?"** — and it has to be the caller's, because the closure it walks is the
    // caller's: `look_up` can only answer for the files the closure holds, so a unit built while
    // the closure was still growing is missing files the index has since read. `session` already
    // calls that a *provisional* unit and refuses to store one; the sharing cache has the same
    // reason and must be neither written nor read for one. That was the third divergence, measured:
    // `look_up(child)` answered `None` inside a growing closure, the child contributed nothing, and
    // a later complete unit hit that contribution and lost the subtree under it.
    let sharing = (share && walked.timeline.is_some()).then(|| {
        crate::index::walk_cache::key(
            path,
            // **The file's own contents, as a fingerprint.** The invalidation clock covers a summary being dropped, but
            // a header can be rewritten underneath a unit that still holds it; a key without the contents went stale
            // and `a_completion_sees_a_change_to_an_included_header` caught it. The fingerprint is O(1) in the file's
            // size, and the contribution's own subtree is covered by the clock.
            crate::index::walk_census::hash(source.as_bytes()),
            crate::index::walk_census::projection_digest(path, source, defined_in_force),
        )
    });
    if let Some(key) = sharing
        && cache.lookup(key).is_some()
        && !walked.spliced.contains(path)
    {
        crate::index::walk_census::a_splice();
        if splice_a_contribution(
            key,
            from_offset,
            parent,
            from_in_parent,
            seen,
            look_up,
            unit,
            walked,
            0,
            cache,
        ) {
            return Some(key);
        }
    }

    let bases = sharing.map(|key| Bases {
        key,
        events: walked
            .timeline
            .as_ref()
            .map_or(0, |timeline| timeline.events.len()),
        changes: walked.changes.len(),
        dead: walked.dead_macros.get(path).map_or(0, Vec::len),
    });
    let mut edges: Vec<(usize, u64)> = Vec::new();

    // The frame this file occupies in the unit's timeline, when the walk is building one. Entered **after** the
    // two early returns above, so a file that is skipped leaves no frame behind — and closed at the end of this
    // function, which is after every file it includes has been walked, so the frame's subtree is an interval.
    let frame = walked
        .timeline
        .as_mut()
        .map(|timeline| timeline.enter(path, parent, from_in_parent, file.guards.visit_once));
    if let Some(frame) = frame
        && walked.conditional_by_frame.len() <= frame as usize
    {
        walked.conditional_by_frame.resize(frame as usize + 1, 0);
    }

    // **One answer per *(region, branch)*, with the generation it was worked out at.**
    //
    // The key is the whole correctness of this, and the first version of it was wrong: it was keyed by *region* alone,
    // which is not enough — a region's condition is asked once per fact inside it, and two facts in the same region
    // can be in **different branches**, which is a different question with a different answer. That version was caught
    // by its own effect on the diagnostics (36 findings became 18) rather than by reasoning, and reverted.
    //
    // `(region, branch)` is sound because the branches of a region are ranges and regions nest: if two positions fall
    // in the same branch of the innermost region, they fall in the same branch of every region enclosing it, so the
    // *whole chain* [`SummaryGuards::visibility_of`] walks is fixed by the pair. What is left is the environment —
    // which is what the generation covers, and only a change to the set in force can make it stale.
    // **Three answers per region**, not two: see the note where it is read. The memo has to hold the third one too,
    // or a region nobody can decide would be remembered as dead on its second fact.
    let mut decided: rustc_hash::FxHashMap<(u32, u32), crate::preprocess::guard::Visibility> =
        Default::default();
    // The generation every answer in `decided` was worked out at. The memo lives *between two changes to the set in
    // force* and nowhere longer, which is what the clearing below says in one line.
    let mut decided_at = unit.generation;

    let mut macros = file.macros.iter().peekable();
    let mut includes = file.includes.iter().peekable();

    loop {
        // Whichever the file writes **first**: that is the order a preprocessor reads them in, and a condition
        // depends on it.
        let next_is_a_macro = match (macros.peek(), includes.peek()) {
            (Some(fact), Some(include)) => fact.range.start_offset <= include.range.start_offset,
            (Some(_), None) => true,
            (None, _) => false,
        };

        if next_is_a_macro {
            let fact = macros.next().expect("peeked just above");
            let (in_force, visibility) = if matches!(fact.guard, FactGuard::Unconditional) {
                (true, crate::preprocess::guard::Visibility::Active)
            } else {
                walked.conditional_facts += 1;
                if let Some(at) = frame.map(|frame| frame as usize) {
                    if walked.conditional_by_frame.len() <= at {
                        walked.conditional_by_frame.resize(at + 1, 0);
                    }
                    walked.conditional_by_frame[at] += 1;
                }
                // **Which branch this fact falls in**, asked of the ranges alone — no macro is consulted, which is
                // what makes it usable as part of a key.
                let branch = match fact.guard {
                    // `regions` and `conditionals` are two views of the same list, indexed by the same region number
                    // — see `SummaryGuards` — so the branch is one lookup away, and it needs no macro.
                    crate::summary::FactGuard::Region(region) => file
                        .guards
                        .conditionals
                        .get(region as usize)
                        .and_then(|conditional| conditional.branch_at(fact.range.start_offset))
                        .map(|branch| (region, branch as u32)),
                    crate::summary::FactGuard::Unconditional => None,
                };

                // **Anything the set in force has changed since the last fact makes every answer suspect** — a
                // definition fed by this file, or by a file it includes, can turn a branch on or off from its own
                // line downwards. Clearing is the honest reaction and it is cheap: the map holds one entry per
                // *(region, branch)*, and definitions arrive in bursts rather than between every two facts.
                if unit.generation != decided_at {
                    decided.clear();
                    decided_at = unit.generation;
                }

                // **Three answers, not two.** `Inactive` is a branch the compiler does not read; `Unknown` is one
                // nobody can decide, and a `#define` in a region nobody can decide must **not** be dropped: a compiler
                // takes one branch or the other, so the name is defined afterwards either way. Measured on
                // `import std;`: `<xstddef>` defines `_MEMBER_CALL_CV_REF_NOEXCEPT` in **both** branches of
                // `#ifdef __cpp_noexcept_function_type` and no file `#undef`s it, yet the walk never fed it — so
                // `<xtr1common>`'s usages were left in the rendering as text.
                let visibility = match branch.and_then(|key| decided.get(&key).copied()) {
                    Some(answer) => answer,
                    None => {
                        let answer =
                            crate::index::environment::a_guard_visibility(file, fact, |at| {
                                UnitMacros {
                                    seed,
                                    state: unit,
                                    here: Some((path, at)),
                                }
                            });
                        if let Some(key) = branch {
                            decided.insert(key, answer);
                        }
                        answer
                    }
                };
                let taken = visibility == crate::preprocess::guard::Visibility::Active;
                if taken {
                    walked.facts_in_force += 1;
                }
                (taken, visibility)
            };

            if !in_force {
                match visibility {
                    // **A branch the compiler does not read.** Recorded before the skip, because the file's own
                    // summary kept this `#define` and a consumer would otherwise decide the region again with a
                    // different environment. See [`RenderedUnit::dead_macros`].
                    crate::preprocess::guard::Visibility::Inactive => {
                        walked
                            .dead_macros
                            .entry(path.to_path_buf())
                            .or_default()
                            .push(fact.range.start_offset);
                    }
                    // **A branch nobody can decide.** A `#define` here is kept as a definition for what follows — a
                    // compiler takes one branch or the other, so the name is defined afterwards either way, and
                    // dropping it is what left `_MEMBER_CALL_CV_REF_NOEXCEPT` undefined in `import std;`. An `#undef`
                    // is **not** executed: taking a name away on a guess is the error in the other direction.
                    crate::preprocess::guard::Visibility::Unknown if fact.kind.is_definition() => {
                        if let Some(definition) = definitions_of.get_or_read(path, source, fact) {
                            unit.define(&fact.name, definition, path, fact.range.start_offset);
                        }
                    }
                    crate::preprocess::guard::Visibility::Unknown => {}
                    crate::preprocess::guard::Visibility::Active => {}
                }
                continue;
            }

            // What a preprocessor's table would have: the name with its body and parameter list, or taken away
            // again. Fed for conditional facts too — a `#define` in a branch that **was** taken is a definition like
            // any other, and it is what the next file's conditions are answered against.
            if fact.kind.is_definition() {
                if let Some(definition) = definitions_of.get_or_read(path, source, fact) {
                    walked
                        .changes
                        .push(crate::index::walk_cache::StateChange::Defined {
                            name: Box::from(&*fact.name),
                            definition: definition.clone(),
                            file: path.to_path_buf(),
                            at: fact.range.start_offset,
                        });
                    unit.define(&fact.name, definition, path, fact.range.start_offset);
                } else {
                    // A `#define` this reader cannot put back together is a name the unit has seen and cannot
                    // describe: defined, with nothing more to say. Better than dropping it — an `#ifdef` about it
                    // is a real question with a real answer.
                    // A #define this reader cannot put back together is not fed at all: the compilation's own
                    // table answers instead, which is Undefined — a lost reading rather than a wrong one.
                }
            } else {
                walked
                    .changes
                    .push(crate::index::walk_cache::StateChange::Undefined {
                        name: Box::from(&*fact.name),
                        file: path.to_path_buf(),
                        at: fact.range.start_offset,
                    });
                unit.undefine(&fact.name);
            }

            // The **evidence** is still two channels: definitions only from what no condition guards, and
            // bodies from everything in force. The state above is a third, separate thing — it exists to answer
            // *conditions*, and it deliberately carries no bodies.
            //
            // **An `#undef` in force decides its name on both channels.** Its guard does not matter: a name this
            // walk has just seen taken away is not one any earlier `#define` in the closure still defines, and a
            // `#define` behind an `#if` is exactly what a later `#undef` behind another `#if` cancels — the
            // Windows precompiled header shape this was measured on (`min`/`max`). Without the `remove`, the
            // in-force channel kept the body it had already collected, and the in-force channel is consulted
            // before the positional one.
            if !fact.kind.is_definition() {
                walked.conditional_bodies.remove(&*fact.name);
            }
            if matches!(fact.guard, FactGuard::Unconditional) {
                walked.entries.push((from_offset, fact, source));
            } else if fact.kind.is_definition()
                && let Some(text) = fact.body_range.and_then(|range| {
                    source.get(range.start_offset..range.start_offset + range.length)
                })
            {
                let parameters = fact
                    .body_range
                    .and_then(|range| parameters_before(source, range.start_offset))
                    .map(Box::from);
                walked.conditional_bodies.insert(
                    Box::from(&*fact.name),
                    (fact.function_like, parameters, Box::from(text)),
                );
            }

            // …and the **timeline**, when there is one: every fact in force, both channels, with the file and the
            // offset it was written at. This is the record a file's environment is later read out of, so it must
            // hold what the per-file walk would have collected — including the conditional-but-in-force bodies the
            // second channel carries.
            if let (Some(frame), Some(timeline)) = (frame, walked.timeline.as_mut()) {
                timeline.record(
                    frame,
                    fact,
                    source,
                    matches!(fact.guard, FactGuard::Unconditional),
                );
            }

            continue;
        }

        let Some(include) = includes.next() else {
            break;
        };
        // **An `#include` is a guarded fact, and the walk asks whether its guard is in force.**
        //
        // It did not, and that is not a small omission on a compiler's own headers: *every* conditional include in
        // them was entered. `sal.h` writes
        //
        // ```cpp
        // #if _USE_ATTRIBUTES_FOR_SAL          // 1561 — which the cooker decides is **0**
        // #include "CodeAnalysis/sourceannotations.h"
        // ```
        //
        // and the walk descended anyway, pulling 1020 tokens of `/analyze`-only declarations into a program that
        // never asks for them — 99% of the reading of `#include <sal.h>`, and the first difference against cl.exe on
        // `#include <vector>`. Meanwhile the *cooker* answered the same guard correctly, which is what made the two
        // disagree: one layer asked, the other did not.
        //
        // A guard that cannot be decided is **`Unknown`, and `a_guard_holds` is false for it** — the same rule the
        // macro facts below already followed, and the reason `Visibility` has three states rather than two.
        //
        // Taken under its own timer: one per include per visit, and `Walk` was measured at 78 s with nothing inside
        // it accounted for.
        let include_is_in_force = {
            crate::index::environment::a_guard_holds(
                file,
                include.guard,
                include.range.start_offset,
                |at| UnitMacros {
                    seed,
                    state: unit,
                    here: Some((path, at)),
                },
            )
        };
        if !include_is_in_force {
            walked.includes_skipped += 1;
            continue;
        }

        // **A file that includes itself is not followed.** uriparser's `uri.h` writes `#include "Uri.h"` twice,
        // inside regions a doxygen build takes, and on Windows the spelling resolves to the file itself — so the
        // walk descended into the header it was already reading, and an unguarded file has nothing to stop it: the
        // census measured **197 470 entries of `uri.h`** and a walk that never finished at 6 GB. A preprocessor
        // cannot meaningfully include the file it is reading, so the edge is recorded as skipped.
        if include
            .resolved
            .as_deref()
            .is_some_and(|nested| nested == file.path)
        {
            walked.includes_skipped += 1;
            continue;
        }

        let child_key = include.resolved.as_deref().and_then(|nested| {
            walk_one_file(
                nested,
                include.range.start_offset + include.range.length,
                frame,
                include.range.start_offset + include.range.length,
                depth + 1,
                seen,
                look_up,
                seed,
                definitions_of,
                unit,
                walked,
                share,
                cache,
            )
        });
        if let Some(child) = child_key {
            edges.push((include.range.start_offset + include.range.length, child));
        }
    }

    if let (Some(frame), Some(timeline)) = (frame, walked.timeline.as_mut()) {
        timeline.leave(frame);
    }

    // **File what this file contributed** — its own frame's work and the edges it took, so that a later unit that
    // reaches it with the same projection splices it instead of walking it. See `index::walk_cache`.
    // **A file whose includes are not resolved yet is not cacheable.**
    //
    // Its contribution would record **no edges** — the walk only descends an `#include` whose target is known — and a
    // later unit, with the include resolved, would hit that contribution and lose the whole subtree under it. That is
    // exactly how `a_declaration_only_a_macro_makes_is_found_once_the_session_has_cooked_the_file` failed: the first
    // unit for a file that includes a header not yet read recorded an empty edge list, and the second unit trusted it.
    // The summary's own resolution state is the guard, and it is a fact about the summary rather than about the walk —
    // which is why the invalidation clock cannot cover it.
    let resolvable = !file
        .includes
        .iter()
        .any(|include| include.resolved.is_none());
    if let (true, Some(bases), Some(frame), Some(timeline)) =
        (resolvable, bases, frame, walked.timeline.as_ref())
    {
        let mut contribution = crate::index::walk_cache::Contribution {
            file: path.to_path_buf(),
            visit_once: file.guards.visit_once,
            edges,
            ..crate::index::walk_cache::Contribution::default()
        };

        for event in timeline.events[bases.events..]
            .iter()
            .filter(|event| event.frame == frame)
        {
            let mut carried = event.clone();
            carried.frame = 0;
            if !carried.unconditional
                && carried.function_like.is_some()
                && let Some(body) = carried.body_text.clone()
            {
                contribution
                    .bodies
                    .push(crate::index::walk_cache::ConditionalBody {
                        name: carried.name.to_string().into_boxed_str(),
                        function_like: carried.function_like.unwrap_or(false),
                        parameters: carried
                            .parameters
                            .as_ref()
                            .map(|p| p.to_string().into_boxed_str()),
                        body: body.to_string().into_boxed_str(),
                    });
            }
            contribution.facts_in_force += 1;
            contribution.events.push(carried);
        }

        contribution.changes = walked.changes[bases.changes..]
            .iter()
            .filter(|change| change.file() == path)
            .cloned()
            .collect();
        contribution.dead = walked
            .dead_macros
            .get(path)
            .map(|decided| decided[bases.dead.min(decided.len())..].to_vec())
            .unwrap_or_default();
        contribution.conditional_facts = walked
            .conditional_by_frame
            .get(frame as usize)
            .copied()
            .unwrap_or(0);

        crate::index::walk_census::a_fresh_walk();

        cache.store(bases.key, contribution);

        return Some(bases.key);
    }

    None
}

///
/// One frame for the file, its state changes replayed in order, its own evidence rebuilt from its own events, and then
/// each **edge** it recorded spliced recursively under that frame. Nothing is re-decided and no text is read.
///
/// The evidence is rebuilt because a contribution stores no borrows: an unconditional event is an entry, and the fact
/// behind it is found again in the summary by its offset, the summary's own `macros` being in offset order.
#[allow(clippy::too_many_arguments)]
fn splice_a_contribution<'a>(
    key: u64,
    from_offset: usize,
    parent: Option<u32>,
    from_in_parent: usize,
    seen: &std::collections::HashSet<&'a std::path::Path>,
    look_up: &mut impl FnMut(&std::path::Path) -> Option<(&'a FileSummary, &'a str)>,
    unit: &mut UnitState,
    walked: &mut Walked<'a>,
    depth: usize,
    cache: &crate::index::walk_cache::WalkCache,
) -> bool {
    /// A guard against a contribution graph that somehow points into itself. A unit's include graph is a DAG, and this
    /// is a cheap bound rather than an argument about it.
    const MAX_SPLICE_DEPTH: usize = 256;

    if depth > MAX_SPLICE_DEPTH {
        return false;
    }
    let Some(contribution) = cache.lookup(key) else {
        return false;
    };

    let Some(timeline) = walked.timeline.as_mut() else {
        return false;
    };
    let frame = timeline.frames.len() as u32;
    let event_base = timeline.events.len() as u32;
    let (built, events) =
        crate::index::walk_cache::rebased(&contribution, frame, event_base, parent, from_in_parent);
    let file = built.file.clone();
    timeline.entered.entry(frame_key(&file)).or_insert(frame);
    timeline.frames.push(built);
    timeline.events.extend(events);

    // **A file's own facts and the includes it took are one sequence in the source**, and the walk
    // visits them in offset order.
    for body in &contribution.bodies {
        walked.conditional_bodies.insert(
            body.name.clone(),
            (
                body.function_like,
                body.parameters.clone(),
                body.body.clone(),
            ),
        );
    }
    walked
        .dead_macros
        .entry(file.clone())
        .or_default()
        .extend(contribution.dead.iter().copied());
    walked.conditional_facts += contribution.conditional_facts;
    walked.facts_in_force += contribution.facts_in_force;

    let summary = look_up(&file);
    let mut next_event = 0usize;
    let mut next_change = 0usize;
    let mut next_edge = 0usize;
    loop {
        let next = [
            contribution.events.get(next_event).map(|event| event.at),
            contribution
                .changes
                .get(next_change)
                .map(|change| change.at()),
            contribution.edges.get(next_edge).map(|(at, _)| *at),
        ]
        .into_iter()
        .flatten()
        .min();
        let Some(next) = next else {
            break;
        };

        // The state at this offset: a definition or an `#undef` takes effect here, before anything it pulls in.
        while contribution
            .changes
            .get(next_change)
            .is_some_and(|change| change.at() == next)
        {
            match &contribution.changes[next_change] {
                crate::index::walk_cache::StateChange::Defined {
                    name,
                    definition,
                    file,
                    at,
                } => unit.define(name, definition.clone(), file, *at),
                crate::index::walk_cache::StateChange::Undefined { name, .. } => {
                    unit.undefine(name)
                }
            }
            next_change += 1;
        }

        // The evidence this file wrote here.
        while contribution
            .events
            .get(next_event)
            .is_some_and(|event| event.at == next)
        {
            let event = &contribution.events[next_event];
            if event.unconditional
                && let Some((summary, source)) = summary
                && let Ok(found) = summary
                    .macros
                    .binary_search_by_key(&event.at, |fact| fact.range.start_offset)
            {
                walked
                    .entries
                    .push((from_offset, &summary.macros[found], source));
            }
            next_event += 1;
        }

        // And whatever this file included here, spliced under this frame.
        while contribution
            .edges
            .get(next_edge)
            .is_some_and(|(at, _)| *at == next)
        {
            let (at, child) = contribution.edges[next_edge];
            // **The include-guard rule, on the recursion too.** The walk enters a file once per unit; a splice that
            // re-entered one would duplicate its evidence, which is a different unit. Measured: this is what kept
            // `a_declaration_only_a_macro_makes_is_found_once_the_session_has_cooked_the_file` red.
            let already_entered = cache.lookup(child).is_some_and(|child| {
                seen.contains(child.file.as_path()) || walked.spliced.contains(&child.file)
            });
            if !already_entered {
                splice_a_contribution(
                    child,
                    at,
                    Some(frame),
                    at,
                    seen,
                    look_up,
                    unit,
                    walked,
                    depth + 1,
                    cache,
                );
            }
            next_edge += 1;
        }
    }

    for change in &contribution.changes {
        match change {
            crate::index::walk_cache::StateChange::Defined {
                name,
                definition,
                file,
                at,
            } => unit.define(name, definition.clone(), file, *at),
            crate::index::walk_cache::StateChange::Undefined { name, .. } => unit.undefine(name),
        }
    }

    if let Some((summary, source)) = look_up(&file) {
        for event in &contribution.events {
            if !event.unconditional {
                continue;
            }
            let Ok(at) = summary
                .macros
                .binary_search_by_key(&event.at, |fact| fact.range.start_offset)
            else {
                continue;
            };
            walked
                .entries
                .push((from_offset, &summary.macros[at], source));
        }
    }
    for body in &contribution.bodies {
        walked.conditional_bodies.insert(
            body.name.clone(),
            (
                body.function_like,
                body.parameters.clone(),
                body.body.clone(),
            ),
        );
    }
    walked
        .dead_macros
        .entry(file.clone())
        .or_default()
        .extend(contribution.dead.iter().copied());
    walked.conditional_facts += contribution.conditional_facts;
    walked.facts_in_force += contribution.facts_in_force;

    if let Some(timeline) = walked.timeline.as_mut() {
        timeline.leave(frame);
    }
    if crate::probes::splice() {
        eprintln!(
            "splice: {} | {} changes, {} edges, {} events",
            file.display(),
            contribution.changes.len(),
            contribution.edges.len(),
            contribution.events.len(),
        );
    }
    walked.spliced.insert(file);

    true
}

/// The macros a file's **direct** includes define — the one-hop variant, kept as the measured comparison for the
/// closure walk above.
pub fn macros_from_direct_includes<'a>(
    summary: &FileSummary,
    mut look_up: impl FnMut(&std::path::Path) -> Option<&'a FileSummary>,
) -> Vec<cpp_parser::IncludedMacro> {
    let mut entries = Vec::new();

    for include in &summary.includes {
        let Some(included) = include.resolved.as_deref().and_then(&mut look_up) else {
            continue;
        };
        // Where the name becomes visible: the end of the `#include` directive, which is where a consumer of the
        // tree would put a marker.
        let from_offset = include.range.start_offset + include.range.length;

        for fact in &included.macros {
            if !matches!(fact.guard, FactGuard::Unconditional) {
                continue;
            }

            entries.push(if fact.kind.is_definition() {
                cpp_parser::IncludedMacro::defined_at(
                    from_offset,
                    &fact.name,
                    fact.function_like,
                    fact.body,
                )
            } else {
                cpp_parser::IncludedMacro::undefined_at(from_offset, &fact.name)
            });
        }
    }

    entries
}

/// `#include "local.h"` against `#include <system.h>`.
///
/// **Re-used from the preprocessor rather than re-declared here**: the two are searched for differently, the
/// directive reader is what knows that, and a second enum with the same two variants is how the two layers would
/// come to disagree about a spelling.
pub use crate::preprocess::directive::IncludeForm;

/// Which conditional region a fact was written in.
///
/// An index into the file's [`SummaryGuards`] rather than an inline condition: many facts share one region, and a
/// region is a small tree while a fact is meant to be tiny. [`FactGuard::Unconditional`] is the common case — code
/// outside every `#if` — and it is a variant rather than `0` so that a fact can never be misread as guarded by
/// forgetting to fill a field in.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FactGuard {
    Unconditional,
    Region(u32),
}

/// The conditional regions a file's facts refer to, in the order they were opened.
///
/// A region is stored as its **question**, never as its answer. Whether a region is entered depends on the
/// macros in force, and those are a property of the compilation rather than of the file: the `-D`s, the `-std=`
/// that fixes `__cplusplus`, and the five hundred names a compiler predefines. A summary is keyed without any of
/// that (see `cache.rs`), so the answer cannot live here — the same reasoning that keeps a resolved type out of a
/// declaration fact. A query that has the environment evaluates the stored question; one that does not answers
/// `Unknown`, which is what every consumer of this type did before the questions were stored at all.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SummaryGuards {
    /// One entry per region: the span of its conditions, which is its identity in [`FactGuard::Region`].
    pub regions: Vec<cpp_parser::SourceRange>,
    /// One entry per region, in the same order: the branches written for it, and what encloses it.
    pub conditionals: Vec<ConditionalRegion>,
    /// The region the file's **own include guard** opens, when it has one.
    ///
    /// Not a condition, and that is the whole point: `#ifndef _GLIBCXX_STRING` at the top of `string` is the file
    /// saying "read me once", not a feature test — entering the file at all is what the guard means, so a fact
    /// inside it is as visible as one written outside every `#if`. The index already treats the facts whose guard
    /// is *exactly* this region that way ([`crate::FileSummary`], `deguard_the_files_own_guard`); storing the
    /// index is what lets a walk treat the *nested* ones that way too, and a nested fact is the common case —
    /// `#ifndef GUARD / #define GUARD` followed by a file full of `#if __cplusplus` blocks.
    ///
    /// Without it those blocks read as "the guard is not taken", because by the time they are evaluated the guard
    /// has *defined* its own name — a file whose contents are `#ifndef X / #define X / … #endif` would answer
    /// "inactive" to everything inside it, which is exactly backwards.
    pub own_guard: Option<u32>,
    /// **The file writes `#pragma once`**, and so is entered at most once per translation unit.
    ///
    /// Stored rather than derived at the point it is needed, because the two places that need it are far from the
    /// directives: the walk, which skips a second visit, and the **renderer**, which has to put the pragma into the
    /// stream. `#pragma once` is the one directive that is *recognised* and, until this field existed, never
    /// *produced* — the cook only ever sees the file it is cooking, and a header that is nothing but directives
    /// contributes no token to be cooked at all, so its `#pragma once` never reached the output.
    ///
    /// Measured on `#include <vector>`: the compiler's stream carries **54** of them and ours carried none of the
    /// ones from such files, which is what made the first difference a `#pragma`: every compiler emits the pragma of
    /// each file it enters, and the presence of that line is how a reader sees which files a compilation read.
    pub visit_once: bool,
}

/// One conditional region: the chain of branches a single `#if` opened.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConditionalRegion {
    /// The branches in source order; the first is the `#if`/`#ifdef`/`#ifndef` that opened the region.
    pub branches: Vec<GuardBranch>,
    /// The conditional this one is written inside, by region index.
    ///
    /// Stored rather than derived from the spans, because a region's span is its **condition**: a nested
    /// region's condition lies inside its parent's body, and so does the text of a sibling `#elif`. Which
    /// conditional encloses which is a fact about the nesting, and arithmetic on two ranges would be a second
    /// way of computing it — free to disagree with the walk that knew.
    ///
    /// Regions are numbered in opening order, so a parent always has a smaller index than its children.
    pub parent: Option<u32>,
    /// **The branches as the guard layer reads them — built once, not once per question.**
    ///
    /// `branches` above stores each condition as **text**, and reading it back is a lex: `as_branch` →
    /// `GuardBranch::tokens()` → `CppLexer`. `region_at` did that on every call, and it is called once per
    /// condition inside `visibility_of`'s loop — 37 M times in an index of a real project, each rebuilding a
    /// `Vec<Branch>` with a `Box<str>` per token.
    ///
    /// It also threw away every `Branch` cache before it could be read twice, which is what made the parse cache in
    /// `an_expression_holds` worth only 35% of what it should be: the parse was kept, and the `Branch` holding it was
    /// dropped at the end of the same guard.
    ///
    /// `OnceLock` rather than a precomputed field because a summary is decoded from bytes and most regions are never
    /// asked about: a file whose `#if`s nobody evaluates should pay nothing for this.
    ///
    /// **Not part of equality** — it is derived from `branches`, which is.
    pub decoded: std::sync::OnceLock<Vec<crate::Branch>>,
}

/// One branch of a conditional: what it asks, and the body it guards.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GuardBranch {
    /// Which directive wrote it: `#if`, `#ifdef`, `#ifndef`, `#elif` or `#else`.
    pub kind: crate::DirectiveKind,
    /// The condition as **text to evaluate**: the expression's tokens for `#if`/`#elif` (`__cplusplus >=
    /// 201703L`), the name for `#ifdef`/`#ifndef` (`_WIN32`), and `None` for `#else`, which has no condition and
    /// holds when nothing before it did.
    ///
    /// Text rather than tokens because a token list is four fields and a range per token in every cache entry,
    /// and because reading it back is one call to the lexer that read it the first time. Text rather than a
    /// *value* because there is nothing to evaluate it with here — see [`SummaryGuards`].
    pub condition: Option<Box<str>>,
    /// The body: from after this branch's directive to the next branch's directive, or to the `#endif`.
    ///
    /// Zero-length for an empty branch, which is what `#if A\n#else\n...` writes and what a consumer has to
    /// read as "no code here" rather than as "a body I could not find".
    pub body: cpp_parser::SourceRange,
    /// Where the directive is, so that a consumer explaining "this is not compiled" can point at the condition
    /// that decided it.
    pub range: cpp_parser::SourceRange,
}

/// One conditional that contains a position, and where its own condition is.
///
/// The two are different offsets and both are needed: which branch the position falls in is asked at the
/// position, while *what the condition means* is decided where the condition was written — a `#define NAME`
/// inside a region's own body changes the answer to `#ifndef NAME` if it is read at the wrong end of the region.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ConditionAt {
    /// Which entry of [`SummaryGuards::regions`] this is.
    pub region: u32,
    /// The offset of the region's own condition, which is where it must be evaluated.
    pub condition_at: usize,
}

impl SummaryGuards {
    /// The conditionals containing `offset`, **innermost first**.
    ///
    /// Empty for code outside every `#if`, which is the common case and the cheap one. This is the general
    /// answer, for a caller that has a position and no guard; a caller that *has* the guard — which is every
    /// caller in this crate, because a fact records one — should use [`SummaryGuards::conditions_of`] instead:
    /// it walks the nesting outwards from the region the guard names, where this has to look for it.
    pub fn conditions_at(&self, offset: usize) -> Vec<ConditionAt> {
        let mut found: Vec<ConditionAt> = Vec::new();

        // Innermost first: the smallest region that contains the position, then its parent, and so on. A region
        // contains the position when the position is inside one of its branch *bodies* — the region's own span
        // starts at its condition, and a position before the first branch's body is not in the region at all.
        let mut current = (0..self.conditionals.len())
            .filter(|index| self.conditionals[*index].contains(offset))
            .min_by_key(|index| {
                self.span_of(*index as u32)
                    .map_or(usize::MAX, |span| span.length)
            });

        while let Some(index) = current {
            let Some(span) = self.span_of(index as u32) else {
                break;
            };

            if Some(index as u32) != self.own_guard {
                found.push(ConditionAt {
                    region: index as u32,
                    condition_at: span.start_offset,
                });
            }

            current = self.conditionals[index]
                .parent
                .map(|parent| parent as usize);
        }

        found
    }

    /// The conditionals around the region a fact's guard names, **innermost first**.
    ///
    /// The same answer as [`SummaryGuards::conditions_at`] for the region that guard was assigned from — and the
    /// walk is the *point*: the nesting is already recorded (each region names its parent), so this costs one
    /// step per level of nesting instead of a search over every conditional in the file. A file with two hundred
    /// conditionals would otherwise pay for all of them on every include it has, in every query that walks it.
    ///
    /// The file's own guard is left out: it is not a condition — see [`SummaryGuards::own_guard`].
    pub fn conditions_of(&self, region: u32) -> Vec<ConditionAt> {
        // **It allocates a `Vec` on every call, and it stays that way because the measurement said
        // not to bother.** `visibility_of` calls this once per guard — nine million times in an
        // index of a real project — so the allocation looked like the cost. A counter said
        // otherwise: nine million calls producing 37 M conditions, **100-300 ns each**, about two
        // seconds in total. The cost was in what the conditions are then used for, not in making
        // the list.
        let mut found = Vec::new();
        let mut current = Some(region);

        while let Some(index) = current {
            let Some(span) = self.span_of(index) else {
                break;
            };

            if Some(index) != self.own_guard {
                found.push(ConditionAt {
                    region: index,
                    condition_at: span.start_offset,
                });
            }

            current = self
                .conditionals
                .get(index as usize)
                .and_then(|conditional| conditional.parent);
        }

        found
    }

    /// The region a fact's guard names, as the preprocessor's own value, with the branch **in force at
    /// `offset`** as its `active_branch`.
    ///
    /// `None` when the index names no region, which a summary whose guards were written by another producer can
    /// have. The caller evaluates the returned region against the macros in force where the *condition* was
    /// written — [`SummaryGuards::conditions_at`] says where that is.
    pub fn region_at(&self, region: u32, offset: usize) -> Option<Region> {
        let conditional = self.conditionals.get(region as usize)?;

        // **The branches are built once per region, not once per question.** `GuardBranch` holds a condition as
        // *text*, so building them is a lex per branch — and this used to do it on every call, once per condition
        // inside `visibility_of`'s loop. See the note on [`ConditionalRegion::decoded`].
        //
        // Cloned rather than borrowed because `Region` is owned and `Region::visibility` takes `&self`: the clone is
        // a `Vec<Branch>` of tokens that are now in hand, where the old path re-lexed the text to produce those same
        // tokens every time. **The `Branch` caches are cloned with their values**, so a parse kept by
        // `an_expression_holds` is still there on the next question about this region instead of being dropped at
        // the end of the guard that made it.
        let decoded = conditional.decoded.get_or_init(|| {
            conditional
                .branches
                .iter()
                .map(GuardBranch::as_branch)
                .collect()
        });

        Some(Region {
            branches: decoded.clone(),
            active_branch: conditional.branch_at(offset)?,
        })
    }

    /// **Does the file's own include guard let its body be read at all?**
    ///
    /// The facts inside the guard are stored as `Unconditional` (`deguard_the_files_own_guard`), because a fact
    /// inside `#ifndef X / #define X` is as visible as one written outside every `#if` — *once the file is read*. A
    /// fold that composes the file's directives has to know whether it is read at all: the second `#include` of a
    /// guarded header contributes nothing, and applying its `#define X` a second time would produce a different
    /// environment for the same text (measured: the guard fixture's two inclusions hashed differently before this).
    ///
    /// `Some(true)` when there is no guard or its opener holds, `Some(false)` when the opener does not, `None` when
    /// the opener cannot be decided from the table.
    pub fn own_guard_holds<M: crate::MacroValues>(&self, macros: &M) -> Option<bool> {
        let Some(own) = self.own_guard else {
            return Some(true);
        };
        let conditional = self.conditionals.get(own as usize)?;
        let decoded = conditional.decoded.get_or_init(|| {
            conditional
                .branches
                .iter()
                .map(GuardBranch::as_branch)
                .collect()
        });
        decoded.first()?.holds(macros)
    }
    /// The span of a region's condition, when the index names one.
    pub fn span_of(&self, region: u32) -> Option<cpp_parser::SourceRange> {
        self.regions.get(region as usize).copied()
    }

    /// Was the code the guard names compiled, given the macros in force at each condition?
    ///
    /// `macros_at` is asked for a table **per condition**, and takes that condition's own offset — not
    /// `offset`. That is not a detail: a region's condition is decided where it is written, and the tokens that
    /// matter are the ones in force there. `#ifndef NAME` whose own body then writes `#define NAME` is the shape
    /// that makes the difference, and reading the condition at the *fact's* offset would decide it the other way
    /// round — for every include guard and every `#ifndef X / #define X` block in the corpus.
    ///
    /// The rule over the chain of enclosing regions is [`crate::Guard::visibility`]'s: one region known not to be
    /// taken makes the code `Inactive` whatever the others say, one that cannot be decided makes it `Unknown`, and
    /// only when every one of them is taken is it `Active`. A table that cannot speak about a name answers
    /// [`Lookup::Unanswered`](crate::Lookup), which the evaluator turns into `Unknown` — so a condition this
    /// index has no evidence about costs an answer, never a wrong one.
    pub fn visibility_of<M: crate::MacroValues>(
        &self,
        guard: FactGuard,
        offset: usize,
        macros_at: impl Fn(usize) -> M,
    ) -> Visibility {
        // The fast path, and it is the common one: code outside every conditional is compiled without anything
        // being evaluated, and asking would cost a walk per include of every file a query touches.
        let FactGuard::Region(region) = guard else {
            return Visibility::Active;
        };

        let mut unknown = false;

        for at in self.conditions_of(region) {
            let Some(region) = self.region_at(at.region, offset) 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;
            };

            match region.visibility(&macros_at(at.condition_at)) {
                Some(true) => {}
                Some(false) => return Visibility::Inactive,
                None => unknown = true,
            }
        }

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

impl ConditionalRegion {
    /// Which branch's body holds `offset`.
    ///
    /// The last branch that starts at or before the position when no body contains it: the position can only be
    /// in the directives between two bodies (a fact's range starts after its directive, so this is the
    /// degenerate case of a zero-length body), and "the branch that was open there" is the reading
    /// [`crate::GuardStack`] itself takes — it makes the branch in force the last one it observed.
    ///
    /// `None` only for a region with no branches at all, which no walk produces and a foreign summary can.
    pub fn branch_at(&self, offset: usize) -> Option<usize> {
        if let Some(index) = self.branches.iter().position(|branch| {
            branch.body.start_offset <= offset && offset < branch.body.end_offset()
        }) {
            return Some(index);
        }

        self.branches
            .iter()
            .rposition(|branch| branch.body.start_offset <= offset)
            .or(if self.branches.is_empty() {
                None
            } else {
                Some(0)
            })
    }

    /// Is there an `#else`? Then one of the branches is taken whatever the conditions say.
    pub fn exhaustive(&self) -> bool {
        self.branches
            .iter()
            .any(|branch| branch.kind == crate::DirectiveKind::Else)
    }

    /// Does this region's body hold `offset`?
    fn contains(&self, offset: usize) -> bool {
        self.branches
            .iter()
            .any(|branch| branch.body.start_offset <= offset && offset < branch.body.end_offset())
    }
}

impl GuardBranch {
    /// This branch as the guard layer reads it: the same condition, with its text read back into tokens.
    ///
    /// `#ifdef NAME` becomes a branch whose *name* is set and whose tokens are empty, which is how
    /// [`crate::Branch::holds`] reads it — so the two layers cannot disagree about what `#ifdef` means, and
    /// neither can they about `#else` or about an expression.
    pub fn as_branch(&self) -> Branch {
        // `Branch::new` starts the two caches empty: this reads a branch back out of a cached summary, which stores
        // the condition's *text*, so there is nothing parsed yet to carry over.
        match self.kind {
            crate::DirectiveKind::Ifdef | crate::DirectiveKind::Ifndef => {
                Branch::new(self.kind, Vec::new(), self.condition.clone(), self.range)
            }
            _ => Branch::new(self.kind, self.tokens(), None, self.range),
        }
    }

    /// The stored condition, read back into tokens whose ranges point into the file they came from.
    ///
    /// The lexer rather than a split on whitespace, for the reason the reference query gives: this has to be the
    /// same reader that produced the tokens the condition was written as, and a second reader would disagree
    /// about `'` digit separators, about a suffix, and about a `//` comment ending a condition early.
    ///
    /// Ranges are shifted by the directive's own position, so a consumer that follows a token to the file lands
    /// in the right place. A text that does not lex at all is not an error: the evaluator reads what it can, and
    /// a condition that cannot be read is `Unknown` rather than wrong — the same answer the guard layer gives for
    /// a condition it cannot parse.
    fn tokens(&self) -> Vec<crate::Token> {
        let Some(text) = self.condition.as_deref() else {
            return Vec::new();
        };

        let mut errors = Vec::new();
        let mut lexer =
            cpp_parser::CppLexer::new(text, cpp_parser::LexerConfig::default(), &mut errors);

        let base = self.range.start_offset;
        lexer
            .tokenize()
            .into_iter()
            .filter(|token| !cpp_parser::is_trivia(token.kind))
            .map(|token| {
                crate::Token::new(
                    token.kind,
                    text.get(token.range.start_offset..token.range.end_offset())
                        .unwrap_or_default(),
                    cpp_parser::SourceRange::new(
                        base + token.range.start_offset,
                        token.range.length,
                    ),
                )
            })
            .collect()
    }
}

/// Everything the index remembers about one file.
///
/// [`FileSummary::is_empty`] is not a curiosity: an empty summary is what a file that failed to parse, or a header
/// with nothing but comments, produces — and a consumer that treats "no facts" as "no declarations exist" is making
/// a claim the index never made. See `Known` in [`crate::symbol`] for the vocabulary that keeps those apart.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileSummary {
    /// Where the file is, as the path it was read from.
    ///
    /// A path rather than a [`FileId`], and the reason is what survives a restart: a `FileId` is an index into a
    /// [`PathInterner`] that is built fresh every run, so an id written to disk means something different — or
    /// nothing at all — when it is read back. The path is also what a consumer needs anyway: a "go to
    /// definition" in another file opens it by name.
    ///
    /// [`FileId`]: crate::FileId
    /// [`PathInterner`]: crate::PathInterner
    pub path: std::path::PathBuf,
    /// What this summary was built from — see [`SummaryKey`]. Stored so that a loaded entry can be *checked*
    /// against the file it claims to describe rather than trusted because it was found.
    pub key: SummaryKey,
    pub declarations: Vec<DeclFact>,
    pub macros: Vec<MacroFact>,
    pub includes: Vec<IncludeFact>,
    pub guards: SummaryGuards,
    /// Where a **scope** in this file came out of a macro's replacement list — see [`MacroScopeReading`].
    ///
    /// Empty for the overwhelming majority of files, and empty is the ordinary answer rather than a failure: a file
    /// that writes its own braces has nothing to record here. It is stored because it is the one part of a summary
    /// whose evidence is in *another* file, and a consumer that can ask that file again must be able to.
    pub macro_readings: Vec<MacroScopeReading>,
    /// **Every identifier name this file mentions, as a Bloom filter** — what turns a references query from "read
    /// every file that can see the declaration" into "read the few that contain the name".
    ///
    /// # Why a filter and not the uses themselves
    ///
    /// `ProjectIndex::symbol_references` walks the declaring file and everything that transitively includes it, and
    /// for each one it **reads the whole file** before it can ask the cheap question (`text.contains`). The read is
    /// the cost an index removes, and the volume says what removing it costs
    /// (`examples/use_index_cost.rs`, 126 files of MSVC's standard library):
    ///
    /// ```text
    ///   identifier uses                                   299 143
    ///   every use as (name id, offset)                   2 478 456 bytes   13.4% of the summaries
    ///   this filter, 14 bits per distinct name per file    ~1%             and no offsets, names or order
    /// ```
    ///
    /// Both answer *"might this file use this name"*. The filter is two orders of magnitude smaller because it is
    /// allowed to be wrong in one direction — and it is: a **false positive** costs exactly what today's code costs
    /// for that file, one read and one `contains`, and nothing more, while a **false negative is impossible**. That
    /// asymmetry is what makes a filter the right shape here rather than an approximation of the right shape.
    ///
    /// **Empty means "no information" and is read that way** — a summary written before this field existed, or built
    /// by a caller that did not fill it, filters nothing rather than filtering everything out. See
    /// [`use_filter_might_contain`].
    pub use_filter: Vec<u8>,
    /// **What this file declares about modules** — see [`ModuleReading`], and `plan-units.md` §35 for why the
    /// visibility walk needs it *in* the summary rather than in a lookup beside it.
    pub modules: ModuleReading,
}

/// **The bits per distinct name** in a [`FileSummary::use_filter`].
///
/// Fourteen is the textbook optimum for three probes at a one-percent false-positive rate, and the rate matters
/// less than it looks — a false positive is one wasted read. What matters is the size, so the two bounds below keep
/// a two-name file from paying for hashes it cannot use and an enormous generated file from adding thirty kilobytes
/// to its own summary.
const USE_FILTER_BITS_PER_NAME: usize = 14;

/// The smallest filter worth writing: below this the probes cost more than the answer saves.
const USE_FILTER_MIN_BYTES: usize = 64;

/// The largest, so that one generated file cannot put a megabyte in the cache.
const USE_FILTER_MAX_BYTES: usize = 32 * 1024;

/// **Build the filter over the identifier names a file mentions.**
///
/// The names come from the **tree** and not from the text: a word inside a comment or a string literal is not a use
/// of it, and the lexer has already made that distinction — which is also why this is not a scan for word-shaped
/// substrings.
pub fn use_filter_of(root: &cpp_parser::CppSyntaxNode) -> Vec<u8> {
    use std::collections::HashSet;

    // **Owned, because a token's text borrows the token.** The names are the distinct identifiers of one file — a
    // few thousand at most, against the file's whole token stream — so the allocations are bounded by the answer
    // and not by the input, and the alternative is a second lifetime threaded through the builder for nothing.
    let mut names: HashSet<String> = HashSet::new();
    for element in root.descendants_with_tokens() {
        let Some(token) = element.as_token() else {
            continue;
        };
        if cpp_parser::CppTokenKind::from(token.kind()) != cpp_parser::CppTokenKind::Identifier {
            continue;
        }
        let name = token.text();
        if !name.is_empty() {
            names.insert(name.to_string());
        }
    }

    use_filter_of_names(names)
}

/// **The same filter over a file's own tokens** — the half [`use_filter_of`] cannot answer for a caller that has
/// tokens and no tree.
///
/// That caller is the one this whole file's second reading is about: a file is **tokenized** and **rendered**, and the
/// parser only ever sees the rendering ([`FileSummary::take_the_directives_of`]). The tree the filter would have come
/// from belongs to that rendering, whose dead branches are deleted — so a name used only inside an `#if` nobody takes
/// is a name the tree does not have while the file's text does, and [`use_filter_might_contain`]'s one guarantee is
/// that a `false` is *certain*. Asking the tokens keeps it: the token stream is the file's text, every branch of it.
pub fn use_filter_of_tokens(source: &str, tokens: &[cpp_parser::CppTokenData]) -> Vec<u8> {
    use std::collections::HashSet;

    let mut names: HashSet<&str> = HashSet::new();
    for token in tokens {
        if token.kind != cpp_parser::CppTokenKind::Identifier {
            continue;
        }
        let from = token.range.start_offset;
        if let Some(name) = source.get(from..from + token.range.length)
            && !name.is_empty()
        {
            names.insert(name);
        }
    }

    use_filter_of_names(names)
}

/// The filter itself, over a name set — one builder for both readings of a file.
fn use_filter_of_names<S: AsRef<str> + Eq + std::hash::Hash>(
    names: impl IntoIterator<Item = S>,
) -> Vec<u8> {
    use std::collections::HashSet;

    let names: HashSet<S> = names
        .into_iter()
        .filter(|name| !name.as_ref().is_empty())
        .collect();

    let bits = names
        .len()
        .saturating_mul(USE_FILTER_BITS_PER_NAME)
        .clamp(USE_FILTER_MIN_BYTES * 8, USE_FILTER_MAX_BYTES * 8);
    let mut filter = vec![0u8; bits.div_ceil(8)];

    for name in names {
        for probe in use_filter_probes(name.as_ref()) {
            let bit = probe as usize % bits;
            filter[bit / 8] |= 1 << (bit % 8);
        }
    }

    filter
}

/// **Might this file mention `name`?** — `true` when there is no filter to ask, which is the safe direction.
///
/// A `false` is certain: the filter was built from every identifier the file contains, so a name that is not in it
/// is a name not written there. A `true` means "read it and see", which is all a caller needs to skip the files that
/// cannot possibly contain the name. See [`FileSummary::use_filter`].
pub fn use_filter_might_contain(filter: &[u8], name: &str) -> bool {
    if filter.is_empty() {
        return true;
    }
    let bits = filter.len() * 8;
    use_filter_probes(name).iter().all(|probe| {
        let bit = *probe as usize % bits;
        filter[bit / 8] & (1 << (bit % 8)) != 0
    })
}

/// **Three bit positions for a name**, from two FNV-1a hashes — the standard double-hashing trick, so that one pass
/// over the bytes yields every probe.
fn use_filter_probes(name: &str) -> [u64; 3] {
    const OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
    const PRIME: u64 = 0x0000_0100_0000_01b3;

    let mut first = OFFSET;
    for byte in name.as_bytes() {
        first ^= u64::from(*byte);
        first = first.wrapping_mul(PRIME);
    }
    // A second, independent-looking hash; it only has to be **odd**, which makes the step coprime with any power of
    // two and is what keeps three probes from collapsing onto one bit.
    let mut second = OFFSET ^ 0x9e37_79b9_7f4a_7c15;
    for byte in name.as_bytes().iter().rev() {
        second ^= u64::from(*byte);
        second = second.wrapping_mul(PRIME);
    }
    let step = second | 1;

    [
        first,
        first.wrapping_add(step),
        first.wrapping_add(step.wrapping_mul(2)),
    ]
}

impl FileSummary {
    /// A summary with no facts, for the file at `path`, built under `key`.
    pub fn empty(path: impl Into<std::path::PathBuf>, key: SummaryKey) -> Self {
        FileSummary {
            path: path.into(),
            key,
            declarations: Vec::new(),
            macros: Vec::new(),
            includes: Vec::new(),
            guards: SummaryGuards::default(),
            macro_readings: Vec::new(),
            // **Empty, and that is a real answer**: no filter is "ask the file", not "the file uses nothing".
            use_filter: Vec::new(),
            modules: ModuleReading::default(),
        }
    }

    pub fn is_empty(&self) -> bool {
        self.declarations.is_empty() && self.macros.is_empty() && self.includes.is_empty()
    }

    /// Put a fact's guard into the file's region list, returning the index to store in the fact.
    ///
    /// The single entry point for guarding a fact, so that the "many facts, one region" sharing cannot be forgotten
    /// at one call site out of five — the same reason the parser's rules share their predicates.
    pub fn intern_region(&mut self, region: Option<cpp_parser::SourceRange>) -> FactGuard {
        let Some(range) = region else {
            return FactGuard::Unconditional;
        };
        match self.guards.regions.iter().position(|known| *known == range) {
            Some(index) => FactGuard::Region(index as u32),
            None => {
                self.guards.regions.push(range);
                FactGuard::Region((self.guards.regions.len() - 1) as u32)
            }
        }
    }

    /// **Complete a summary built from a rendering with the directives of the file's own text.**
    ///
    /// A file is read **twice**, and each reading answers a question the other cannot:
    ///
    /// ```text
    /// the text      lexed, not parsed     #define / #include / #if regions — what this file *directs*
    /// the rendering parsed                declarations, uses — what a compiler *reads* here
    /// ```
    ///
    /// `self` is the first of those to be *built* — it came from
    /// [`FileIndexer::index_rendering`](crate::FileIndexer::index_rendering) — and it is missing exactly the three
    /// fields only the text can answer, because **a rendering has no directives in it**: they were consumed producing
    /// it. `directed` is the same file's text read by the lexer and the directive scanner and by nothing else
    /// ([`FileIndexer::directive_summary`](crate::FileIndexer::directive_summary)), so no second parse is paid for.
    ///
    /// # Why this is not an optimization
    ///
    /// The three fields are what **every other file's cook reads out of this one**: a header's `#define`s are the
    /// bodies its includers expand, and its `#include`s are the edges the closure walks. A summary that has the
    /// rendering's declarations and an empty `macros` therefore does not describe a file that declares things — it
    /// describes a file whose macros have never been defined, and the next file's rendering comes out with
    /// `_STD_BEGIN` unexpanded and its declarations at file scope. Measured as a red test three times before this
    /// method existed: a summary built from a rendering alone made `std::Widget` answer `NotDeclaredHere`.
    ///
    /// # What is taken, and what is kept
    ///
    /// Taken: `macros`, `includes`, `guards`, and `use_filter`. The filter is the text's for a stated reason — a
    /// rendering has the dead branches deleted, so a name used only inside one would be a **false negative** of
    /// [`use_filter_might_contain`], whose contract is that a `false` is certain (see [`use_filter_of_tokens`]).
    ///
    /// Kept: `declarations` (the point of the exercise), `macro_readings` (where a scope came out of a replacement
    /// list — the rendering's answer, and its ranges are already the file's), and `modules` (the `import`s are still
    /// in the rendering, and [`FileIndexer::directive_summary`] cannot see them: it has no tree).
    ///
    /// Declarations keep their **own** guards, which a rendering's parse makes `Unconditional` — and that is the
    /// reading, not a shortcut: a declaration in a rendering is one the compiler compiles. A caller that hands this a
    /// directive-bearing summary gets its indices translated into the adopted region list rather than left pointing
    /// into a list that is gone.
    pub fn take_the_directives_of(&mut self, directed: FileSummary) {
        let authored = std::mem::take(&mut self.guards.regions);
        let mut directed = directed;
        let mut regions = std::mem::take(&mut directed.guards.regions);

        if !authored.is_empty() {
            for fact in &mut self.declarations {
                let FactGuard::Region(index) = fact.guard else {
                    continue;
                };
                let Some(range) = authored.get(index as usize).copied() else {
                    fact.guard = FactGuard::Unconditional;
                    continue;
                };
                fact.guard = match regions.iter().position(|known| *known == range) {
                    Some(index) => FactGuard::Region(index as u32),
                    None => {
                        regions.push(range);
                        FactGuard::Region((regions.len() - 1) as u32)
                    }
                };
            }
        }

        self.macros = directed.macros;
        self.includes = directed.includes;
        self.guards = directed.guards;
        self.guards.regions = regions;
        if !directed.use_filter.is_empty() {
            self.use_filter = directed.use_filter;
        }
        // The **key is the caller's**, and deliberately not touched here: this method has a rendering and a text and
        // no way to say which file they are of. `index_the_readings` sets it, where the file's own hash is at hand.
    }

    /// **Turn a summary built from a rendering back into a summary of the file.**
    ///
    /// A rendering's offsets are not file offsets — they are positions in text this crate spelled out — so a
    /// summary built by parsing one describes a file that does not exist. This is what makes it usable: every
    /// range it carries is answered for by [`crate::RenderedCooked::reported_span`], which is the place in the file a
    /// reader can act on (the invocation when a macro produced the text, the file's own span otherwise), and the
    /// facts whose ranges cannot be placed at all are **dropped and counted** rather than left pointing into a
    /// rendering.
    ///
    /// # What is in a rendering's summary
    ///
    /// Only declarations, and that is a property of what a rendering is: the directives are gone, so there are no
    /// macros, no includes and no conditional regions to place. The other fields are mapped anyway — the function
    /// is about the *type*, and a caller that hands it a summary from something directive-bearing should get
    /// answers for every range rather than silent rendering offsets in one field.
    ///
    /// Dropping is the honest answer for a fact whose range cannot be placed: an empty node covers no token, and a
    /// declaration the parser recovered out of nothing has nothing to point at. It is counted so that a caller can
    /// say how much of a reading it could use — see [`MapReport`].
    pub fn map_into_the_file(
        &mut self,
        rendered: &crate::preprocess::cooked::RenderedCooked,
    ) -> MapReport {
        let mut report = MapReport::default();
        let place = |range: cpp_parser::SourceRange, report: &mut MapReport| match rendered
            .reported_span(range)
        {
            Some(mapped) => {
                report.placed += 1;
                Some(mapped)
            }
            None => {
                report.dropped += 1;
                None
            }
        };

        self.declarations.retain_mut(|fact| {
            let (Some(range), Some(name_range)) = (
                place(fact.range, &mut report),
                place(fact.name_range, &mut report),
            ) else {
                // One of the two did not place, and a declaration is kept **whole or not at all**: half of it in
                // the file and half of it in a rendering is not a smaller answer, it is a wrong one.
                return false;
            };
            fact.range = range;
            fact.name_range = name_range;
            true
        });

        self.macros.retain_mut(|fact| {
            let Some(range) = place(fact.range, &mut report) else {
                return false;
            };
            fact.range = range;
            fact.body_range = fact.body_range.and_then(|body| place(body, &mut report));
            true
        });

        self.includes.retain_mut(|fact| {
            let Some(range) = place(fact.range, &mut report) else {
                return false;
            };
            fact.range = range;
            true
        });

        self.macro_readings.retain_mut(|reading| {
            let Some(range) = place(reading.range, &mut report) else {
                return false;
            };
            reading.range = range;
            true
        });

        // Regions are mapped **in place or not at all**: a fact's guard is an *index* into this list, so dropping
        // one would renumber the guards of every fact after it — a silently wrong summary rather than a smaller
        // one. A rendering has none of them (see the note), which is why this can be this simple.
        for region in &mut self.guards.regions {
            if let Some(mapped) = place(*region, &mut report) {
                *region = mapped;
            }
        }

        report
    }
}

/// How a summary's ranges mapped back into a file — see [`FileSummary::map_into_the_file`].
///
/// Both numbers count **ranges**, which is what the mapping answers for: a fact with two ranges contributes two
/// answers, and a fact one of whose ranges fails is dropped whole — so [`MapReport::dropped`] is what was *lost*,
/// not what was kept.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct MapReport {
    /// Ranges that landed in the file.
    pub placed: usize,
    /// Ranges that landed nowhere, taking their facts with them.
    pub dropped: usize,
}

/// What indexing a **whole unit's** rendering produced, file by file — see
/// [`crate::FileIndexer::index_unit_rendering`].
///
/// One parse, many files: the facts are grouped by the file each declaration was written in, so a caller files
/// them under their own paths rather than under the unit's root.
#[derive(Debug, Default, Clone)]
pub struct IndexedUnit {
    /// Each file's share, in the order the unit's frames hold them — which is include order.
    pub files: Vec<(std::path::PathBuf, crate::CookedFile)>,
    /// Facts and errors that could not be placed in any file.
    pub unplaced: usize,
    /// How many tokens the unit's stream has.
    pub tokens: usize,
    /// How many files the stream actually carries a token from.
    pub files_with_tokens: usize,
    /// How many files the walk reached that the caller had no text for.
    pub missing: usize,
    /// Files whose own text does not balance its braces — see [`RenderedUnit::unbalanced`].
    ///
    /// A **report**, not a filter: the files named here contributed their tokens to the stream like every other
    /// file, and the crossed pairing their imbalance caused was repaired by this very function. A reader sees the
    /// list to know which files to doubt, which is the plan's rule 3 — an uncertain answer that names what it is
    /// uncertain about beats both a silent wrong answer and a refusal to answer.
    pub unbalanced: Vec<std::path::PathBuf>,
    /// The stream's own brace balance — see [`RenderedUnit::braces`].
    pub braces: i64,
    /// Files **repaired**: the parser paired a brace of theirs with a brace in another file, so that one pairing was
    /// neutralised in the stream (`RenderedUnit::neutralized`) and the file was parsed on its own as well — see
    /// [`crate::FileIndexer::index_unit_rendering`]. What they declare is filed from the program; what their parse
    /// got wrong stays inside them.
    ///
    /// This used to be called *quarantine*, and the name was the mechanism: the file's tokens left the program
    /// entirely ([`RenderedUnit::without`]), so a file that leaked one brace lost every declaration in it. The plan's
    /// **How many braces were given up to repair a crossing, and none of them is still in the stream.**
    ///
    /// Counted as the offsets **actually neutralised** — not as the crossings a parse reported, which is a different
    /// number for a reason worth knowing: a parse that reports a crossing out of braces already given up has found
    /// nothing new to fix, and counting it would report a repair that did not happen. Only the new ones count.
    ///
    /// It is not a gate, and that is deliberate: a non-zero value here means the parse had to repair something, so
    /// the declarations nearest those braces are the ones to doubt — not a reason to file nothing. Compare
    /// [`RenderedUnit::unbalanced`], which records a file whose braces do not balance before the parse even runs;
    /// this is the after-the-parse half of the same policy, and it is the one that must not scale up to the whole
    /// **Crossings the repair could not cure**, one per crossing left in the final parse.
    ///
    /// The honest counterpart of [`IndexedUnit::repaired`], and it exists because the two can differ: a parser that
    /// reports a crossing out of braces that are *already* markers has nothing left for the repair to give up, so the
    /// loop stops and reports the remainder rather than spinning out its rounds pretending to fix it.
    ///
    /// Zero in every case measured, and non-zero is **not** a reason to refuse the reading — it is the same
    /// all-or-nothing gate this whole milestone removed, one level down. What it means is that the files named in
    /// [`IndexedUnit::quarantined`] are the ones whose scopes the program's parse got wrong, and that their own
    /// Errors the parse of the stream reported.
    ///
    /// Reported per file (each lands in the file it is in) and never the gate — see `repaired`. It was the gate
    /// while the only defence against one file's unclosed scope was to refuse the whole program.
    ///
    /// *The original account, kept because it is the measurement:*
    ///
    /// **This was the gate the unit reading needed**, and `braces` is not: measured on a real project the stream is
    /// *lexically* balanced (`braces: 0`) while `CodeAnalysis/sourceannotations.h` — the one file a census has never
    /// read cleanly, registered as "`/analyze`-only syntax, not a gap" — still leaves its `namespace vc_attributes`
    /// open **syntactically**, so every file spliced after it reads as `vc_attributes::std`. Equal counts of `{` and
    /// `}` do not make the parser pair them the way the file meant; only the parse does.
    pub errors: usize,
}

/// What reading one translation unit as a program produced — see [`crate::Session::read_the_unit`].
///
/// A report rather than the facts themselves: the facts went into the index (that is the point of the call), and
/// what a caller wants back is whether the reading happened and how much of the program it covered.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnitReading {
    /// The unit's root, in the index's own spelling.
    pub root: std::path::PathBuf,
    /// How many files the reading was filed under.
    pub files: usize,
    /// Declarations placed in a file.
    pub declared: usize,
    /// Tokens in the unit's stream.
    pub tokens: usize,
    /// Files the stream carries a token from — not `files`, because a file whose whole body is inside a branch
    /// nobody takes contributes nothing, and counting it as read is the mistake §7 records.
    pub files_with_tokens: usize,
    /// Files the walk reached that this session had no text for.
    pub missing: usize,
    /// Facts and errors that could not be placed in any file.
    pub unplaced: usize,
    /// Files whose own text does not balance its braces — see [`RenderedUnit::unbalanced`]. Named rather than
    /// counted: the file is the thing to look at.
    ///
    /// Being named here is **not** a claim that the file was skipped. Its declarations are in the index, filed at the
    /// scope its own text gives them; what the name says is that a brace of it could not be paired inside it, and
    /// that the pairing it got instead had to be given up.
    pub unbalanced: Vec<std::path::PathBuf>,
    /// The stream's own brace balance — see [`RenderedUnit::braces`].
    pub braces: i64,
    /// Errors the parse of the **program** reported, wherever they are — each is also filed against its own file.
    pub errors: usize,
}

/// One thing the parse of a **rendering** found, said in the file's own coordinates.
///
/// A rendering's offsets are not file offsets, so an error the parser reports against one describes text that does
/// not exist. This is that error after [`crate::RenderedCooked::reported_span`] has answered for it: a position a
/// reader can act on — the invocation when a macro produced the text, the file's own span otherwise.
///
/// It is a type of its own rather than the parser's [`cpp_parser::CppParseError`] with a shifted range, because the
/// message and the range are no longer the same claim: the parser said "here, in this text", and this says "there,
/// in that file" — the two have different owners, and a consumer that published the first as if it were the second
/// would point at a line inside a `#define` three headers up.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CookedDiagnostic {
    /// Where to point the reader, **in the file** the rendering was cooked from.
    pub range: cpp_parser::SourceRange,
    pub message: String,
}

/// What indexing one file's rendering produced — see [`crate::FileIndexer::index_rendering`].
#[derive(Debug, Clone)]
pub struct IndexedRendering {
    /// The file's facts **as a compiler reads them**, with every range mapped back into the file.
    pub summary: FileSummary,
    /// **The rendering this was read from** — the macro-expanded text, kept rather than dropped.
    ///
    /// It used to be thrown away: `cook` rendered a file, parsed the rendering, kept the declarations, and discarded
    /// the text. That is why a query could not find one — [`crate::Session::view`] answers from a rendering or not at
    /// all, so a file whose rendering had just been built and parsed was still answered `None` on the next request,
    /// and the request after that, until something happened to ask for it again through a path that remembered.
    ///
    /// Keeping it costs one `Arc` clone: the renderer already holds the text in an `Arc`, so this is a pointer and
    /// not a copy of a header. It is what makes "the reading exists" and "the reading is available" the same state.
    pub rendered: std::sync::Arc<crate::preprocess::cooked::RenderedCooked>,
    /// How the mapping went: ranges placed, ranges that landed nowhere.
    pub mapped: MapReport,
    /// The parse errors of the rendering, placed in the file.
    pub diagnostics: Vec<CookedDiagnostic>,
    /// Errors the map could not place **in this file** — a grammar error inside another file's macro body, or in a
    /// token whose spelling exists nowhere (a paste). Counted rather than dropped in silence: the rendering is not
    /// clean, and a consumer that reports "no errors" while this is non-zero is claiming more than it knows.
    pub unplaced: usize,
}

impl DeclKind {
    /// The index's vocabulary for a binding, which is deliberately **coarser** than the analysis layer's.
    ///
    /// `parser_symbols` maps the same source vocabulary onto `cpp_parser::SymbolKind`, and that is not a duplicate
    /// of this: the parser is asked "which reading should I take" (five answers, in its own enum), while the index
    /// stores "what kind of thing is written here" and has to keep that answer readable by consumers written before
    /// the finer kinds existed. Two questions, two vocabularies — the same reason `IncludeForm` is re-used rather
    /// than re-declared.
    pub fn from_binding_kind(kind: crate::BindingKind) -> DeclKind {
        use crate::BindingKind as B;
        match kind {
            B::Class | B::Enum | B::Alias | B::Typedef | B::TemplateParameter => DeclKind::Type,
            B::Function
            | B::Constructor
            | B::Destructor
            | B::ConversionFunction
            | B::OperatorFunction
            | B::LiteralOperator => DeclKind::Function,
            B::Variable | B::Enumerator => DeclKind::Variable,
            B::Namespace => DeclKind::Namespace,
            // A label, a `using`, or something the walker could not classify: the declaration is real and worth a
            // "go to definition", so it is stored as `Other` rather than dropped.
            _ => DeclKind::Other,
        }
    }
}

// Declaration facts are built by [`crate::declarations::build_facts`], in the `sema` layer rather than here, and
// the reason is worth knowing before looking for it: a fact has to say which `#if` it was written in, which means
// the walk needs the *preprocessor* state as well as the scopes — and this module is the shape of what gets
// stored, not a place that knows about directives. There was a `build_declarations` here that took only a scope
// tree and filled every guard with `Unconditional`; it was deleted rather than kept, because a function whose
// contract is "the guards are wrong" is one a caller reaches for by accident.

/// **The two positional questions the renderer asks** — see
/// [`cpp_toolchain::preprocess::cooked::MacroEnvironment`].
///
/// This is the whole seam between the walk's timeline and a rendering: the renderer owns the file's text and the
/// expansion, the environment owns where the file sits and which definitions are in force there, and neither needs the
/// other's types. `MacroView` is two words — the unit and a frame — so the answers are the same comparisons they were
/// when the renderer took the view by value.
impl cpp_toolchain::preprocess::cooked::MacroEnvironment for MacroView<'_> {
    fn visible_body_in_force(&self, name: &str) -> Option<u32> {
        MacroView::visible_body_in_force(self, name)
    }

    fn visible_binding(&self, name: &str) -> Option<(usize, u32)> {
        MacroView::visible_binding(self, name)
    }
}

/// **A unit's definitions, answered by slot** — see
/// [`cpp_toolchain::preprocess::cooked::UnitDefinitionsView`].
///
/// Lazy on both sides: the table lexes a replacement list the first time a rendering meets it, and a slot nobody asks
/// for is never read. `of` is the reader; this trait is the door the renderer is allowed to knock on.
impl cpp_toolchain::preprocess::cooked::UnitDefinitionsView for UnitDefinitions<'_> {
    fn definition_of(&self, index: u32) -> Option<&std::sync::Arc<crate::macros::MacroDef>> {
        self.of(index)
    }
}

#[cfg(test)]
mod tests {

    /// **A destructor is recognised by the tilde**, which is the only spelling it has.
    #[test]
    fn a_destructor_is_a_name_that_starts_with_a_tilde() {
        assert!(super::is_a_destructor_name("~Widget"));
        assert!(
            super::is_a_destructor_name("~"),
            "the spelling is the test, not the identifier"
        );
        assert!(!super::is_a_destructor_name("Widget"));
        assert!(
            !super::is_a_destructor_name("operator~"),
            "a bitwise-not overload is not a destructor"
        );
    }

    /// **An operator is `operator` followed by a symbol or a space**, not by another identifier character.
    #[test]
    fn an_operator_is_recognised_without_hiding_a_name_that_begins_with_the_same_letters() {
        for operator in [
            "operator+",
            "operator()",
            "operator[]",
            "operator=",
            "operator<=>",
            "operator bool",
            "operator new",
            "operator Widget",
        ] {
            assert!(
                super::is_an_operator_name(operator),
                "`{operator}` is an operator"
            );
        }
        for plain in ["grow", "operate", "operator_helper", "operators", "Widget"] {
            assert!(
                !super::is_an_operator_name(plain),
                "`{plain}` is an ordinary function, not an operator"
            );
        }
    }
}