cpp_code_analysis 0.1.4

The analysis layer of cpp_ls: the preprocessor, symbol scopes, type inference and the semantic checks.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
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
use super::{OpenDocuments, Session, SessionFiles, queue_key};
use crate::file::coordinates::ReadingOffset;
use crate::file::paths::{DiskFiles, FileProvider, MemoryFiles};
use crate::include::config::{CommandLineMacro, CompilerConfig};
use crate::include::toolchain::{Toolchain, ToolchainSource};
use crate::index::watch::{FileEvent, WatchFilter};
use crate::index::{Priority, StepOutcome};
use crate::symbol::Known;
use std::path::{Path, PathBuf};

/// A project in memory: the files, the buffers in front of them, and the providers that join the two.
///
/// The fixture keeps the providers and hands each session a **clone**, which is what a caller outside a test
/// does too — a provider is a handle, so the fixture's copy and the session's copy read the same files, and a
/// test can go on looking at what the analysis read while the session owns its own chain.
struct Memory<'a> {
    files: &'a MemoryFiles,
    documents: OpenDocuments,
    providers: SessionFiles<MemoryFiles>,
    root: PathBuf,
}

impl<'a> Memory<'a> {
    fn new(name: &str, files: &'a MemoryFiles) -> Self {
        let root = std::env::temp_dir().join("cppls-session-tests").join(name);
        let _ = std::fs::remove_dir_all(&root);

        let documents = OpenDocuments::new();
        let providers = SessionFiles::new(documents.clone(), files.clone());

        Memory {
            files,
            documents,
            providers,
            root,
        }
    }

    fn session(&self) -> Session<MemoryFiles> {
        self.session_with(CompilerConfig::default())
    }

    /// A session over the same files, with the configuration the caller states — how a test reads a **CUDA** project
    /// (`CompilerConfig::with_cuda`), or one for a particular compiler.
    fn session_with(&self, config: CompilerConfig) -> Session<MemoryFiles> {
        Session::with_config(
            &self.root,
            self.providers.clone(),
            WatchFilter::new(&self.root),
            config,
        )
    }

    /// The text the analysis would read for a path — the buffer if there is one.
    fn text(&self, path: &str) -> Option<String> {
        self.documents
            .text(path)
            .or_else(|| self.files.read(Path::new(path)))
    }
}

impl Drop for Memory<'_> {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.root);
    }
}

/// The paths of a run of steps, for an assertion about the order rather than about the work.
fn paths(steps: &[crate::index::Step]) -> Vec<String> {
    steps
        .iter()
        .map(|step| step.path.to_string_lossy().replace('\\', "/"))
        .collect()
}

// -------------------------------------------------------------------------------------------
// The buffer is the text
// -------------------------------------------------------------------------------------------

/// **A summary that describes a *rendering* is not left in the cache for the next session.**
///
/// `api.h` declares `Live` one way when `FROM_THE_SOURCE` is defined and another when it is not, so the file read
/// **inside `main.cpp`'s program** is not the file read **on its own**. The cache key is the file's text plus the
/// compilation's context, and a rendering is a function of the text *and of the environment at the point the file was
/// included* — so a rendering-derived summary written under that key is a row which says something the next session
/// has no way to ask for, and a session that reads it answers another translation unit's reading.
///
/// Measured before this rule: the same project indexed twice answered **43 238** and **43 483** declarations in one
/// closure (`tests/unit_read_probe.rs`), and 36 name answers in both — a small enough difference to look like noise,
/// which is why it went unexplained for a round.
#[test]
fn a_rendering_is_not_left_in_the_cache_for_the_next_session() {
    let api = "#ifdef FROM_THE_SOURCE\nstruct Live { int a; };\n#else\nstruct Live { long b; };\n#endif\n";
    let main = "#define FROM_THE_SOURCE 1\n#include \"api.h\"\nLive live;\n";
    let files = MemoryFiles::new()
        .with_file("/p/api.h", api)
        .with_file("/p/main.cpp", main);
    let fixture = Memory::new("a-rendering-is-not-cached", &files);

    // **The run that renders**: `main.cpp`'s program defines the macro, so `api.h`'s reading there is the `int`
    // branch and the summary built for it is that rendering.
    {
        let mut session = fixture.session();
        session.did_open("/p/main.cpp", main);
        session.index_everything();
        let reading = session
            .read_a_looked_at_unit()
            .expect("the program is read");
        assert!(reading.files >= 2, "two files: {reading:?}");
        assert!(
            session
                .index()
                .cooked_declarations(Path::new("/p/api.h"))
                .is_some_and(|facts| facts.iter().any(|fact| fact.name == "Live")),
            "the program's reading of the header is in this session"
        );
    }

    // **The next session knows nothing about that program.** `api.h` read on its own takes the `#else` branch, so
    // that — and only that — is what its summary may say.
    let mut session = fixture.session();
    session.add_project_files([std::path::PathBuf::from("/p/api.h")]);
    session.index_everything();
    let summary = session
        .index()
        .summary(Path::new("/p/api.h"))
        .expect("the header is read")
        .clone();
    let live: Vec<_> = summary
        .declarations
        .iter()
        .filter(|fact| fact.name == "Live")
        .collect();
    assert_eq!(
        live.len(),
        1,
        "the file declares `Live` once when it is read on its own: {live:?}"
    );
    assert_eq!(
        live[0].range.start_offset,
        api.find("struct Live { long b; }").expect("the fixture"),
        "and it is the branch that file has when nothing defines `FROM_THE_SOURCE`"
    );
}
/// **A declaration only a macro makes becomes one this session answers for**, once its queue drains.
///
/// `DECLARE_HANDLE(HWND)` declares `HWND__` and `HWND` to a compiler and *nothing* to a reader of the file's own
/// text: the declaration is inside the macro's replacement list, and the invocation is not a declaration. So the
/// index has no `HWND__` before the file is cooked and has one after — which is the whole reason the reading
/// exists.
///
/// (The other half of what cooking buys — the *scope* a namespace-opening macro puts a declaration in — is
/// already handled by the raw reading when the indexer is given the closure's macro bodies: `BEGIN_NS` is
/// `namespace ns {` to the parser and a declaration inside it is scoped correctly. That is the two-hop reading of
/// a macro-shaped scope and of a body written in another file, and it is why this test is about a declaration
/// the file does not write at all rather than about one it writes.)
#[test]
fn the_sharing_cache_survives_a_restart() {
    let handle = "#define DECLARE_HANDLE(name) struct name##__ { int unused; };\n";
    let source = "#include \"handle.h\"\nDECLARE_HANDLE(HWND);\n";
    let files = MemoryFiles::new()
        .with_file("/p/handle.h", handle)
        .with_file("/p/api.h", source);
    let fixture = Memory::new("the-sharing-cache-survives-a-restart", &files);

    // **The run that fills it.**
    let written = {
        let mut session = fixture.session();
        session.did_open("/p/api.h", source);
        session.index_everything();
        session
            .save_the_sharing()
            .expect("the cache directory is the fixture's")
    };
    assert!(
        written > 0,
        "a run that walked files must have something to write"
    );

    // **A restart**: the memory is empty, the disk is not.
    // A restart: the store a session opens has its own table, empty.
    let empty = fixture.session();
    assert_eq!(
        empty.walk_contributions_held(),
        0,
        "a new store holds nothing"
    );

    let session = fixture.session();
    let restored = session.load_the_sharing();
    assert_eq!(restored, written, "what was written is what is read back");
    assert_eq!(
        session.walk_contributions_held(),
        restored,
        "and it is in the cache the walk consults, not merely counted"
    );
}

#[test]
fn a_declaration_only_a_macro_makes_is_found_once_the_session_has_cooked_the_file() {
    let handle = "#define DECLARE_HANDLE(name) struct name##__ { int unused; }; \
                      typedef struct name##__ *name\n";
    let source = "#include \"handle.h\"\nDECLARE_HANDLE(HWND);\n";
    let files = MemoryFiles::new()
        .with_file("/p/handle.h", handle)
        .with_file("/p/api.h", source);
    let fixture = Memory::new("cooked-reading-is-indexed", &files);
    let mut session = fixture.session();

    session.did_open("/p/api.h", source);

    // **One step**: `api.h` is read and its include is queued, so the queue is *not* empty — and a file whose
    // includes have not been read has an environment that is not complete, which is why nothing is cooked yet.
    session.advance(1);
    let before = session.index().definition("HWND__", Path::new("/p/api.h"));
    assert!(
        matches!(before, Known::Unknown(_)),
        "the file's own text does not declare what the macro declares: {before:?}"
    );
    assert!(
        session
            .index()
            .cooked_declarations(Path::new("/p/api.h"))
            .is_none(),
        "and nothing has cooked it yet"
    );

    // **Drain**: the queue emptying is the moment a file's environment is complete, and that is where the
    // session cooks the files a reader is looking at. No caller asked for this — it is the indexing loop's own
    // last step.
    session.index_everything();

    let after = session.index().definition("HWND__", Path::new("/p/api.h"));
    let Known::Yes(found) = after else {
        panic!("the cooked reading declares it: {after:?}");
    };
    assert_eq!(found.file, Path::new("/p/api.h"));
    let at = found.fact.range;
    let written = &source[at.start_offset..at.end_offset()];
    assert!(
        written.contains("DECLARE_HANDLE"),
        "the declaration is reported at the invocation: {written:?}"
    );

    // What the cook reported about itself, asked for explicitly so the numbers are part of the test: the file
    // was already cooked once by the drain, and cooking it again reads the same thing.
    let cooked = session.cook_the_open_files();
    assert_eq!(cooked.len(), 1, "api.h is the open file");
    let (path, reading) = &cooked[0];
    assert_eq!(path, Path::new("/p/api.h"));
    assert!(
        reading.declarations >= 2,
        "the struct, its member and the typedef are declarations here: {reading:?}"
    );
    assert!(
        reading.only_after_expansion >= 2,
        "`HWND__` and `HWND` exist only after expansion: {reading:?}"
    );
    assert_eq!(reading.mapped.dropped, 0, "every range landed in the file");
}

/// **Opening a file reads the files it includes the way a compiler reads them too.**
///
/// A name used in the file the user is editing is declared in a header — often one they never open — and the
/// answer comes from **that** file's reading. So the closure is what gets cooked, not the one file: here
/// `main.cpp` is open, `api.h` is not, and the declaration only exists because `api.h` was read as a compiler
/// reads it. Without the closure marking the index would have the raw reading of `api.h` — which cannot see
/// what `DECLARE_HANDLE` declares at all.
///
/// **The bound is one level of includes, and a unit read moves it** — see
/// [`a_unit_read_reads_the_whole_program_once`] for what the session does when a caller asks for the program
/// rather than for one file, and why that is not wired into the pump yet.
#[test]
fn a_header_the_user_never_opened_is_cooked_when_a_request_names_it() {
    let handle = "#include \"deep.h\"\n#define DECLARE_HANDLE(name) struct name##__ { int unused; }; \
                      typedef struct name##__ *name\n";
    let api = "#include \"handle.h\"\nDECLARE_HANDLE(HWND);\n";
    let main = "#include \"api.h\"\nHWND h;\n";
    let files = MemoryFiles::new()
        .with_file("/p/deep.h", "#define DEEP 1\n")
        .with_file("/p/handle.h", handle)
        .with_file("/p/api.h", api)
        .with_file("/p/main.cpp", main);
    let fixture = Memory::new("a-named-file-is-cooked", &files);
    let mut session = fixture.session();

    session.did_open("/p/main.cpp", main);
    session.index_everything();

    // **The open file, and the files its own text names.** `api.h` is one of them, so the declaration the macro
    // writes in it is `api.h`'s declaration and a question about `HWND` is answered with a jump into it — the
    // capability that the closure used to buy, bought for the price of one direct include instead of 138 files.
    let after = session
        .index()
        .definition("HWND__", Path::new("/p/main.cpp"));
    let Known::Yes(found) = after else {
        panic!("`api.h`'s cooked reading declares it: {after:?}");
    };
    assert_eq!(
        found.file,
        Path::new("/p/api.h"),
        "the file that invoked the macro, which nobody opened"
    );

    // **And one level further, which is the bound** — `handle.h` is a nested include of a direct one, and
    // `want_the_closure_cooked` reaches it deliberately: [`COOK_ONE_LEVEL_FURTHER`] exists because MSVC's
    // `<string>` is a thin wrapper over `<xstring>`, and `std::string` lives in the *second* level, so a policy
    // that stopped at the direct includes answered `std::string` with nothing. Cooking is a render and an index
    // per file, so the level is bounded at sixty-four rather than taken to the closure — measured on a real
    // project, the closure was 138 files and **11.7 s of every startup**, and the direct includes are four.
    assert!(
        session
            .index()
            .cooked_declarations(Path::new("/p/handle.h"))
            .is_some(),
        "the level under a direct include is where the library keeps what a reader asks for"
    );

    // **And one level more than that.** `deep.h` is the third level down, which
    // [`COOK_TWO_LEVELS_FURTHER`] reaches: the class a header *uses* is often one `#include` below the header the
    // file writes — MSVC's `<string>` is a thin layer over `<xstring>`, where `basic_string` lives — and measured on
    // EmmyLuaCodeStyle, `std::string` answered `NotDeclaredHere` for a file whose header includes the header that
    // includes the one that declares it. Past that bound a file still has no reading until something names it.
    assert!(
        session
            .index()
            .cooked_declarations(Path::new("/p/deep.h"))
            .is_some(),
        "the third level is where a header's own class is declared, and it is cooked"
    );

    // A request naming it — the shell's `prepare` does this for every file a request is about — is what makes it.
    session.want_cooked_reading(Path::new("/p/handle.h"));
    session.index_everything();
    assert!(
        session
            .index()
            .cooked_declarations(Path::new("/p/handle.h"))
            .is_some(),
        "and then it has one"
    );
}

/// **A file whose text does not balance its braces is named, and its declarations are filed anyway.**
///
/// The hazard this pins was found by measurement, not by reading: 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 {` whose close is not in the text we rendered. Everything
/// spliced after it read as `vc_attributes::std`: `<cstdio>`'s declarations, `<string>`'s, the lot. A reader
/// asking about `std::size_t` was told the index had no such name while the file in front of them declared it.
///
/// # What this used to assert, and why it was the wrong shape
///
/// It used to assert that such a file's text was **left out of the stream** — the plan's gate ①, one of the two
/// all-or-nothing gates §2 names. That throws away every declaration in the file to protect the ones after it,
/// which is §4 rule 1's *"任何一层都不允许因为'不确定'而放弃已经确定的答案"* broken in the same way the
/// `crossings == 0` gate broke it one layer up.
///
/// The text now goes in, and the crossed pairing it creates is repaired like every other crossed pairing: the
/// `{` this file opened is paired with a `}` in another file, **that pair** is neutralised, and both files are
/// read on their own as well. So the assertions here are the two that matter and they pull in opposite
/// directions, which is what makes them worth having: the file after the unbalanced one is still scoped by its
/// own namespace, **and** the unbalanced file's own declaration is in the index.
#[test]
fn a_file_that_does_not_balance_its_braces_is_named_and_still_read() {
    let files = MemoryFiles::new()
        // Opens a namespace and never closes it: what a `/analyze` header does, and what swallows a program.
        .with_file(
            "/p/broken.h",
            "namespace vc_attributes {\nstruct NotAClosure { int x; };\n",
        )
        .with_file(
            "/p/good.h",
            "namespace good {\nstruct Inside { int y; };\n}\n",
        )
        .with_file(
            "/p/main.cpp",
            "#include \"broken.h\"\n#include \"good.h\"\nInside i;\n",
        );
    let fixture = Memory::new("a-unit-that-does-not-balance", &files);
    let mut session = fixture.session();

    session.did_open(
        "/p/main.cpp",
        "#include \"broken.h\"\n#include \"good.h\"\nInside i;\n",
    );
    session.index_everything();

    let reading = session
        .read_the_unit(Path::new("/p/main.cpp"))
        .expect("the unit reads");

    assert_eq!(
        reading.unbalanced.len(),
        1,
        "one file does not balance: {reading:?}"
    );
    assert!(
        reading.unbalanced[0].ends_with("broken.h"),
        "and it is the one that opens a brace it never closes: {reading:?}"
    );

    // **And the file after it is not nested inside the scope `broken.h` left open.** `broken.h`'s unclosed
    // namespace ends at the end of `broken.h`, so `good.h`'s own namespace holds `Inside` and nothing else.
    //
    // This is the parser's `file_boundaries` rule, the same one
    // `a_file_that_does_not_balance_costs_nothing_but_a_name` asserts for a file whose braces do not balance at
    // all. Measured on 2026-06: **it does not hold here** — `good.h` comes out scoped `vc_attributes::good`, so
    // the namespace `broken.h` opened is still open across the boundary. The assertion is left as written
    // because it is the contract; the failure is real and is not a stale expectation.
    let inside = session
        .index()
        .cooked_declarations(Path::new("/p/good.h"))
        .expect("good.h is part of the program");
    let inside = inside
        .iter()
        .find(|fact| fact.name == "Inside")
        .expect("the class is declared there");
    assert_eq!(
        inside.scope.as_deref(),
        Some("good"),
        "a scope does not cross a file boundary, so `good.h` is scoped by its own namespace"
    );

    // **And the unbalanced file did not lose its own declarations.** This is the half gate ① could not give: the
    // file's struct is declared in it, and it is filed under the namespace the file itself opens.
    let broken = session
        .index()
        .cooked_declarations(Path::new("/p/broken.h"))
        .expect("the unbalanced file's own reading is filed too");
    let struct_fact = broken
        .iter()
        .find(|fact| fact.name == "NotAClosure")
        .expect("the struct is declared in the file that does not balance");
    assert_eq!(
        struct_fact.scope.as_deref(),
        Some("vc_attributes"),
        "and at the scope its own text gives it: {broken:?}"
    );
}

/// **MSVC's single-bracket attribute no longer leaks, and the fence is not what saves it.**
///
/// This test used to assert that `broken.h` was *quarantined*: its text balances its braces, the parser still
/// got it wrong — `REPEATABLE [source_annotation_attribute(1)] struct X { … };` read as an expression whose
/// lambda body never closes — and the fence took the file out of the program so that `good.h` could still be
/// read as itself. The reading was right and the file was not.
///
/// The parser now reads that shape (a decl-specifier sequence accepts a single-bracket attribute, see
/// [`cpp_parser`]'s `at_a_single_bracket_attribute`), so the assertion has to be the *stronger* one: nothing
/// is quarantined, because nothing leaked — and the declarations of the file that used to poison the program
/// are in the index under their own names.
///
/// The fence itself is still tested, by [`a_file_that_really_leaks_is_repaired_and_still_filed`] with a file that
/// still does.
#[test]
fn a_single_bracket_attribute_no_longer_props_the_program_open() {
    let leaky = "REPEATABLE\n[source_annotation_attribute( 1 )]\nstruct Pre\n{\n int Deref;\n};\n";
    let main = "#include \"broken.h\"\n#include \"good.h\"\nInside i;\n";
    let files = MemoryFiles::new()
        .with_file("/p/broken.h", leaky)
        .with_file(
            "/p/good.h",
            "namespace good {\nstruct Inside { int y; };\n}\n",
        )
        .with_file("/p/main.cpp", main);
    let fixture = Memory::new("a-scope-that-used-to-leak", &files);
    let mut session = fixture.session();

    session.did_open("/p/main.cpp", main);
    session.index_everything();
    let reading = session
        .read_the_unit(Path::new("/p/main.cpp"))
        .expect("the unit reads");

    assert!(
        reading.unbalanced.is_empty(),
        "the text balances, and now the parse does too: {reading:?}"
    );
    assert!(
        reading.unbalanced.is_empty(),
        "nothing leaked and nothing is out of balance: {reading:?}"
    );

    // **The declarations of the file that used to poison the program are filed, under their own names.**
    let pre = session
        .index()
        .cooked_declarations(Path::new("/p/broken.h"))
        .expect("the reading was filed")
        .iter()
        .find(|fact| fact.name == "Pre")
        .expect("the struct the attribute precedes is declared there");
    assert_eq!(
        pre.scope, None,
        "and it is at file scope, not inside anything"
    );

    let inside = session
        .index()
        .cooked_declarations(Path::new("/p/good.h"))
        .expect("the reading was filed")
        .iter()
        .find(|fact| fact.name == "Inside")
        .expect("the class is declared there")
        .scope
        .clone();
    assert_eq!(
        inside.as_deref(),
        Some("good"),
        "the file after it is read as itself"
    );
}

/// **A file that really leaks no longer costs anything, because there is no fence to invoke.**
///
/// `good.h` opens a namespace and never closes it, so a parse of the program sees `other.h` inside it. That
/// used to be found (a brace paired across two files) and repaired (the pair neutralised, both files read on
/// their own). **Both halves are gone**, and the reason is the plan's §3.0: a crossing needs the parser to pair
/// a brace in one file with one in another, which it can only do when the text it is given has a macro invocation
/// in place of the braces — and this stream is the *cooked* one, where every macro is already replaced.
///
/// So what is asserted here is what remains true and matters: nothing is refused, the file after the leak is
/// scoped by its own namespace, and the leaking file keeps its own declaration.
#[test]
fn a_file_that_does_not_balance_costs_nothing_but_a_name() {
    // `good.h` opens a namespace and never closes it. `other.h` is the file after it.
    let good = "namespace good {\nstruct Good { int x; };\n";
    let other = "struct Other { int y; };\n";
    let main = "#include \"good.h\"\n#include \"other.h\"\nOther o;\n";
    let files = MemoryFiles::new()
        .with_file("/p/good.h", good)
        .with_file("/p/other.h", other)
        .with_file("/p/main.cpp", main);
    let fixture = Memory::new("a-scope-that-really-leaks", &files);
    let mut session = fixture.session();

    session.did_open("/p/main.cpp", main);
    session.index_everything();
    let reading = session
        .read_the_unit(Path::new("/p/main.cpp"))
        .expect("the unit reads");

    // **The imbalance is named, and that is all that happens to it.** No file is quarantined, nothing is
    // repaired, and the reading is filed — the plan's §4 rule 1.
    assert_eq!(
        reading.unbalanced.len(),
        1,
        "one file does not balance, and it is reported: {reading:?}"
    );

    // **The file after it is read as itself, at file scope.**
    //
    // This is what the fence used to buy, and it is now bought **in the parser**: a scope may not cross a file
    // boundary, so the `{` that `good.h` never closed is closed at the end of `good.h` rather than paired with a
    // `}` in `other.h`. See `ParserConfig::file_boundaries` for the rule and `balance_events` for where it is
    // applied.
    //
    // The distinction matters for who owns the fix: deleting the fence exposed this leak, and the answer was not
    // to put the fence back — it was a defect **in the parser**, and the parser is where it is now fixed.
    let other_fact = session
        .index()
        .cooked_declarations(Path::new("/p/other.h"))
        .expect("other.h is part of the program")
        .iter()
        .find(|fact| fact.name == "Other")
        .map(|fact| fact.scope.clone())
        .expect("the struct is declared there");
    assert_eq!(
        other_fact, None,
        "the file after the unbalanced one is at file scope, not inside `good::`: {reading:?}"
    );

    // **And the unbalanced file did not lose its own declarations.**
    let good_facts = session
        .index()
        .cooked_declarations(Path::new("/p/good.h"))
        .expect("the leaking file's own reading is filed too");
    assert!(
        good_facts.iter().any(|fact| fact.name == "Good"),
        "the struct is declared in the file that does not balance: {good_facts:?}"
    );
}

/// **A program in which no file leaks is read once** — the ordinary case has no quarantine and no second parse.
#[test]
fn a_program_whose_files_keep_their_scopes_quarantines_nothing() {
    let main = "#include \"a.h\"\n#include \"b.h\"\nint main_variable;\n";
    let files = MemoryFiles::new()
        .with_file("/p/a.h", "namespace a {\nstruct A { int x; };\n}\n")
        .with_file("/p/b.h", "namespace b {\n#include \"c.h\"\n}\n")
        .with_file("/p/c.h", "struct C { int z; };\n")
        .with_file("/p/main.cpp", main);
    let fixture = Memory::new("a-program-that-does-not-leak", &files);
    let mut session = fixture.session();

    session.did_open("/p/main.cpp", main);
    session.index_everything();
    let reading = session
        .read_the_unit(Path::new("/p/main.cpp"))
        .expect("the unit reads");

    assert!(
        reading.unbalanced.is_empty(),
        "a scope that closes around an `#include` is in balance: {reading:?}"
    );
    let c = session
        .index()
        .cooked_declarations(Path::new("/p/c.h"))
        .expect("filed")
        .iter()
        .find(|fact| fact.name == "C")
        .expect("declared")
        .scope
        .clone();
    assert_eq!(
        c.as_deref(),
        Some("b"),
        "the namespace `b.h` opens around its include still holds `C`"
    );
}

/// **A unit read puts the whole program in the index, once** — [`Session::read_the_unit`].
///
/// The reading this session is built to reach and has not reached: one walk, one stream, one parse, and every
/// declaration filed under the file it was written in — so a header has the program's reading whether or not
/// anybody opened it. Here the same fixture as above, asked for the **program** rather than for one file:
/// `handle.h` is read (it is what the program is made of), and a file the program does not read is not.
///
/// It is a test of the call as the *caller* makes it — [`Session::read_the_unit`] is still the API for a caller that
/// wants a program now. The pipeline's own schedule is
/// [`a_program_is_read_when_the_reader_stops_editing`] below, which is a different question: *when*.
#[test]
fn a_unit_read_reads_the_whole_program_once() {
    let handle = "#include \"deep.h\"\n#define DECLARE_HANDLE(name) struct name##__ { int unused; }; \
                      typedef struct name##__ *name\n";
    let api = "#include \"handle.h\"\nDECLARE_HANDLE(HWND);\n";
    let main = "#include \"api.h\"\nHWND h;\n";
    let files = MemoryFiles::new()
        .with_file("/p/deep.h", "#define DEEP 1\n")
        .with_file("/p/handle.h", handle)
        .with_file("/p/api.h", api)
        .with_file("/p/main.cpp", main)
        .with_file("/p/other.cpp", "#include \"other.h\"\nvoid g() { }\n")
        .with_file("/p/other.h", "struct Unrelated { int y; };\n");
    let fixture = Memory::new("a-unit-read", &files);
    let mut session = fixture.session();

    session.did_open("/p/main.cpp", main);
    session.index_everything();

    // **The per-file policy has a bound, and this is it.** `handle.h` is the level under a direct include, which
    // [`COOK_ONE_LEVEL_FURTHER`] reaches on purpose (`<string>` → `<xstring>`); `deep.h` is the level under *that*,
    // which [`COOK_TWO_LEVELS_FURTHER`] reaches for the reason `std::string` needed it — measured on
    // EmmyLuaCodeStyle, `members_of` answered `NotDeclaredHere` for a file whose header includes the header that
    // includes the one that declares the class. The rest of this test is what the session does when a caller asks
    // for the **program** instead of for one file, and the contrast is the point: a unit read has no bound at all.
    assert!(
        session
            .index()
            .cooked_declarations(Path::new("/p/handle.h"))
            .is_some(),
        "the level under a direct include is cooked"
    );
    assert!(
        session
            .index()
            .cooked_declarations(Path::new("/p/deep.h"))
            .is_some(),
        "and the level under that is cooked too — the bound moved when `std::string` needed it"
    );

    let reading = session
        .read_the_unit(Path::new("/p/main.cpp"))
        .expect("the unit reads");
    assert_eq!(reading.root, Path::new("/p/main.cpp"));
    // **`files` is the walk's frames; `files_with_tokens` is smaller, and that is not a defect.** `handle.h`
    // holds one `#define` and nothing else, and a directive contributes no token to the rendering — the same
    // distinction the census records as "a clean file whose rendering is empty was not read at all" (§7). Both
    // numbers are asserted so that the difference stays visible rather than being smoothed over.
    assert!(
        reading.files >= 3,
        "the program is three files: {reading:?}"
    );
    assert_eq!(
        reading.files_with_tokens, 2,
        "two of them write tokens; a file of directives writes none: {reading:?}"
    );
    assert_eq!(reading.missing, 0, "every file had text: {reading:?}");

    // **The program's files**, including the header nobody opened, the level the per-file policy stopped short
    // of, and the macro's declaration in the file that invoked it.
    for (file, why) in [
        (
            "/p/handle.h",
            "a file the program is made of is read with it",
        ),
        ("/p/deep.h", "including the one the per-file bound left out"),
    ] {
        assert!(
            session
                .index()
                .cooked_declarations(Path::new(file))
                .is_some(),
            "{why}"
        );
    }
    let after = session
        .index()
        .definition("HWND__", Path::new("/p/main.cpp"));
    let Known::Yes(found) = after else {
        panic!("`api.h`'s cooked reading declares it: {after:?}");
    };
    assert_eq!(found.file, Path::new("/p/api.h"));

    // **And a file outside the program is not touched**: nothing compiles `other.cpp`, nobody opens it.
    assert!(
        session
            .index()
            .cooked_declarations(Path::new("/p/other.cpp"))
            .is_none(),
        "a file no program reads and nobody opens has no reading"
    );
}

/// **The pipeline reads a whole program once the reader has stopped typing** — the schedule, and its gate.
///
/// A unit read is the session's one indivisible piece of work ([`Session::prepare_a_unit_reading`]: a walk, a cook of
/// every file in include order, a parse of the whole program and a sweep — 5.09 s for a 159-file program measured on
/// a real project). Its preparing half takes the **read** lock, and a keystroke takes the write one, so a reader
/// typing during it waits for the whole program. Two things follow, and both are asserted here:
///
/// ```text
/// while the reader is typing      `advance` reads the file it was told about and no program  → the fixture's
///                                 `deep.h` — two includes below the file opened — has no cooked reading
/// a second after the last edit    the next drain schedules the program, and the closure's files get one
/// ```
///
/// The second half is what makes the whole closure queryable without anybody asking about it, which is the shape
/// §5 step two needs: one timeline per translation unit, not one walk per file.
#[test]
fn a_program_is_read_when_the_reader_stops_editing() {
    // **Four includes deep on purpose**: the per-file policy cooks an open file's direct includes and the level under
    // them (`COOK_TWO_LEVELS_FURTHER`), so `deep.h` — the file this test watches — has to be further down than that
    // or its reading would be there before the program is read at all.
    let handle = "#include \"mid.h\"\n#define DECLARE_HANDLE(name) struct name##__ { int unused; }; \
                  typedef struct name##__ *name\n";
    let main = "#include \"api.h\"\nHWND h;\n";
    let files = MemoryFiles::new()
        .with_file("/p/deep.h", "#define DEEP 1\n")
        .with_file("/p/mid.h", "#include \"deep.h\"\nstruct Mid { int x; };\n")
        .with_file("/p/handle.h", handle)
        .with_file("/p/api.h", "#include \"handle.h\"\nDECLARE_HANDLE(HWND);\n")
        .with_file("/p/main.cpp", main);
    let fixture = Memory::new("a-program-when-the-typing-stops", &files);
    let mut session = fixture.session();

    // **The reader opens the file and types into it**, which is the state the schedule must stay out of.
    session.did_open("/p/main.cpp", main);
    session.index_everything();
    let steps = session.advance(4);
    assert!(
        !session
            .index()
            .cooked_declarations(Path::new("/p/deep.h"))
            .is_some(),
        "nothing read the program while the reader was typing: {:?}",
        paths(&steps)
    );

    // **And the clock is the gate**: a second after the last keystroke, the next drain reads one program.
    std::thread::sleep(super::UNTIL_A_UNIT_MAY_BE_READ + std::time::Duration::from_millis(100));
    session.advance(1);

    assert!(
        session
            .index()
            .cooked_declarations(Path::new("/p/deep.h"))
            .is_some(),
        "the program's own files are read with it, two includes below the file the reader opened"
    );
    let found = session
        .index()
        .definition("HWND__", Path::new("/p/main.cpp"));
    let Known::Yes(found) = found else {
        panic!("the macro's declaration is in the index after the program was read: {found:?}");
    };
    assert_eq!(
        found.file,
        Path::new("/p/api.h"),
        "filed under the file that invoked the macro"
    );
}

/// **A program too large to read inside a keystroke's budget is left to the per-file reading.**
///
/// The other half of the schedule above. A unit read is linear in its program — 0.72 s per megabyte of source
/// measured — and its preparing half holds the read lock, so a program over
/// [`THE_LARGEST_PROGRAM_READ_AT_ONCE`] would make a keystroke wait longer than the server's own write budget. Such a
/// program is not read as one piece: it keeps the per-file reading, which answers for the file a query names and
/// never blocks anybody.
///
/// The fixture is the same shape with one big comment-only header in the middle, so the *choice* is the only thing
/// that differs between the two tests.
#[test]
fn a_program_too_large_to_read_at_once_is_left_alone() {
    // A comment block just over the budget: the file is in the program's closure and contributes nothing but bytes,
    // which is exactly what the budget is about. Sized from the constant rather than written out, so that raising the
    // budget cannot quietly turn this test into the one above.
    let line = "// padding padding padding padding\n";
    let big = line.repeat(super::THE_LARGEST_PROGRAM_READ_AT_ONCE / line.len() + 1);
    assert!(big.len() > super::THE_LARGEST_PROGRAM_READ_AT_ONCE);

    let handle = "#include \"big.h\"\n#include \"mid.h\"\n#define DECLARE_HANDLE(name) struct name##__ { int unused; }; \
                  typedef struct name##__ *name\n";
    let main = "#include \"api.h\"\nHWND h;\n";
    let files = MemoryFiles::new()
        .with_file("/p/big.h", big)
        .with_file("/p/deep.h", "#define DEEP 1\n")
        .with_file("/p/mid.h", "#include \"deep.h\"\nstruct Mid { int x; };\n")
        .with_file("/p/handle.h", handle)
        .with_file("/p/api.h", "#include \"handle.h\"\nDECLARE_HANDLE(HWND);\n")
        .with_file("/p/main.cpp", main);
    let fixture = Memory::new("a-program-too-large", &files);
    let mut session = fixture.session();

    session.did_open("/p/main.cpp", main);
    session.index_everything();
    std::thread::sleep(super::UNTIL_A_UNIT_MAY_BE_READ + std::time::Duration::from_millis(100));
    session.advance(1);

    assert!(
        !session
            .index()
            .cooked_declarations(Path::new("/p/deep.h"))
            .is_some(),
        "the program is over the budget, so it is not read in one piece"
    );
    // …and the reading the file *does* have is there: the open file and its direct includes are cooked as always.
    assert!(
        session
            .index()
            .cooked_declarations(Path::new("/p/api.h"))
            .is_some(),
        "the per-file reading is unaffected by the budget"
    );
}

/// **The same, with everything the real project has that the fixture above does not**: a namespace, a *private*
/// alias, and the alias declared after the members that use it.
///
/// The previous fixture passes and the real `std::_Tree` does not, so the difference has to be one of these three —
/// this fixture is the instrument that says which.
#[test]
fn a_private_namespaced_alias_still_resolves_in_a_return_type() {
    let text = "namespace std {\n\
                template <typename T> struct _Tree_base { using iterator = T *; };\n\
                template <typename T> struct _Tree {\n\
                public:\n\
                \x20   _Mybase::iterator find(int key) const;\n\
                private:\n\
                \x20   using _Mybase = _Tree_base<T>;\n\
                };\n\
                }\n\
                void f(std::_Tree<int> &t) {\n\
                \x20   t.find(1);\n\
                }\n";
    let files = MemoryFiles::new().with_file("/p/a.cpp", text);
    let fixture = Memory::new("a-private-namespaced-alias", &files);
    let mut session = fixture.session();
    session.did_open("/p/a.cpp", text);
    session.index_everything();
    let path = std::path::PathBuf::from("/p/a.cpp");
    let view = session.view_of_the_file(&path).expect("a view");

    let at = text.find("find(1)").expect("the fixture") + "find".len();
    let typed = session.type_at(&view, crate::file::coordinates::ReadingOffset::new(at));
    let Known::Yes(typed) = typed else {
        panic!("`t.find(1)` must have a type: {typed:?}");
    };
    assert_eq!(
        typed.type_of, "int*",
        "`_Mybase::iterator` is `_Tree_base<int>::iterator` — a private alias still names a type here"
    );
}
/// **A call whose return type is a *qualified alias of its own class*** — `_Mybase::iterator`, MSVC's spelling.
///
/// Measured on a real project: `LuaReserved.find(text)` typed as `_Mybase::iterator` — `_Tree::find` returns
/// `_Mybase::iterator`, and `_Mybase` is a member alias of the very class the function belongs to. Everything
/// downstream then asks a class called `_Mybase::iterator` for its members, and the answer is whatever the last hop
/// happened to be. The finishing walk (`finish_a_nested_name`) reads one *bare* name at a time, which is why it could
/// not follow this one.
#[test]
fn a_calls_return_type_is_a_qualified_alias_of_its_own_class() {
    let text = "template <typename T> struct base { using iterator = T *; };\n\
                template <typename T> struct tree {\n\
                \x20   using _Mybase = base<T>;\n\
                \x20   _Mybase::iterator find(int key) const;\n\
                };\n\
                void f(tree<int> &t) {\n\
                \x20   t.find(1);\n\
                }\n";
    let files = MemoryFiles::new().with_file("/p/a.cpp", text);
    let fixture = Memory::new("a-qualified-alias-return", &files);
    let mut session = fixture.session();
    session.did_open("/p/a.cpp", text);
    session.index_everything();
    let path = std::path::PathBuf::from("/p/a.cpp");
    let view = session.view_of_the_file(&path).expect("a view");

    let at = text.find("find(1)").expect("the fixture") + "find".len();
    let typed = session.type_at(&view, crate::file::coordinates::ReadingOffset::new(at));
    let Known::Yes(typed) = typed else {
        panic!("`t.find(1)` must have a type: {typed:?}");
    };
    assert_eq!(
        typed.type_of, "int*",
        "`_Mybase::iterator` is `base<int>::iterator`, which is `int*`"
    );
}
/// **`map<…>::find(k)->second`, with the comparator written out** — the real project's own line.
///
/// MSVC's `map` takes four template arguments and `LuaReserved`'s type writes three
/// (`std::map<std::string, LuaTokenKind, std::less<>>`). The element of a map is `pair<const K, V>` whatever the
/// comparator is, and the layer's element rule required **exactly two** arguments — so it answered "no element" and the
/// call fell back to its declaration's `_Mybase::iterator`, which is a dependent type nobody can open. Measured on the
/// real project before this fixture: `LuaReserved.find(text)->second` → `Unknown(NotDeclaredHere("std::conditional<
/// _Test, _Ty1, _Ty2>::type::second"))`; after: `LuaTokenKind`.
#[test]
fn a_maps_find_reaches_the_element_when_the_comparator_is_written() {
    let text = "template <typename A, typename B> struct pair { A first; B second; };\n\
                template <typename K, typename V, typename C> struct map_like {\n\
                \x20   pair<const K, V> find(const K &key) const;\n\
                };\n\
                void f(map_like<int, float, int> &m) {\n\
                \x20   m.find(1)->second;\n\
                }\n";
    let files = MemoryFiles::new().with_file("/p/a.cpp", text);
    let fixture = Memory::new("a-maps-find-with-a-comparator", &files);
    let mut session = fixture.session();
    session.did_open("/p/a.cpp", text);
    session.index_everything();
    let path = std::path::PathBuf::from("/p/a.cpp");
    let view = session.view_of_the_file(&path).expect("a view");

    // **The call itself**, which is the element the iterator rule answers: `pair<const int, float>`.
    let at = text.find("find(1)").expect("the fixture") + "find".len();
    let typed = session.type_at(&view, crate::file::coordinates::ReadingOffset::new(at));
    let Known::Yes(typed) = typed else {
        panic!("`m.find(1)` must have a type: {typed:?}");
    };
    assert!(
        typed.type_of.contains("pair") && typed.type_of.contains("float"),
        "the element of the map, not the iterator: {:?}",
        typed.type_of
    );

    // **And the member reached through it**: `second` is `float`.
    let second = text.find("->second").expect("the fixture") + "->".len();
    let found = session.definitions(&view, crate::file::coordinates::ReadingOffset::new(second));
    let Known::Yes(found) = found else {
        panic!("`find(1)->second` must resolve: {found:?}");
    };
    assert_eq!(found.found[0].fact.name, "second");
}
/// **`map::find(…)`'s answer, the shape the real project has** — the call's type, then the arrow, then the element.
///
/// The previous fixture asked the arrow directly. The real report is one hop longer: `LuaReserved.find(text)` is a
/// *call*, whose answer is an iterator, whose `operator->` answers a trait alias. On the real project that chain
/// answered `class "conditional_t": 0 member(s)` **without entering the alias walk at all**, which is what this
/// fixture is for — it reproduces the same three steps in one file, where a fix takes five seconds to try.
#[test]
fn a_calls_iterator_answer_reaches_the_element_through_a_trait_alias() {
    let text = "template <bool B, class T, class F> struct conditional {};\n\
                template <class T, class F> struct conditional<false, T, F> { using type = F; };\n\
                template <bool B, class T, class F>\n\
                using conditional_t = typename conditional<B, T, F>::type;\n\
                struct element { int first; int second; };\n\
                template <typename T> struct tree_iterator {\n\
                \x20   using pointer = conditional_t<false, void, T> *;\n\
                \x20   pointer operator->() const;\n\
                };\n\
                struct map_like {\n\
                \x20   using value_type = element;\n\
                \x20   tree_iterator<value_type> find(int key) const;\n\
                };\n\
                void f(map_like &m) {\n\
                \x20   m.find(1)->second = 2;\n\
                }\n";
    let files = MemoryFiles::new().with_file("/p/a.cpp", text);
    let fixture = Memory::new("a-calls-iterator-through-a-trait", &files);
    let mut session = fixture.session();
    session.did_open("/p/a.cpp", text);
    session.index_everything();
    let path = std::path::PathBuf::from("/p/a.cpp");
    let view = session.view_of_the_file(&path).expect("a view");

    let at = text.find("->second").expect("the fixture") + "->".len();
    let found = session.definitions(&view, crate::file::coordinates::ReadingOffset::new(at));
    let Known::Yes(found) = found else {
        panic!("`m.find(1)->second` must resolve: {found:?}");
    };
    assert_eq!(
        (
            found.found[0].fact.name.as_str(),
            found.found[0].fact.scope.as_deref()
        ),
        ("second", Some("element")),
        "the call's iterator, its `pointer` alias, and the trait alias in it"
    );
}
/// **`auto s = std::format("x {}", 1)` has the type of the overload the *arguments* select.**
///
/// The engine refused an ambiguous callee name and stopped there, so `auto` had no initializer type and no type at
/// all — reported from an editor on `auto enenn = std::format(FULL_NAME_FORMAT, myName.getFullName(0));`, where the
/// card said "a variable" and nothing else. The ranking that decides it already existed (the signature popup and the
/// hover's `→` marker use it); the callee's declaration simply never asked it.
///
/// Measured on the real file after this: `enenn` answers
/// `basic_string<char, char_traits<char>, allocator<char>>`. The narrow/wide tie is broken by the character width the
/// arguments' types carry, which is the rule the fix's own comment states.
/// **A constant's value is folded, and an enumerator's initialiser can name one.**
///
/// Reported from an editor with two screenshots: `const int FIRST_RESERVED = UCHAR_MAX + 1;` showed no value, and
/// `enum LuaTokenTypeDetail { TK_AND = FIRST_RESERVED, … }` showed none for `TK_AND` either. The layer that folds it
/// is `sema::constant` — arithmetic, literals, and names it can be told the value of (a file-local constant, an
/// enumerator, an object-like macro).
#[test]
fn a_constants_value_is_folded_and_an_enumerators_initialiser_reads_it() {
    let text = "#define UCHAR_MAX 0xff\n\
                const int FIRST_RESERVED = UCHAR_MAX + 1;\n\
                enum Kind { TK_AND = FIRST_RESERVED, TK_BREAK, TK_SHIFT = 1 << 4 };\n\
                int plain = 5;\n";
    let files = MemoryFiles::new().with_file("/p/a.cpp", text);
    let fixture = Memory::new("a-folded-constant", &files);
    let mut session = fixture.session();
    session.did_open("/p/a.cpp", text);
    session.index_everything();
    let path = std::path::PathBuf::from("/p/a.cpp");
    let view = session.view_of_the_file(&path).expect("a view");

    let value_at = |written: &str| {
        let at = text.find(written).expect("the fixture");
        session.constant_value_at(&view, crate::file::coordinates::ReadingOffset::new(at))
    };

    assert_eq!(
        value_at("FIRST_RESERVED = "),
        Some(256),
        "`UCHAR_MAX + 1` folds: `0xff` + 1"
    );
    assert_eq!(
        value_at("TK_AND"),
        Some(256),
        "the enumerator names the constant"
    );
    assert_eq!(
        value_at("TK_BREAK"),
        Some(257),
        "and the next one counts on"
    );
    assert_eq!(value_at("TK_SHIFT"), Some(16), "`1 << 4` folds");
    assert_eq!(
        value_at("plain = 5"),
        None,
        "a non-const variable has a value but not a constant one"
    );
}
/// **A member list through an alias written with an absolute target** — the shape the renderer produces.
///
/// `std::string` is `using string = basic_string<char, …>;`, and a target read out of the **rendering** is spelled
/// `:: std :: basic_string<char, …>`: the preprocessor writes a macro's expansion spaced and absolute. Every later
/// lookup keys on the spelling, so the chain gave up (`is_declared` answered false for `:: std :: basic_string`) and
/// `members_of` answered **0 members** — which is what an editor saw as "the type is deduced but nothing completes
/// after `enenn.`".
#[test]
fn a_member_list_is_reached_through_an_alias_written_absolutely() {
    let text = "namespace std {\n\
                template <class T> struct basic_string {\n\
                \x20   void append(const T &value);\n\
                \x20   int size() const;\n\
                };\n\
                using string = ::std::basic_string<char>;\n\
                }\n\
                void g() {\n\
                \x20   std::string s;\n\
                \x20   s.\n\
                }\n";
    let files = MemoryFiles::new().with_file("/p/a.cpp", text);
    let fixture = Memory::new("an-absolute-alias-target", &files);
    let mut session = fixture.session();
    session.did_open("/p/a.cpp", text);
    session.index_everything();
    let path = std::path::PathBuf::from("/p/a.cpp");
    let view = session.view_of_the_file(&path).expect("a view");

    let at = text.find("s.\n").expect("the fixture") + "s.".len();
    let completions =
        session.member_completions(&view, crate::file::coordinates::FileOffset::new(at));
    let Known::Yes(completions) = completions else {
        panic!("`s.` must list `basic_string`'s members: {completions:?}");
    };
    let mut names: Vec<&str> = completions
        .members
        .members
        .iter()
        .map(|member| member.fact.name.as_str())
        .collect();
    names.sort_unstable();
    names.dedup();
    assert_eq!(
        names,
        vec!["append", "size"],
        "the alias's absolute target names a class the index has"
    );
}

#[test]
fn a_calls_overload_is_the_one_its_arguments_select() {
    let text = "namespace std {\n\
                struct string { };\n\
                struct wstring { };\n\
                template <class... T> struct format_string { };\n\
                template <class... T> struct wformat_string { };\n\
                template <class... T> string format(const format_string<T...>, T &&...);\n\
                template <class... T> wstring format(const wformat_string<T...>, T &&...);\n\
                }\n\
                void g() {\n\
                \x20   auto narrow = std::format(\"x {}\", 1);\n\
                \x20   auto wide = std::format(L\"x {}\", 1);\n\
                }\n";
    let files = MemoryFiles::new().with_file("/p/a.cpp", text);
    let fixture = Memory::new("a-calls-selected-overload", &files);
    let mut session = fixture.session();
    session.did_open("/p/a.cpp", text);
    session.index_everything();
    let path = std::path::PathBuf::from("/p/a.cpp");
    let view = session.view_of_the_file(&path).expect("a view");

    for (written, expected) in [("auto narrow", "string"), ("auto wide", "wstring")] {
        let at = text.find(written).expect("the fixture") + "auto ".len();
        let typed = session.type_at(&view, crate::file::coordinates::ReadingOffset::new(at));
        let Known::Yes(typed) = typed else {
            panic!("`{written} = std::format(…)` must have a type: {typed:?}");
        };
        assert_eq!(
            typed.type_of, expected,
            "the arguments select the overload — {written}"
        );
    }
}
/// **A name with several declarations and no type they agree on says *that*, rather than "unknown type".**
///
/// Reported from an editor: `auto enenn = std::format(FULL_NAME_FORMAT, myName.getFullName(0));` showed no type at
/// all — no type in the card, no inlay hint — and nothing said why. Measured on the real project, `std::format` has
/// four overloads visible (narrow and wide, with and without a locale) and the call selects none of them, so refusing
/// is right; what was wrong is that the refusal said `UnknownType("std::format")`, which reads like a missing name.
/// `UnknownReason::Ambiguous` has a sentence a reader can act on, and the hover card now prints it.
#[test]
fn a_name_whose_declarations_disagree_answers_with_the_disagreement() {
    // **Two headers, one name, two return types** — the shape `std::format` has: the *index* answers it, so the
    // scope tree's own "first declaration" rule is not what decides. (A single file's two declarations are resolved by
    // `definition_at` to the first, which is the ordinary rule for one scope and is pinned by its own tests.)
    let header = "int f();\n";
    let other = "double f();\n";
    let text = "#include \"a.h\"\n#include \"b.h\"\nvoid g() {\n    auto x = f();\n}\n";
    let files = MemoryFiles::new()
        .with_file("/p/a.h", header)
        .with_file("/p/b.h", other)
        .with_file("/p/a.cpp", text);
    let fixture = Memory::new("a-disagreeing-name", &files);
    let mut session = fixture.session();
    session.did_open("/p/a.cpp", text);
    session.index_everything();
    let path = std::path::PathBuf::from("/p/a.cpp");
    let view = session.view_of_the_file(&path).expect("a view");

    let at = text.find("auto x").expect("the fixture") + "auto ".len();
    let typed = session.type_at(&view, crate::file::coordinates::ReadingOffset::new(at));
    match typed {
        Known::Unknown(crate::UnknownReason::Ambiguous(name)) => assert_eq!(&*name, "f"),
        other => panic!("`int f()` and `double f()` agree on no type: {other:?}"),
    }
}
/// **An unscoped enumeration's enumerators are visible one scope *out*.** — the C++ rule, and the one place a scope
/// tree built as a mirror of the syntax gets it wrong.
///
/// Reported from an editor: `enum { MyClass = 123, AnotherClass };` with `printf("…", AnotherClass)` coloured the
/// *definition* as an enum member and nothing at all at the use — the client's own fallback drew it as an unknown
/// variable, "go to definition" found nothing, and the same would be true of hover and completion. The bindings live
/// in the enum's own scope, which is a **child** of the scope that can see them, so the upward lookup never reached
/// them; [`crate::sema::resolve::definitions_at`] now looks one scope out for an `enum` and not for an `enum class`.
#[test]
fn an_unscoped_enumerations_member_is_visible_in_the_enclosing_scope() {
    let text = "enum { MyClass = 123, AnotherClass };\n\
                enum class Scoped { Hidden };\n\
                int main() {\n\
                \x20   int a = AnotherClass;\n\
                \x20   int b = Hidden;\n\
                }\n";
    let files = MemoryFiles::new().with_file("/p/a.cpp", text);
    let fixture = Memory::new("an-unscoped-enum", &files);
    let mut session = fixture.session();
    session.did_open("/p/a.cpp", text);
    session.index_everything();
    let path = std::path::PathBuf::from("/p/a.cpp");
    let view = session.view_of_the_file(&path).expect("a view");

    // The use of `AnotherClass` resolves — and the name it resolves to is the enumerator.
    let at = text.find("= AnotherClass").expect("the fixture") + 2;
    let found = session.definitions(&view, crate::file::coordinates::ReadingOffset::new(at));
    let Known::Yes(found) = found else {
        panic!("a bare `AnotherClass` must resolve: {found:?}");
    };
    assert_eq!(
        found.found[0].fact.name, "AnotherClass",
        "the enumerator, not the enumeration"
    );

    // …and it is classified as an **enum member**, which is what the highlighter draws.
    let classified: Vec<(String, crate::semantic::NameKind)> = session
        .classified_names(&view)
        .into_iter()
        .map(|name| {
            (
                text[name.range.start_offset..]
                    .chars()
                    .take(12)
                    .collect::<String>(),
                name.kind,
            )
        })
        .collect();
    let kinds: Vec<&crate::semantic::NameKind> = classified
        .iter()
        .filter(|(spelled, _)| spelled.starts_with("AnotherClass"))
        .map(|(_, kind)| kind)
        .collect();
    assert!(
        kinds.contains(&&crate::semantic::NameKind::EnumMember),
        "the use is an enum member too, not just the declaration: {classified:?}"
    );
    assert!(
        kinds.len() >= 2,
        "both the declaration and the use are coloured: {classified:?}"
    );

    // **The declaration answers too.** An enumerator's name is a plain token rather than a `NameExpr`, so
    // `definitions` at the *definition* used to answer `Unknown(UnparsableName)` — the second half of the editor
    // report ("在匿名枚举的定义本身没有 hover 结果") — while hovering the use worked.
    let declaration = text.find("AnotherClass }").expect("the fixture");
    let found = session.definitions(
        &view,
        crate::file::coordinates::ReadingOffset::new(declaration),
    );
    let Known::Yes(found) = found else {
        panic!("the declaration of `AnotherClass` must answer: {found:?}");
    };
    assert_eq!(found.found[0].fact.name, "AnotherClass");

    // **`enum class` still hides its enumerators**: `Scoped::Hidden` is the only way to name it.
    let hidden = text.find("= Hidden").expect("the fixture") + 2;
    let found = session.definitions(&view, crate::file::coordinates::ReadingOffset::new(hidden));
    assert!(
        !matches!(&found, Known::Yes(found) if found.found[0].fact.name == "Hidden"),
        "a scoped enumeration's member is not visible here: {found:?}"
    );
}
/// **A trait alias selects its specialization** — `conditional_t<false, void, T>` is `T`, and the arrow reaches it.
///
/// The lookup therefore has to pick the declaration the *use* is an instance of — the pattern rule,
/// with the arguments split where the language splits them.
#[test]
fn a_trait_alias_selects_the_specialization_its_arguments_name() {
    let text = "struct Item { int value; void grow(); };\n\
                template <bool B, class T, class F> struct conditional {};\n\
                template <class T, class F> struct conditional<false, T, F> { using type = F; };\n\
                template <bool B, class T, class F>\n\
                using conditional_t = typename conditional<B, T, F>::type;\n\
                template <typename T> struct handle {\n\
                \x20   using value_type = conditional_t<false, void, T>;\n\
                \x20   value_type *operator->() const;\n\
                };\n\
                void g(handle<Item> h) {\n\
                \x20   h->\n\
                }\n";
    let files = MemoryFiles::new().with_file("/p/a.cpp", text);
    let fixture = Memory::new("a-trait-alias-selects", &files);
    let mut session = fixture.session();
    session.did_open("/p/a.cpp", text);
    session.index_everything();
    let path = std::path::PathBuf::from("/p/a.cpp");
    let view = session.view_of_the_file(&path).expect("a view");

    let written = "h->";
    let at = text.find(written).expect("the fixture") + written.len();
    let completions =
        session.member_completions(&view, crate::file::coordinates::FileOffset::new(at));
    let Known::Yes(completions) = completions else {
        panic!("`{written}` must reach `Item`: {completions:?}");
    };
    let names: Vec<&str> = completions
        .members
        .members
        .iter()
        .map(|member| member.fact.name.as_str())
        .collect();
    assert_eq!(
        completions.class, "Item",
        "`conditional_t<false, void, T>` is `T`, and the arrow reaches it ({names:?})"
    );
}
/// **`find()->second`**: an arrow whose answer is a *name* the class declares as an alias.
///
/// `std::map::find` answers an iterator, and MSVC's `_Tree_iterator::operator->` is declared as
///
/// ```cpp
/// using pointer = _Val*;          // _Val is the tree's value_type — a `pair<const K, V>`
/// _NODISCARD pointer operator->() const noexcept;
/// ```
///
/// so the arrow's answer is the *spelling* `pointer`, not a class.
#[test]
fn an_arrow_through_an_alias_reaches_the_pointee() {
    let text = "template <typename K, typename V> struct pair {\n\
                \x20   K first;\n\
                \x20   V second;\n\
                };\n\
                template <typename T> struct iterator {\n\
                \x20   using pointer = T *;\n\
                \x20   pointer operator->() const;\n\
                };\n\
                template <typename K, typename V> struct map {\n\
                \x20   using value_type = pair<const K, V>;\n\
                \x20   iterator<value_type> find(const K &key) const;\n\
                };\n\
                void f(map<int, float> &m) {\n\
                \x20   m.find(1)->second = 2;\n\
                }\n";
    let files = MemoryFiles::new().with_file("/p/a.cpp", text);
    let fixture = Memory::new("an-arrow-through-an-alias", &files);
    let mut session = fixture.session();
    session.did_open("/p/a.cpp", text);
    session.index_everything();
    let path = std::path::PathBuf::from("/p/a.cpp");
    let view = session.view_of_the_file(&path).expect("a view");

    let at = text.find("->second").expect("the fixture") + "->".len();
    let found = session.definitions(&view, crate::file::coordinates::ReadingOffset::new(at));
    let Known::Yes(found) = found else {
        panic!("`find()->second` must resolve through `pointer`: {found:?}");
    };
    assert_eq!(
        (
            found.found[0].fact.name.as_str(),
            found.found[0].fact.scope.as_deref()
        ),
        ("second", Some("pair")),
        "the arrow's `pointer` is the value type, and `second` is its member"
    );
}
/// **An out-of-line definition's type is the type it writes, not its own qualified name.**
///
/// Reported from an editor, three times in one sitting, always as a *type* that was really a name:
///
/// ```cpp
/// std::map<std::string, LuaTokenKind, std::less<>> LuaLexer::LuaReserved = { … };   // hover: `LuaLexer::LuaReserved`
/// std::size_t LuaSource::GetLine(std::size_t offset) const { … }                   // hover: `LuaSource::GetLine`
/// ```
///
/// and the member lookups that followed answered "`LuaLexer::LuaReserved` has no member `find`". The grammar puts a
/// qualified definition's name in the **specifier sequence** — the declarator holds only the parameter list — so a
/// reader that takes "the last name of the specifiers" as the type takes the declarator's own name. A definition and
/// its declaration are both in the index, and whoever asks may get either.
#[test]
fn an_out_of_line_definition_records_the_type_it_writes() {
    let text = "namespace std {\n\
                template <typename K, typename V> struct map { V &at(const K &key); };\n\
                }\n\
                struct Lexer {\n\
                \x20   static std::map<int, int> Reserved;\n\
                \x20   std::size_t GetLine(std::size_t offset) const;\n\
                };\n\
                std::map<int, int> Lexer::Reserved = {};\n\
                std::size_t Lexer::GetLine(std::size_t offset) const { return offset; }\n";
    let files = MemoryFiles::new().with_file("/p/a.cpp", text);
    let fixture = Memory::new("an-out-of-line-definition", &files);
    let mut session = fixture.session();
    session.did_open("/p/a.cpp", text);
    session.index_everything();
    let path = std::path::PathBuf::from("/p/a.cpp");

    let summary = session.index().summary(&path).expect("the file is read");
    for (name, expected) in [
        ("Reserved", "std::map<int, int>"),
        ("GetLine", "std::size_t"),
    ] {
        let written: Vec<Option<&str>> = summary
            .declarations
            .iter()
            .filter(|fact| fact.name == name)
            .map(|fact| fact.type_of.as_deref().or(fact.returns.as_deref()))
            .collect();
        assert!(
            written.contains(&Some(expected)),
            "`{name}` declares `{expected}`, and one of its facts must say so: {written:?}"
        );
        let qualified = format!("::{name}");
        assert!(
            !written
                .iter()
                .any(|found| found.is_some_and(|found| found.ends_with(&qualified))),
            "and none of them may record the declarator's own qualified name (`…{qualified}`): {written:?}"
        );
    }
}
/// **A class template's member answer is substituted with the use's arguments** — `b[0].value` and `b->value`.
///
/// The two reports from an editor (`events[Pos].U` on a `std::vector<MarkEvent>`, `file->setUri` on a
/// `std::shared_ptr<LuaSource>`) both ended the same way: the member question was asked about a class called `_Ty` or
/// `_Ty2` — the *declaration's* spelling of the class's own parameter, not the type the use wrote. Measured on the real
/// project with `tests/inference_probe.rs`:
///
/// ```text
/// events[Pos].   → Unknown(NotDeclaredHere("_Ty"))
/// file->         → class "_Ty2": 0 member(s)
/// ```
///
/// This fixture is the same question with names that say what is happening.
#[test]
fn a_class_templates_members_are_read_through_the_uses_arguments() {
    // **Three shapes, because the standard library uses all three.** `T& operator[]` states the parameter itself;
    // `reference operator[]` names an alias *of the class*, and the alias is what says `T&` — `std::vector`'s spelling,
    // and the one that answered `NotDeclaredHere("_Ty")` on a real project; `T *operator->` is `shared_ptr`'s.
    let text = "template <typename T> struct Box {\n\
                \x20   T &operator[](int index);\n\
                \x20   T *operator->();\n\
                };\n\
                template <typename T> struct AliasBox {\n\
                \x20   using reference = T &;\n\
                \x20   reference operator[](int index);\n\
                };\n\
                struct Item { int value; void grow(); };\n\
                void f(Box<Item> box) {\n\
                \x20   box[0].value;\n\
                \x20   box->grow();\n\
                }\n\
                void g(AliasBox<Item> box) {\n\
                \x20   alias[0].value;\n\
                }\n";
    let text = text.replace("alias[0]", "box[0]");
    let files = MemoryFiles::new().with_file("/p/a.cpp", &text);
    let fixture = Memory::new("a-class-templates-members", &files);
    let mut session = fixture.session();
    session.did_open("/p/a.cpp", &text);
    session.index_everything();
    let path = std::path::PathBuf::from("/p/a.cpp");
    let view = session.view_of_the_file(&path).expect("a view");

    // **The member after the operator, as a definition question** — the shape both reports had: `events[Pos].U` and
    // `file->setUri` are jumps, and a jump that asks about `_Ty` finds nothing.
    //
    // The third one searches *after* the first two, because the fixture writes `box[0].value` twice and the cursor of
    // each case has to be in its own function.
    let mut searched = 0usize;
    for (written, expected) in [
        ("box[0].value", ("value", Some("Item"))),
        ("box->grow", ("grow", Some("Item"))),
        ("box[0].value", ("value", Some("Item"))),
    ] {
        let found_at = text[searched..]
            .find(written)
            .map(|at| searched + at)
            .expect("the fixture writes it");
        searched = found_at + written.len();
        let at = found_at + written.len() - expected.0.len();
        let found = session.definitions(&view, crate::file::coordinates::ReadingOffset::new(at));
        let Known::Yes(found) = found else {
            panic!("`{written}` must resolve to the element's member: {found:?}");
        };
        assert_eq!(
            (
                found.found[0].fact.name.as_str(),
                found.found[0].fact.scope.as_deref()
            ),
            expected,
            "`{written}` is the element's member"
        );
    }
}
/// **A member template's own parameter is not the class's** — the shape `std::shared_ptr` is written in.
///
/// MSVC's `<memory>` declares
///
/// ```cpp
/// template <class _Ty> class shared_ptr : public _Ptr_base<_Ty> {
///     template <class _Ty2 = _Ty, enable_if_t<!is_array_v<_Ty2>, int> = 0>
///     _NODISCARD _Ty2* operator->() const noexcept { return get(); }
/// ```
///
/// so the member's answer mentions `_Ty2` — a parameter of the *member template*, defaulted to the class's `_Ty`. The
/// fact records the member's parameters as names, without their defaults, so substituting with the class's arguments
/// leaves `_Ty2` standing and the member lookup asks about a class called `_Ty2` (measured on EmmyLuaCodeStyle's
/// `LuaFormat.cpp`: `file->` → `class "_Ty2": 0 member(s)`).
///
/// What settles it is the convention every pointer-like type in the standard library follows: `element_type` is what
/// the arrow reaches.
#[test]
fn an_arrow_through_a_member_template_reaches_the_element_type() {
    // **The shape MSVC writes**, because it is the one that broke: the base is named through an alias, and the alias
    // being re-exposed (`using typename _Mybase::element_type;`) declares no type of its own.
    let header = "template <typename T> struct Holder {\n\
                  \x20   using element_type = T;\n\
                  };\n\
                  template <typename T> struct Handle {\n\
                  \x20 private:\n\
                  \x20   using _Mybase = Holder<T>;\n\
                  \x20 public:\n\
                  \x20   using typename _Mybase::element_type;\n\
                  \x20   template <typename U = T, int = 0>\n\
                  \x20   U *operator->() const;\n\
                  };\n";
    let source = "#include \"handle.h\"\n\
                  struct Item { int value; void grow(); };\n\
                  void g(Handle<Item> file) {\n\
                  \x20   file->\n\
                  }\n";
    let files = MemoryFiles::new()
        .with_file("/p/handle.h", header)
        .with_file("/p/a.cpp", source);
    let fixture = Memory::new("an-arrow-through-a-member-template", &files);
    let mut session = fixture.session();
    session.did_open("/p/a.cpp", source);
    session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
    session.index_everything();
    let path = std::path::PathBuf::from("/p/a.cpp");
    let view = session.view_of_the_file(&path).expect("a view");

    let written = "file->";
    let at = source.find(written).expect("the fixture") + written.len();
    let completions =
        session.member_completions(&view, crate::file::coordinates::FileOffset::new(at));
    let Known::Yes(completions) = completions else {
        panic!("`{written}` must list the element's members: {completions:?}");
    };
    let names: Vec<&str> = completions
        .members
        .members
        .iter()
        .map(|member| member.fact.name.as_str())
        .collect();
    assert_eq!(
        completions.class, "Item",
        "the arrow reaches `element_type`, not the member template's parameter name ({names:?})"
    );
}
/// **The real shape: a base in another file, a namespace, and an alias with arguments.**
///
/// The fixture above keeps `element_type` in the same file; this one is MSVC's layout — `std::_Ptr_base` in one header,
/// `std::shared_ptr` in another, the base named through `using _Mybase = _Ptr_base<_Ty>;` and the alias re-exposed with
/// `using typename _Mybase::element_type;`. It exists because the arrow's fallback works on the small fixture and did
/// **not** work on a real project, and the difference had to be found somewhere cheaper than a 95-second probe run.
#[test]
fn an_arrow_through_a_base_named_by_a_member_alias_in_another_file() {
    // **A forward declaration first**, which is what MSVC's `<memory>` has and what a member list must look past: the
    // first visible declaration of a class is not always the one with a body.
    // **The trait, not the parameter** — MSVC's `_Ptr_base` says `using element_type = remove_extent_t<_Ty>;`, and
    // `remove_extent_t` is an alias *template* whose target the library writes through `typename remove_extent<T>::type`.
    // A layer that follows spellings arrives at the bare name `remove_extent_t`, which is an alias and not a class; the
    // answer for a pointer-like handle is the class's own argument, and that is what the last part of the arrow's
    // fallback is for.
    let base = "namespace std {\n\
                template <typename T> class _Ptr_base;\n\
                template <typename T> struct remove_extent { using type = T; };\n\
                template <typename T> using remove_extent_t = typename remove_extent<T>::type;\n\
                template <typename T> class _Ptr_base {\n\
                public:\n\
                \x20   using element_type = remove_extent_t<T>;\n\
                };\n\
                }\n";
    let memory = "#include \"ptr_base.h\"\nnamespace std {\n\
                  template <typename T> class shared_ptr {\n\
                  private:\n\
                  \x20   using _Mybase = _Ptr_base<T>;\n\
                  public:\n\
                  \x20   using typename _Mybase::element_type;\n\
                  \x20   template <typename U = T, int = 0>\n\
                  \x20   U *operator->() const;\n\
                  \x20   element_type *get() const;\n\
                  };\n\
                  }\n";
    let source = "#include \"memory.h\"\n\
                  struct Item { int value; void grow(); };\n\
                  void g(std::shared_ptr<Item> file) {\n\
                  \x20   file->\n\
                  }\n";
    let files = MemoryFiles::new()
        .with_file("/p/ptr_base.h", base)
        .with_file("/p/memory.h", memory)
        .with_file("/p/a.cpp", source);
    let fixture = Memory::new("an-arrow-through-a-real-shape", &files);
    let mut session = fixture.session();
    session.did_open("/p/a.cpp", source);
    session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
    session.index_everything();
    let path = std::path::PathBuf::from("/p/a.cpp");
    let view = session.view_of_the_file(&path).expect("a view");

    let written = "file->";
    let at = source.find(written).expect("the fixture") + written.len();
    let completions =
        session.member_completions(&view, crate::file::coordinates::FileOffset::new(at));
    let Known::Yes(completions) = completions else {
        panic!("`{written}` must list the element's members: {completions:?}");
    };
    let names: Vec<&str> = completions
        .members
        .members
        .iter()
        .map(|member| member.fact.name.as_str())
        .collect();
    assert_eq!(
        completions.class, "Item",
        "the arrow reaches the base alias's `element_type` ({names:?})"
    );
}
/// **The same question when the class is declared in a header** — the shape the real project has, and the one that
/// answers `_Ty`.
///
/// `std::vector`'s `operator[]` is declared `reference operator[](size_type)`, and `reference` is `_Ty&` — an alias
/// *inside* the class. When the class is declared in another file, the alias is followed by
/// `ProjectIndex::template_parameters_of`/`resolve_aliases`, which has the *spelling* and not the use's arguments, so
/// it answers `_Ty&` and the member lookup then asks about a class called `_Ty`. Measured on EmmyLuaCodeStyle's
/// `Mark.cpp` (`events[Pos].U`): `Unknown(NotDeclaredHere("_Ty"))`.
#[test]
fn a_class_templates_alias_return_is_substituted_too() {
    let header = "template <typename T> struct AliasBox {\n\
                  \x20   using reference = T &;\n\
                  \x20   reference operator[](int index);\n\
                  };\n";
    let source = "#include \"box.h\"\n\
                  struct Item { int value; void grow(); };\n\
                  void g(AliasBox<Item> box) {\n\
                  \x20   box[0].value;\n\
                  }\n";
    let files = MemoryFiles::new()
        .with_file("/p/box.h", header)
        .with_file("/p/a.cpp", source);
    let fixture = Memory::new("a-class-templates-alias", &files);
    let mut session = fixture.session();
    session.did_open("/p/a.cpp", source);
    session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
    session.index_everything();
    let path = std::path::PathBuf::from("/p/a.cpp");
    let view = session.view_of_the_file(&path).expect("a view");

    let written = "box[0].value";
    let at = source.find(written).expect("the fixture") + written.len() - "value".len();
    let found = session.definitions(&view, crate::file::coordinates::ReadingOffset::new(at));
    let Known::Yes(found) = found else {
        panic!("`{written}` must resolve to the element's member: {found:?}");
    };
    assert_eq!(
        (
            found.found[0].fact.name.as_str(),
            found.found[0].fact.scope.as_deref()
        ),
        ("value", Some("Item")),
        "the alias's target is the use's argument, not the class's parameter name"
    );
}
/// **An anonymous enum declares its enumerators** — `enum { LAJF };`, the C spelling of a set of constants.
///
/// Reported from an editor as "an unnamed enum is not supported", and it was literally true: the declaration names
/// nothing, `is_unnamed_declaration` was consulted before the body was walked, and the walker returned — so every
/// enumerator of every anonymous enum was missing from the scope tree and from the index. Two lines above it the file
/// declares `LAJF`, and `definitions("LAJF")` answered `NotDeclaredHere`.
#[test]
fn an_anonymous_enum_declares_its_enumerators() {
    let text = "enum { LAJF, LBJF };\nvoid f() { int x = LAJF; }\n";
    let files = MemoryFiles::new().with_file("/p/a.cpp", text);
    let fixture = Memory::new("an-anonymous-enum", &files);
    let mut session = fixture.session();
    session.did_open("/p/a.cpp", text);
    session.index_everything();
    let path = std::path::PathBuf::from("/p/a.cpp");

    for name in ["LAJF", "LBJF"] {
        let found = session.index().definitions(name, &path);
        let Known::Yes(found) = found else {
            panic!("`{name}` is declared by the anonymous enum: {found:?}");
        };
        assert_eq!(
            found.found[0].fact.scope, None,
            "an unnamed enum has no scope name"
        );
    }

    // **And the name is classified as an enumerator**, which is what the semantic pass draws.
    let view = session.view_of_the_file(&path).expect("a view");
    let names = session.classified_names(&view);
    let lajf = names
        .iter()
        .find(|name| name.range.start_offset == text.find("LAJF").expect("the fixture"))
        .expect("`LAJF` is a name");
    assert_eq!(lajf.kind, crate::semantic::NameKind::EnumMember);
}
/// **A member reached through `operator->`** — `config->Generate` on a smart-pointer-shaped class.
///
/// Reported twice from an editor, in one sentence: *"a member cannot be found through a smart pointer, and there is no
/// completion either"*. The handle's own member list is `operator->`, `get`, `reset`; the names a reader is reaching
/// for after an arrow are the pointee's. Both halves are answered here: the lookup follows what `operator->` returns
/// (substituted with the arguments the use wrote, because the return type is the *class's* spelling — `_Ty *` for
/// `std::shared_ptr`), and the member list after `->` is the pointee's.
#[test]
fn a_member_through_an_operator_arrow_is_the_pointees() {
    let text = "template <typename T> struct handle { T *operator->(); void reset(); };\n\
                struct Config { int Generate(int uri); };\n\
                void g(handle<Config> config) { config->Generate(1); }\n";
    let files = MemoryFiles::new().with_file("/p/a.cpp", text);
    let fixture = Memory::new("through-an-arrow", &files);
    let mut session = fixture.session();
    session.did_open("/p/a.cpp", text);
    session.index_everything();
    let path = std::path::PathBuf::from("/p/a.cpp");
    let view = session.view_of_the_file(&path).expect("a view");

    // **The lookup**: `Generate` is `Config`'s, not the handle's.
    let at = text.find("Generate(1)").expect("the fixture") + 1;
    let found = session.definition(&view, crate::file::coordinates::ReadingOffset::new(at));
    let Known::Yes(found) = found else {
        panic!("`config->Generate` must resolve through `operator->`: {found:?}");
    };
    assert_eq!(
        (found.fact.name.as_str(), found.fact.scope.as_deref()),
        ("Generate", Some("Config")),
        "the member is the pointee's"
    );

    // **And the list**, after the arrow: the pointee's declarations.
    let after = text.find("config->Generate").expect("the fixture") + "config->".len();
    let completions =
        session.member_completions(&view, crate::file::coordinates::FileOffset::new(after));
    let Known::Yes(completions) = completions else {
        panic!("`config->` must list the pointee's members: {completions:?}");
    };
    assert_eq!(completions.class, "Config");
    let names: Vec<&str> = completions
        .members
        .members
        .iter()
        .map(|member| member.fact.name.as_str())
        .collect();
    assert_eq!(names, ["Generate"], "and not the handle's own list");
}
/// **`index.read_the_whole_project = false` keeps the reader's own programs and nothing else.**
///
/// A project that says so gets the first and not the second, and the clock says it too: with the
/// setting off there is nothing for the pump to wait for once the reader's own programs are read.
#[test]
fn a_project_can_decline_to_read_its_other_roots() {
    let shared = "struct Shared { int size; };\n";
    let a = "#include \"shared.h\"\n";
    let b = "#include \"shared.h\"\nint from_b = 1;\n";
    let files = MemoryFiles::new()
        .with_file("/p/shared.h", shared)
        .with_file("/p/a.cpp", a)
        .with_file("/p/b.cpp", b)
        .with_file(
            "/p/.cppls.toml",
            "[index]\nread_the_whole_project = false\n",
        );
    let fixture = Memory::new("a-project-declines", &files);
    // **The session's root is the project's**, not the fixture's temporary directory: `.cppls.toml` is read from
    // under that root, and the fixture files live under `/p`.
    let mut session = crate::Session::with_config(
        "/p",
        fixture.providers.clone(),
        crate::WatchFilter::new("/p"),
        crate::CompilerConfig::default(),
    );
    session.add_project_files([
        std::path::PathBuf::from("/p/a.cpp"),
        std::path::PathBuf::from("/p/b.cpp"),
    ]);
    session.did_open("/p/a.cpp", a);
    session.index_everything();

    // **The reader's own file is still read**, one second after they stop typing.
    session.pretend_a_pause(std::time::Duration::from_millis(1_100));
    let first = session
        .read_a_program_now()
        .expect("the reader's own program");
    assert_eq!(first.root, std::path::Path::new("/p/a.cpp"));

    // **And then nothing is owed**, however long the pause: `b.cpp` is a root nobody has open, which this project
    // asked not to read.
    session.pretend_a_pause(std::time::Duration::from_secs(60));
    assert!(
        session.read_a_program_now().is_none(),
        "the project declined its unopened roots"
    );
    assert!(
        session.the_wait_before_a_program_may_be_read().is_none(),
        "so the pump has nothing to wait for"
    );
    assert!(
        !session
            .index()
            .the_program_that_read(std::path::Path::new("/p/b.cpp"))
            .is_some(),
        "and `b.cpp` was not read"
    );
}
/// **A body edit does not cost the program again; a directive edit does.**
///
/// A program read is 5.24 s of background CPU for 180 files (measured, `tests/keystroke_probe.rs`), and what decides
/// whether it has to be paid again is the **shape** of the program: a body edit moves no directive, so every file of
/// the closure but the edited one still reads exactly as it did — and the edited one is rebuilt by the per-file cook
/// that every keystroke already queues. A directive edit moves every offset the timeline recorded, and the rendering
/// of the whole program with it.
///
/// [`Session::the_wait_before_a_program_may_be_read`] is the question the pump asks — `Some` when a program is owed,
/// whatever the clock says — and it is what makes this testable without sleeping.
#[test]
fn a_body_edit_does_not_cost_the_program_again() {
    let handle = "#define DECLARE_HANDLE(name) struct name##__ { int unused; }; \
                  typedef struct name##__ *name\n";
    let main = "#include \"api.h\"\nHWND h;\n";
    let body_edit = "#include \"api.h\"\nHWND h;\nint padding;\n";
    let directive_edit = "#include \"api.h\"\nHWND h;\nint padding;\n#define PAD 1\n";
    let files = MemoryFiles::new()
        .with_file("/p/handle.h", handle)
        .with_file("/p/api.h", "#include \"handle.h\"\nDECLARE_HANDLE(HWND);\n")
        .with_file("/p/main.cpp", main);
    let fixture = Memory::new("a-body-edit-keeps-the-program", &files);
    let mut session = fixture.session();
    session.did_open("/p/main.cpp", main);
    session.index_everything();

    // **The program is read once**, and it stops being owed for that root.
    let reading = session
        .read_a_looked_at_unit()
        .expect("the reader has a file open, so there is a program to read");
    assert!(
        reading.files >= 3,
        "the program is three files: {reading:?}"
    );
    assert!(
        session.the_wait_before_a_program_may_be_read().is_none(),
        "one program per root, until something changes its shape"
    );

    // **A body edit**: the file's text changed, the program's shape did not.
    session.did_change("/p/main.cpp", body_edit);
    assert!(
        session.the_wait_before_a_program_may_be_read().is_none(),
        "a declaration added to a body does not make the program owed again"
    );
    // …and the edited file is still read, by the per-file path its keystroke queued.
    session.advance(4);
    assert!(
        session
            .index()
            .summary(Path::new("/p/main.cpp"))
            .is_some_and(|summary| summary

                .declarations
                .iter()
                .any(|fact| fact.name == "padding")),
        "the keystroke's own file is read again, by the per-file path"
    );

    // **A directive edit**: every offset the timeline recorded moved, so the program is owed again.
    session.did_change("/p/main.cpp", directive_edit);
    assert!(
        session.the_wait_before_a_program_may_be_read().is_some(),
        "a directive that moved makes the program worth reading again"
    );
}

/// **Once a file is read as a program, the lookup-time guard filter has nothing left to do** — patch number two's
/// remaining work, measured.
///
/// The filter exists because a *summary* keeps both branches of every `#if`: `#if 0 struct Dead { … }; #endif` is a
/// declaration to a reader of the text and nothing to a compiler. A **rendering** has no branch left to remove, so a
/// file the session has read as a program answers from facts that are already the compiler's — and the filter becomes
/// a pass over candidates that never rejects one.
///
/// This test pins that on a fixture rather than on a project: the same questions are asked with the filter on and
/// off (`probes::set_no_guard_filter`, which exists for this measurement), and the answers must be identical. If they
/// ever differ, this file's reading is not the rendering and the patch has a user again.
#[test]
fn a_file_read_as_a_program_needs_no_guard_filter() {
    let cfg = "#define ON 1\n";
    let api = "#include \"cfg.h\"\n#if 0\nstruct Dead { int gone; };\n#endif\nstruct Live { int kept; };\n";
    let main = "#include \"api.h\"\nLive live;\n";
    let files = MemoryFiles::new()
        .with_file("/p/cfg.h", cfg)
        .with_file("/p/api.h", api)
        .with_file("/p/main.cpp", main);
    let fixture = Memory::new("no-guard-filter-needed", &files);
    let mut session = fixture.session();
    session.did_open("/p/main.cpp", main);
    session.index_everything();
    session
        .read_a_looked_at_unit()
        .expect("the reader has a file open, so there is a program to read");

    let ask = |session: &Session<_>| {
        let mut answers: Vec<String> = Vec::new();
        for name in ["Dead", "gone", "Live", "kept"] {
            let answer = match session.index().definitions(name, Path::new("/p/main.cpp")) {
                Known::Yes(found) => format!(
                    "{:?}",
                    found
                        .found
                        .iter()
                        .map(|one| (
                            one.file.to_string_lossy().to_string(),
                            one.fact.name.clone()
                        ))
                        .collect::<Vec<_>>()
                ),
                Known::Unknown(reason) => format!("unknown:{reason:?}"),
                Known::No => String::from("no"),
            };
            answers.push(format!("{name} = {answer}"));
        }
        answers
    };

    let with = ask(&session);
    session.index().forget_the_name_answers();
    crate::probes::set_no_guard_filter(true);
    let without = ask(&session);
    crate::probes::set_no_guard_filter(false);

    assert_eq!(
        with, without,
        "the filter changed an answer, so this file's reading is not the rendering: {with:?}"
    );
    assert!(
        !with.iter().any(|answer| answer.starts_with("Dead = yes")),
        "and the branch nobody takes is not an answer at all: {with:?}"
    );
}
/// **Where a file has been read as a program, that reading is the reading — not one answer beside another.**
///
/// The two declaration lists an index can hold for one file are not two views of one thing: the summary is the file
/// read *on its own* and a cooked reading is the file read **in a program**, and `_CRT_…`/`_GLIBCXX_…` decide
/// differently in the two. Measured on a real project, **1 095 declarations over 177 files** are in one list and not
/// the other (`tests/unit_read_probe.rs`). Offering both at once answers for two translation units with one question.
///
/// The fixture is that disagreement in one name: `api.h` declares `Live` one way when `FROM_THE_SOURCE` is defined and
/// another when it is not, so the file read on its own has one `Live` and the file read inside `main.cpp` has the
/// other. With the union, a lookup gets **both** — two declarations of one name, which is a list where a jump wants a
/// place. With the rendering as the reading, it gets the one its translation unit has.
#[test]
fn a_files_rendering_is_its_reading_and_not_one_answer_beside_another() {
    let api = "#ifdef FROM_THE_SOURCE\n\
               struct Live { int a; };\n\
               #else\n\
               struct Live { long b; };\n\
               #endif\n";
    let main = "#define FROM_THE_SOURCE 1\n#include \"api.h\"\nLive live;\n";
    let files = MemoryFiles::new()
        .with_file("/p/api.h", api)
        .with_file("/p/main.cpp", main);
    let fixture = Memory::new("the-rendering-is-the-reading", &files);
    let mut session = fixture.session();
    session.did_open("/p/main.cpp", main);
    session.index_everything();

    let taken = api.find("struct Live { int a; }").expect("the fixture");
    let not_taken = api.find("struct Live { long b; }").expect("the fixture");

    // **Before the program is read**: whatever the per-file reading produced, the one it did *not* produce is not an
    // answer for `main.cpp` — and that is the reading this change is about.
    let before = session
        .index()
        .definitions("Live", Path::new("/p/main.cpp"));
    println!("before the program read: {before:?}");

    session
        .read_a_looked_at_unit()
        .expect("the reader has a file open, so there is a program to read");

    // **One answer, and it is the branch this translation unit takes.** Two candidates here would mean the summary's
    // facts were offered beside the rendering's — the union this change removes.
    let found = session
        .index()
        .definitions("Live", Path::new("/p/main.cpp"));
    let Known::Yes(found) = found else {
        panic!("`Live` is declared in a header the source includes: {found:?}");
    };
    assert_eq!(
        found.found.len(),
        1,
        "the file has been read as a program, so its reading is the reading: {:?}",
        found
            .found
            .iter()
            .map(|one| one.fact.range)
            .collect::<Vec<_>>()
    );
    assert_eq!(
        found.found[0].fact.range.start_offset, taken,
        "the answer is the branch `FROM_THE_SOURCE` selects: {:?}",
        found.found[0].fact.range
    );
    assert_ne!(
        found.found[0].fact.range.start_offset, not_taken,
        "and not the one the file has when it is read on its own"
    );
}

/// **The same header, read in two translation units, answers each of them its own way** — §5 step two's acceptance.
///
/// `cfg.h` declares `X` one way when `A` is defined and another when it is not, so `a.cpp` (which defines it before
/// the include) and `b.cpp` (which does not) read **different** `X` from the same bytes. The index keeps a reading
/// **per program** (`Readings`), and a lookup picks by the asking file's program — the `env_hash` of §5 step two.
/// Before that, the file kept the *last* program's reading and this test answered `b.cpp` with what `a.cpp` compiled.
#[test]
fn a_header_read_in_two_programs_answers_each_its_own_way() {
    let cfg = "#ifdef A\nstruct X { int from_a; };\n#else\nstruct X { long from_b; };\n#endif\n";
    let a = "#define A 1\n#include \"cfg.h\"\n";
    let b = "#include \"cfg.h\"\n";
    let files = MemoryFiles::new()
        .with_file("/p/cfg.h", cfg)
        .with_file("/p/a.cpp", a)
        .with_file("/p/b.cpp", b);
    let fixture = Memory::new("a-header-in-two-programs", &files);
    let mut session = fixture.session();
    session.did_open("/p/a.cpp", a);
    session.did_open("/p/b.cpp", b);
    session.index_everything();

    // **Both programs**, one per call — the schedule reads one at a time and the two roots are both open.
    let mut read = Vec::new();
    while let Some(reading) = session.read_a_looked_at_unit() {
        read.push(reading.root.clone());
    }
    assert!(read.len() >= 2, "both translation units are read: {read:?}");

    let from_a = session.index().definitions("X", Path::new("/p/a.cpp"));
    let from_b = session.index().definitions("X", Path::new("/p/b.cpp"));
    let offset = |known: &Known<crate::ProjectDefinitions>| match known {
        Known::Yes(found) => found.found.first().map(|one| one.fact.range.start_offset),
        _ => None,
    };
    assert_eq!(
        offset(&from_a),
        Some(cfg.find("struct X { int from_a; }").expect("the fixture")),
        "`a.cpp` defines `A`, so it sees the `int` branch: {from_a:?}"
    );
    assert_eq!(
        offset(&from_b),
        Some(cfg.find("struct X { long from_b; }").expect("the fixture")),
        "`b.cpp` does not, so it sees the `long` one: {from_b:?}"
    );
}

/// **The diagnostics of a file whose error is in a branch nobody takes.**
///
/// The two readings disagree here, and that is the whole reason [`Session::diagnostics`] exists: the file's own
/// text has an unclosed class inside `#if OFF`, so the raw reading reports it (correctly — the *text* says so),
/// while a compiler never sees that branch at all. Publishing the raw answer would put a red squiggle on code
/// that is not compiled, which is the false positive the cooked reading removes.
#[test]
fn a_branch_nobody_takes_reports_nothing_once_the_file_is_cooked() {
    let main = "#include \"cfg.h\"\n#if OFF\nstruct Unclosed { int x;\n#endif\nint ok;\n";
    let files = MemoryFiles::new()
        .with_file("/p/cfg.h", "#define OFF 0\n")
        .with_file("/p/main.cpp", main);
    let fixture = Memory::new("a-branch-nobody-takes", &files);
    let mut session = fixture.session();

    // **Before the file is cooked there is no answer, and that is the contract now.** This used to assert a
    // `Raw` reading — the file's own text — whose single error was the unclosed class in the untaken branch. That
    // reading is gone: an untaken branch is not compiled, so reporting an error inside one is reporting an error
    // about a program that does not exist. The file is *held* rather than opened, so nothing has asked for a
    // rendering and there is nothing to answer from.
    session.load("/p/main.cpp");
    assert!(
        session.diagnostics("/p/main.cpp").is_none(),
        "nothing has read this file as a compiler reads it, so there is nothing to say about it"
    );

    session.did_open("/p/main.cpp", main);
    session.index_everything();

    let cooked = session.diagnostics("/p/main.cpp").expect("the file reads");
    assert_eq!(
        cooked.reading,
        super::DiagnosticReading::Cooked,
        "the index holds a reading of this file now"
    );
    assert!(
        cooked.errors.is_empty(),
        "and the branch it complained about is not in it: {cooked:?}"
    );
    assert_eq!(
        cooked.unplaced, 0,
        "nothing was hidden from the reader either"
    );
}

/// **A cooked error's offsets are offsets in the file**, not in the rendering it was found in.
///
/// The two coordinate systems are different here, which is what makes the claim checkable: the file writes
/// `DECLARE_HANDLE(HWND);` and the rendering has the struct and the typedef the macro expands to, so an offset
/// taken from the rendering lands past the end of the file. The evidence that the expansion really happened is
/// in the same test — the declaration the file never wrote (`HWND__`) — because a fixture where the macro stayed
/// unexpanded would make a rendering offset and a file offset the same number and the assertion worthless.
#[test]
fn a_cooked_error_is_placed_in_the_file_not_in_the_rendering() {
    let handle = "#define DECLARE_HANDLE(name) struct name##__ { int unused; }; \
                      typedef struct name##__ *name\n";
    let main = "#include \"handle.h\"\nDECLARE_HANDLE(HWND);\nstruct Unclosed { int x;\n";
    let files = MemoryFiles::new()
        .with_file("/p/handle.h", handle)
        .with_file("/p/main.cpp", main);
    let fixture = Memory::new("cooked-errors-are-file-offsets", &files);
    let mut session = fixture.session();

    session.did_open("/p/main.cpp", main);
    session.index_everything();

    let declarations = session
        .index()
        .cooked_declarations(Path::new("/p/main.cpp"))
        .expect("the file was cooked");
    assert!(
        declarations.iter().any(|fact| fact.name == "HWND__"),
        "the rendering is not the file's text: the macro declared a struct this file never wrote: {:?}",
        declarations
            .iter()
            .map(|fact| &fact.name)
            .collect::<Vec<_>>()
    );

    let found = session.diagnostics("/p/main.cpp").expect("the file reads");
    assert_eq!(found.reading, super::DiagnosticReading::Cooked);
    assert_eq!(found.errors.len(), 1, "{found:?}");

    let error = &found.errors[0];
    let unclosed = main.find("struct Unclosed").expect("the fixture writes it");
    assert!(
        error.start >= unclosed,
        "the error is about the line that is still unclosed: {error:?}"
    );
    assert!(
        error.end <= main.len(),
        "and it is a position in the file — a rendering offset would be past its end: {error:?}"
    );
    assert_eq!(found.unplaced, 0, "nothing had to be hidden: {found:?}");
}

/// **What is cooked is what is looked at**: the open files and the files their own text names, plus any file a
/// request is about — not a closure, and not a project.
///
/// The reader who needed the old behaviour was the diagnostic pass, which publishes an answer for every indexed
/// file — but "every indexed file" is the **closure** of an open file, and on a real project that was 138 files:
/// measured at **11.7 s** of the startup, every time, cache or no cache, for the difference between 999 and 1000
/// declarations. A file nobody looks at is answered from its own text, and the diagnostic layer says so
/// ([`super::DiagnosticReading::Raw`]) rather than pretending otherwise.
#[test]
fn a_file_nobody_looked_at_is_not_cooked_and_one_a_request_names_is() {
    let main = "#include \"a.h\"\n#include \"b.h\"\n#include \"c.h\"\nA a; B b; C c;\n";
    let files = MemoryFiles::new()
        .with_file("/p/a.h", "struct A { int x; };\n")
        .with_file("/p/b.h", "struct B { int x; };\n")
        .with_file("/p/c.h", "struct C { int x; };\n")
        .with_file("/p/main.cpp", main)
        .with_file("/p/other.cpp", "#include \"a.h\"\nvoid g() { }\n");
    let fixture = Memory::new("only-what-is-looked-at-is-cooked", &files);
    let mut session = fixture.session();

    // A file the caller knows about, in the rest half of the queue. Nothing opens it, nothing looks at it.
    session.add_project_files([PathBuf::from("/p/other.cpp")]);
    session.did_open("/p/main.cpp", main);

    session.index_everything();
    assert_eq!(session.pending_work(), 0, "both kinds of work are done");

    for looked_at in ["/p/main.cpp", "/p/a.h", "/p/b.h", "/p/c.h"] {
        assert!(
            session
                .index()
                .cooked_declarations(Path::new(looked_at))
                .is_some(),
            "{looked_at} is what the reader is looking at"
        );
    }
    assert!(
        session
            .index()
            .cooked_declarations(Path::new("/p/other.cpp"))
            .is_none(),
        "and a file nobody opened, nobody included and no request named has no reading"
    );

    // A request names it: that is what the shell does before every query, and the reading follows.
    session.want_cooked_reading(Path::new("/p/other.cpp"));
    session.index_everything();
    assert!(
        session
            .index()
            .cooked_declarations(Path::new("/p/other.cpp"))
            .is_some(),
        "the file a request is about is read the way a compiler reads it"
    );
}

/// **Editing a header invalidates the reading of every file that had one**, and those come back.
///
/// The set is every dependent ([`crate::ProjectIndex::dependents_of`]), because a stale reading is a wrong answer
/// rather than a missing one — and it is *only* the dependents that had a reading, because a file nobody has
/// looked at has nothing to invalidate and asking for a new reading would cook a file nobody asked about.
#[test]
fn editing_a_header_invalidates_the_readings_that_depend_on_it() {
    let ns = "#define BEGIN_NS namespace one {\n#define END_NS }\n";
    let api = "#include \"ns.h\"\nBEGIN_NS struct Widget { int size; }; END_NS\n";
    let other = "#include \"api.h\"\nWidget w;\n";
    let files = MemoryFiles::new()
        .with_file("/p/ns.h", ns)
        .with_file("/p/api.h", api)
        .with_file("/p/other.cpp", other);
    let fixture = Memory::new("a-cooked-file-goes-stale", &files);
    let mut session = fixture.session();

    session.add_project_files([PathBuf::from("/p/other.cpp")]);
    session.did_open("/p/api.h", api);
    // A request names `other.cpp`, so it has a reading to lose — which is what this test is about.
    session.want_cooked_reading(Path::new("/p/other.cpp"));
    session.index_everything();
    assert!(
        session
            .index()
            .cooked_declarations(Path::new("/p/other.cpp"))
            .is_some(),
        "the fixture starts with the dependent cooked"
    );

    // The header the macro is written in opens the *other* namespace.
    let changed = "#define BEGIN_NS namespace two {\n#define END_NS }\n";
    session.did_open("/p/ns.h", changed);

    for stale in ["/p/other.cpp", "/p/api.h"] {
        assert!(
            session
                .index()
                .cooked_declarations(Path::new(stale))
                .is_none(),
            "{stale} was read as the namespace the macro used to open"
        );
    }

    session.index_everything();
    assert!(
        matches!(
            session
                .index()
                .definition("two::Widget", Path::new("/p/other.cpp")),
            Known::Yes(_)
        ),
        "and it is read again, as the new macro says: {:?}",
        session
            .index()
            .definition("two::Widget", Path::new("/p/other.cpp"))
    );
}

/// **A file that defines no macros invalidates nothing**, which is what keeps the common edit cheap.
///
/// The environment is macros: a header that only declares things cannot change what any file that includes it
/// expands to, so its dependents' readings are still readings of the truth. Without this gate, an edit anywhere
/// in a project would drop the readings of everything that includes the file — and in a standard library that is
/// most of the project, on every keystroke.
#[test]
fn editing_a_file_that_defines_no_macros_keeps_its_dependents_readings() {
    let api = "struct Widget { int size; };\n";
    let other = "#include \"api.h\"\nWidget w;\n";
    let files = MemoryFiles::new()
        .with_file("/p/api.h", api)
        .with_file("/p/other.cpp", other);
    let fixture = Memory::new("a-declaration-is-not-an-environment", &files);
    let mut session = fixture.session();

    session.add_project_files([PathBuf::from("/p/other.cpp")]);
    session.did_open("/p/api.h", api);
    session.want_cooked_reading(Path::new("/p/other.cpp"));
    session.index_everything();

    // The same declarations with one more member: the file changed, its macros did not.
    session.did_open("/p/api.h", "struct Widget { int size; int weight; };\n");

    assert!(
        session
            .index()
            .cooked_declarations(Path::new("/p/other.cpp"))
            .is_some(),
        "nothing in this file is part of anyone's environment"
    );
    assert!(
        session
            .index()
            .cooked_declarations(Path::new("/p/api.h"))
            .is_none(),
        "…while the file itself is re-read, which is not a question about macros"
    );
}

/// **The first `#define` a header gets reaches the files that include it.**
///
/// The gate this replaced asked whether the header defined macros *before* the edit — so the edit that added the
/// header's first macro was the one edit it could not see, and every includer went on answering from a reading
/// built when the macro did not exist.
#[test]
fn the_first_macro_a_header_defines_invalidates_the_readings_that_include_it() {
    let api = "#include \"ns.h\"\nBEGIN_NS struct Widget { int size; }; END_NS\n";
    let other = "#include \"api.h\"\nWidget w;\n";
    let files = MemoryFiles::new()
        .with_file("/p/ns.h", "// nothing to say yet\n")
        .with_file("/p/api.h", api)
        .with_file("/p/other.cpp", other);
    let fixture = Memory::new("the-first-macro-of-a-header", &files);
    let mut session = fixture.session();

    session.add_project_files([PathBuf::from("/p/other.cpp")]);
    session.want_cooked_reading(Path::new("/p/other.cpp"));
    session.index_everything();
    assert!(
        session
            .index()
            .cooked_declarations(Path::new("/p/other.cpp"))
            .is_some(),
        "the fixture starts with the dependent cooked"
    );

    session.did_open(
        "/p/ns.h",
        "#define BEGIN_NS namespace one {\n#define END_NS }\n",
    );

    assert!(
        session
            .index()
            .cooked_declarations(Path::new("/p/other.cpp"))
            .is_none(),
        "the reading was built when `BEGIN_NS` meant nothing"
    );
}

/// **Typing in a file's body does not cost the walk of its closure, and typing above the body does.**
///
/// The numbers are [`Session::unit_stats`]'s: `walked` is a closure read and a timeline built,
/// `from_disk` is the entry that replaces it.
///
/// The fixture is two sessions over one cache directory, because the disk entry is the thing under test: a
/// unit walked by the first session is what the second has to be served, and the in-memory table would hide
/// whether that happened.
///
/// # Why the root used to be walked on every keystroke
///
/// A unit's closure includes the file it is rooted at, and the key was every file's whole text — so the file
/// being typed into invalidated its own unit on every character. The key is now that file's **preamble**: see
/// [`crate::RootKey`] for what that is and why the tail is checked separately.
#[test]
fn typing_in_a_body_does_not_cost_the_walk_a_translation_unit_is() {
    let main = "#include \"b.h\"\nint main() { return A; }\n";
    let files = MemoryFiles::new()
        .with_file("/p/a.h", "#pragma once\n#define A 1\n")
        .with_file(
            "/p/b.h",
            "#pragma once\n#include \"a.h\"\nstruct B { int b; };\n",
        )
        .with_file("/p/main.cpp", main);
    let fixture = Memory::new("a-body-edit-is-not-a-walk", &files);

    // **The first session walks, because there is nothing to reuse** — and writes the entry for the next one.
    // `index_everything` is the whole of the work: it reads the queue *and* drains the cooking backlog, which
    // is where a unit is reached.
    let mut first = fixture.session();
    first.add_project_files([PathBuf::from("/p/main.cpp")]);
    first.did_open("/p/main.cpp", main);
    first.index_everything();
    assert!(
        first
            .index()
            .cooked_declarations(Path::new("/p/main.cpp"))
            .is_some(),
        "the fixture cooked the file, which is what walks its unit"
    );
    assert!(
        first.unit_stats().walked > 0,
        "…and nothing was on disk to serve it: {:?}",
        first.unit_stats()
    );
    // **Nothing is written to disk for this any more.** `tu/` held built `TranslationUnit`s, and a stored
    // timeline outlives the files it was built from — so the walk runs every session and what a session reuses is
    // its own memory (`held_units`), not a previous run's file. The property the cases below assert — a keystroke
    // does not cost a walk — is what remains, and it is what the entry was ever for.

    // **One fresh session per question**, because the in-memory table would otherwise answer and hide whether
    // the entry on disk was usable at all — and the entry on disk is the thing under test: it is what has to
    // survive a keystroke, for a session that has not seen the file before and for the one that has.
    let over_a_fresh_session = |what: &str, text: &str| {
        let mut session = fixture.session();
        session.add_project_files([PathBuf::from("/p/main.cpp")]);
        session.did_open("/p/main.cpp", text);
        session.index_everything();
        let stats = session.unit_stats();
        assert!(
            session
                .index()
                .cooked_declarations(Path::new("/p/main.cpp"))
                .is_some(),
            "{what}: the fixture cooked the file"
        );
        stats
    };

    // **The text that was walked**, as a fresh session reads it.
    let unedited = over_a_fresh_session("unedited", main);
    let walked_baseline = unedited.walked;
    // **A fresh session walks, because there is no timeline cache on disk any more** — `tu/` is gone with the
    // rest of the per-directory cache: a stored timeline outlives the files it was built from, which is a
    // correctness question rather than a speed one. What survives is what the cases below measure: a keystroke must
    // not cost *more* than the fresh session already pays.
    assert_eq!(
        unedited.walked, walked_baseline,
        "the entry the first session wrote answers for the text it was walked from: {unedited:?}"
    );
    assert!(
        unedited.walked > 0,
        "…and the fresh session walked, because no timeline survives a session any more: {unedited:?}"
    );

    // **A character typed into the body.** Nothing above the file's last directive moves, and nothing below it
    // can be read by a walk — so the unit the first session built is still this file's unit. **This is the
    // acceptance of stage 1**: before the root of a unit was keyed on its preamble, this session walked.
    let typed = format!("{main}\nint more() {{ return A; }}\n");
    let edited = over_a_fresh_session("a body edit", &typed);
    assert_eq!(
        edited.walked, walked_baseline,
        "a body edit must not cost more walks than a fresh session already pays: {edited:?}"
    );
    assert!(
        edited.walked > 0,
        "…and the body edit walked, as every fresh session now does: {edited:?}"
    );

    // **An `#include` above the body is a different matter**: it moves the preamble, which is the key.
    let with_an_include = "#include \"a.h\"\n#include \"b.h\"\nint main() { return A; }\n";
    let moved = over_a_fresh_session("an include above the body", with_an_include);
    assert!(
        moved.walked > 0,
        "an edit above the bound is an edit to what the walk reads: {moved:?}"
    );
}

/// **A file this session already has a unit for is read *with* that unit's environment, and the second pass is
/// not paid for it.**
///
/// What it buys is that the *first* parse is the right one — which is the thing that has to be true
/// before the rendering can be skipped, because the rendering is what repairs a reading made
/// without an environment. Two sessions, and the difference between them is the whole claim:
///
/// ```text
///   cold   nothing is in memory, so there is no environment to read the file against — today's path, and the
///          file goes to the second pass like any other file that was parsed
///   warm   the unit is in memory, so the file is read once *with* its environment, and the pass that exists
///          only to repair a reading made without one has nothing to do
/// ```
///
/// # The sharper assertion, and why it is not here
///
/// What the environment is *for* is the scope: `BEGIN_NS` is `namespace one {` to a compiler, so the sharper
/// test is "`one::Widget` is in the index after one step, with no second pass to fix it". It cannot be written
/// today, and the reason is not this change: **`one::Widget` is not in the index after a full
/// `index_everything` either** — the cooked reading places `Widget` at file scope, with the macro unexpanded.
/// That is one of the five failures `status.md` §6 records, and
/// `editing_a_header_invalidates_the_readings_that_depend_on_it` fails through exactly this fixture and
/// exactly this name.
///
/// So this asserts what the change is about — **which files the second pass is handed** — and the doc comment
/// is the note to tighten it into the scope assertion the moment that defect is fixed. A test that asserted the
/// scope now would be red for a reason that has nothing to do with the flag, which is the shape of test
/// `status.md` §6 warns about in its second rule.
#[test]
fn a_file_read_back_through_its_own_unit_is_not_read_again_by_the_second_pass() {
    let ns = "#define BEGIN_NS namespace one {\n#define END_NS }\n";
    let api = "#include \"ns.h\"\nBEGIN_NS struct Widget { int size; }; END_NS\n";
    let typed = format!("{api}void body() {{ int inside; }}\n");
    let files = MemoryFiles::new()
        .with_file("/p/ns.h", ns)
        .with_file("/p/api.h", api);
    let fixture = Memory::new("a-file-is-read-with-its-environment", &files);

    let second_pass_has = |session: &Session<MemoryFiles>| {
        session
            .parsed_since_the_last_pass
            .iter()
            .any(|queued| queued.ends_with("api.h"))
    };

    // **Cold**: nothing has been walked, so there is no environment in hand.
    let mut cold = fixture.session();
    cold.did_open("/p/api.h", api);
    cold.advance(1);
    assert!(
        second_pass_has(&cold),
        "with no unit in memory the file is read the way it always was, and the pass still has it: {:?}",
        cold.parsed_since_the_last_pass
    );

    // **Warm**: the fixture has read the file once, so its unit is in memory.
    let mut warm = fixture.session();
    warm.did_open("/p/api.h", api);
    warm.index_everything();
    assert!(
        holds_a_unit_for(&warm, "/p/api.h"),
        "the fixture walked a unit for the file"
    );
    // **And this is the assertion to tighten.** `one::Widget` is what the environment is *for* — it is now in
    // the index (`scope: Some("one")`, the macro's `namespace` placed) where before this round it was
    // `NotDeclaredHere`, and a test that pinned that would be the sharpest statement of what was fixed. It is
    // deliberately not asserted here, because the same name is the subject of two of the failures
    // `status.md` §6 records, and a red test with two possible causes is worse than a narrow green one.
    //
    // What *is* asserted is this change's own subject: which files the second pass is handed.
    //
    // **`advance(64)` and not `advance(1)`**, because that is the path where this used to be dead. With more
    // than one step to take, `advance` prepares a *wave* on the read path and hands the file's summary back
    // through `index_one`'s `Some` arm — where no environment is available and none is looked for. The
    // mechanism was written, tested against `advance(1)`, and never once reached on the pump's path. See
    // `Session::advance` for what now keeps such a file out of the wave.
    warm.did_change("/p/api.h", &typed);
    warm.advance(64);

    assert!(
        !second_pass_has(&warm),
        "read with the environment of its own closure, so the pass has nothing to repair: {:?}",
        warm.parsed_since_the_last_pass
    );
}

/// **A wave with nothing left to parse still carries the timelines the drain will need.**
///
/// The last stretch of a start-up is the **drain phase**: the index queue is empty and the pump commits re-reads
/// slice after slice, so every one of those waves has nothing to prepare. `prepare_a_wave` used to return early
/// in exactly that state and hand the drain `units: []` — and `prepare_the_re_read` reads that as *"a caller
/// with no timelines"* and changes shape: it copies every indexed file's text into a map and asks a question
/// about every `#define` in the project, and its candidate scan falls back to a closure walk per file.
///
/// Measured on `EmmyLuaCodeStyle` (1761 files): twelve such calls — four files each — took **28 s of a 49 s**
/// cold start and **37 s of a 47 s** warm one, while the index itself was 4–16 s. Handing the drain its
/// timelines is what took the warm start to **11.6 s** and the cold one to **20.6 s**.
///
/// The state is built the way the pump reaches it: more files parsed in one wave than the second pass takes at
/// once, so the queue empties with a backlog still standing.
#[test]
fn a_wave_with_nothing_to_parse_still_carries_the_drains_timelines() {
    // **Four more than the second pass takes at once**, so the queue empties with a backlog still standing — the
    // state this test is about. The fixture used to be eight, which was "one more than four".
    let count = crate::session::RE_READ_SLICE + 4;
    let files = (0..count).fold(MemoryFiles::new(), |files, at| {
        files.with_file(format!("/p/f{at}.cpp"), format!("int value_{at} = {at};\n"))
    });
    let fixture = Memory::new("a-wave-carries-its-drain-timelines", &files);
    let mut session = fixture.session();
    session.add_project_files((0..count).map(|at| PathBuf::from(format!("/p/f{at}.cpp"))));

    // One wave over all of them: the parse happens here, and the commit takes the second pass`s slice, leaving
    // four behind — the queue-empty, backlog-not-empty state.
    // leaving four behind — the queue-empty, backlog-not-empty state.
    let wave = session.prepare_a_wave(count);
    session.commit_a_wave(wave, count);
    assert_eq!(
        session.pending(),
        0,
        "the fixture is the drain phase: nothing left to index"
    );
    assert!(
        !session.parsed_since_the_last_pass.is_empty(),
        "and the second pass still has files: {:?}",
        session.parsed_since_the_last_pass
    );

    let next = session.prepare_a_wave(8);
    assert!(
        next.prepared.is_empty(),
        "there is nothing to parse, which is the state this test is about"
    );
    assert_eq!(
        next.units.len(),
        session.parsed_since_the_last_pass.len().min(4),
        "and the drain's timelines are still prepared, one per file it will re-read"
    );
}

/// **A quoted include is verified in the directory it is asked from** — the risk a remembered search carries.
///
/// `SummaryStore::where_it_resolves_now` keeps one answer per **question**, and for an angled include the question
/// is the spelling alone. A quoted one is not: `#include "x.h"` from `/p/a` and from `/p/b` resolve to two
/// different files, so a memo keyed on the spelling would answer the second directory with the first's answer,
/// the stored summary would stop "holding", and every start would rebuild it — a cache that silently stops
/// working. This pins the direction that matters: both summaries are reused.
#[test]
fn a_quoted_include_is_verified_in_the_directory_it_is_asked_from() {
    let files = MemoryFiles::new()
        .with_file("/p/a/x.h", "int from_a;\n")
        .with_file("/p/b/x.h", "int from_b;\n")
        .with_file("/p/a/one.cpp", "#include \"x.h\"\n")
        .with_file("/p/b/two.cpp", "#include \"x.h\"\n");
    let fixture = Memory::new("a-quoted-include-is-per-directory", &files);
    let roots = [PathBuf::from("/p/a/one.cpp"), PathBuf::from("/p/b/two.cpp")];

    // The first session builds the four summaries and writes them down.
    let mut first = fixture.session();
    first.add_project_files(roots.iter().cloned());
    first.index_everything();
    assert!(
        first.stats().rebuilt >= 2,
        "the fixture starts cold: {:?}",
        first.stats()
    );

    // The second answers every one of them from disk, which is only true when each verification accepted the
    // resolution its own directory recorded.
    let mut second = fixture.session();
    second.add_project_files(roots.iter().cloned());
    let steps = second.advance(16);
    let outcomes: Vec<String> = steps
        .iter()
        .map(|step| {
            format!(
                "{}: {:?}",
                step.path.file_name().unwrap_or_default().to_string_lossy(),
                step.outcome
            )
        })
        .collect();
    assert!(
        steps.iter().all(|step| step.outcome == StepOutcome::Reused),
        "nothing may be rebuilt from a cache that holds every one of these files: {outcomes:?}"
    );
}

/// **An `#include` added to a header that defines nothing is still a change to its includers' environment.**
#[test]
fn an_include_added_to_a_header_invalidates_the_readings_that_include_it() {
    let files = MemoryFiles::new()
        .with_file("/p/macros.h", "#define ANSWER 42\n")
        .with_file("/p/api.h", "int declared;\n")
        .with_file("/p/other.cpp", "#include \"api.h\"\nint x = ANSWER;\n");
    let fixture = Memory::new("an-include-is-an-environment", &files);
    let mut session = fixture.session();

    session.add_project_files([PathBuf::from("/p/other.cpp")]);
    session.want_cooked_reading(Path::new("/p/other.cpp"));
    session.index_everything();
    assert!(
        session
            .index()
            .cooked_declarations(Path::new("/p/other.cpp"))
            .is_some()
    );

    session.did_open("/p/api.h", "#include \"macros.h\"\nint declared;\n");

    assert!(
        session
            .index()
            .cooked_declarations(Path::new("/p/other.cpp"))
            .is_none(),
        "`ANSWER` is now in force where it was not"
    );
}

/// **Typing below the last directive keeps the edited file's unit; touching a directive drops it — and it
/// drops that one, not the table.**
///
/// A unit is a timeline of directives, so what decides whether an edit can have moved it is whether any directive
/// did — nearly every keystroke is in a body, and re-walking the closure for each of them was most of what a
/// keystroke cost.
///
/// Dropping the whole table was the first version of this rule and it invalidated up to `MAX_UNITS`
/// units to invalidate one — including, on the next keystroke, the one the file needed. A file that
/// merely *includes* the edited one has a timeline of its own, and it is still the same directives
/// at the same offsets: `ns.h` knows nothing about `api.h`.
#[test]
fn a_unit_survives_typing_in_a_body_and_not_a_change_to_a_directive() {
    let ns = "#define BEGIN_NS namespace one {\n#define END_NS }\n";
    let api = "#include \"ns.h\"\nBEGIN_NS struct Widget { int size; }; END_NS\n";
    let files = MemoryFiles::new()
        .with_file("/p/ns.h", ns)
        .with_file("/p/api.h", api);
    let fixture = Memory::new("a-unit-survives-a-body", &files);
    let mut session = fixture.session();

    session.did_open("/p/api.h", api);
    session.index_everything();
    assert!(
        holds_a_unit_for(&session, "/p/api.h"),
        "the fixture cooked the file, which walked a unit"
    );
    assert!(
        holds_a_unit_for(&session, "/p/ns.h"),
        "…and the header it includes, whose closure does not contain `api.h`"
    );

    let typed = format!("{api}void body() {{ int inside; }}\n");
    session.did_change("/p/api.h", &typed);
    assert!(
        holds_a_unit_for(&session, "/p/api.h"),
        "a body was typed below the last directive"
    );

    let typed_more = format!("{api}void body() {{ int inside; int more; }}\n");
    session.did_change("/p/api.h", &typed_more);
    assert!(holds_a_unit_for(&session, "/p/api.h"), "and again");

    session.did_change(
        "/p/api.h",
        &format!("#include \"ns.h\"\n#define EXTRA 1\n{typed_more}"),
    );
    assert!(
        !holds_a_unit_for(&session, "/p/api.h"),
        "a directive appeared, so `api.h`'s timeline is out of date"
    );
    assert!(
        holds_a_unit_for(&session, "/p/ns.h"),
        "…and `ns.h`'s is not: nothing in its closure moved, and dropping it would be a walk bought for nothing"
    );
}

/// **Is a translation unit held for this file?** — asked through the table's own lock, and per file, because
/// what an edit invalidates is one file's timeline rather than the whole table.
///
/// Four assertions here used to call `units.is_empty()` on the `Mutex` itself, so the *test* had stopped
/// compiling when the field gained a lock; they were then rewritten to ask about the whole table, which was
/// right while an edit cleared it and is wrong now that it does not.
fn holds_a_unit_for(session: &Session<MemoryFiles>, path: &str) -> bool {
    session
        .units
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
        .held
        .contains_key(&queue_key(Path::new(path)))
}

/// **A cook that cannot succeed is not queued again by a request** — the loop an editor reported as "one core, and
/// the diagnostics flashing".
///
/// Measured from a real session's log before this test existed: `index slice: … 4 to cook, 2 left` every ~250 ms for
/// minutes after the index had drained. The cause was the pair this test pins down: [`Session::want_cooked_reading`]
/// *cleared* the refusal (a request is not evidence that the reason changed), and the pump then claimed, refused and
/// the next pull cleared it again.
#[test]
fn a_cook_that_cannot_succeed_is_not_queued_again_by_a_request() {
    let files = MemoryFiles::new().with_file("/p/a.cpp", "int a;\n");
    let fixture = Memory::new("a-refused-cook-is-not-requeued", &files);
    let mut session = fixture.session();
    session.index_everything();

    // A file no summary describes: `materials_for` answers `None` for it, which is the state a cook cannot serve.
    session.want_cooked_reading(Path::new("/p/absent.cpp"));
    let claimed = session.claim_cooking(4);
    assert_eq!(claimed.len(), 1, "the request queued it once");
    let built = session.materials_for(claimed.clone());
    assert!(
        built.is_empty(),
        "a file the index cannot describe has no materials to cook"
    );
    session.refuse_the_cooks_that_built_nothing(&claimed, &[]);
    assert_eq!(
        session.pending_cooking(),
        0,
        "the refused file left the queue"
    );

    // **The request that names it again must not put it back.**
    session.want_cooked_reading(Path::new("/p/absent.cpp"));
    assert_eq!(
        session.pending_cooking(),
        0,
        "a request does not resurrect a refusal — that was the loop"
    );

    // A change to the text is the one thing that asks for a retry.
    session.did_change(Path::new("/p/absent.cpp"), "int b;\n");
    assert_eq!(
        session.pending_cooking(),
        1,
        "an edit is what makes a refusal worth retrying"
    );
}
/// **Editing a header invalidates the reading of the open file that includes it.**
///
/// A file's cooked reading is a reading of its *environment* as well as of its text: `BEGIN_NS` opening a
/// namespace is a fact about `ns.h`, and a reading of `api.h` built before `ns.h` changed would keep answering
/// the old way — a jump to a scope that no longer exists, which is a wrong answer rather than a missing one.
#[test]
fn editing_a_header_stales_the_cooked_reading_of_a_file_that_includes_it() {
    let files = MemoryFiles::new()
        .with_file(
            "/p/ns.h",
            "#define BEGIN_NS namespace one {\n#define END_NS }\n",
        )
        .with_file(
            "/p/api.h",
            "#include \"ns.h\"\nBEGIN_NS struct Widget { int size; }; END_NS\n",
        );
    let fixture = Memory::new("a-header-edit-stales-readings", &files);
    let mut session = fixture.session();

    session.did_open(
        "/p/api.h",
        "#include \"ns.h\"\nBEGIN_NS struct Widget { int size; }; END_NS\n",
    );
    session.index_everything();
    assert!(
        matches!(
            session
                .index()
                .definition("one::Widget", Path::new("/p/api.h")),
            Known::Yes(_)
        ),
        "the fixture reads as the header says: {:?}",
        session
            .index()
            .definition("one::Widget", Path::new("/p/api.h"))
    );

    // The header changes the namespace it opens. `api.h`'s text does not change at all — what changes is what
    // its environment says, which is exactly the dependency a per-file invalidation would miss.
    session.did_change(
        "/p/ns.h",
        "#define BEGIN_NS namespace two {\n#define END_NS }\n",
    );
    assert!(
        session.pending_cooking() > 0,
        "the open file that includes it is marked for cooking again"
    );
    session.index_everything();

    assert!(
        matches!(
            session
                .index()
                .definition("two::Widget", Path::new("/p/api.h")),
            Known::Yes(_)
        ),
        "and the new reading is the one in the index: {:?}",
        session
            .index()
            .definition("two::Widget", Path::new("/p/api.h"))
    );
    assert!(
        session
            .index()
            .cooked_declarations(Path::new("/p/api.h"))
            .is_some_and(|facts| facts

                .iter()
                .any(|fact| fact.qualified_name() == "two::Widget")),
        "the stale reading was replaced, not kept beside it"
    );
}

#[test]
fn a_buffer_is_the_text_the_analysis_reads() {
    // The whole reason an editor needs an overlay: the file on disk says `old`, the user is typing `fresh`, and
    // an analysis that answered about the disk would answer about code that no longer exists.
    let files = MemoryFiles::new()
        .with_file("/p/widget.h", "struct Widget { int old; };\n")
        .with_file(
            "/p/main.cpp",
            "#include \"widget.h\"\nvoid f() { Widget w; }\n",
        );
    let fixture = Memory::new("buffer-is-the-text", &files);
    let mut session = fixture.session();

    session.did_open("/p/widget.h", "struct Widget { int fresh; };\n");
    session.did_open(
        "/p/main.cpp",
        "#include \"widget.h\"\nvoid f() { Widget w; }\n",
    );
    session.index_everything();

    let view = session.view("/p/main.cpp").expect("the file reads");
    let at = view
        .source
        .find("Widget w")
        .expect("the use is in the text");

    match session.definition(&view, ReadingOffset::new(at)) {
        Known::Yes(found) => {
            assert_eq!(found.file, Path::new("/p/widget.h"));
            assert_eq!(found.fact.name, "Widget");
        }
        other => panic!("the buffer's declaration should be found, got {other:?}"),
    }

    // And the members are the buffer's, which is the half a definition jump cannot show.
    match session.members_of(&view, "Widget") {
        Known::Yes(members) => {
            let names: Vec<&str> = members
                .own()
                .map(|member| member.fact.name.as_str())
                .collect();
            assert_eq!(
                names,
                ["fresh"],
                "the disk says `old` and the disk is not the text"
            );
        }
        other => panic!("the buffer's class should have members, got {other:?}"),
    }

    assert_eq!(
        fixture.text("/p/widget.h").as_deref(),
        Some("struct Widget { int fresh; };\n")
    );
}

#[test]
fn a_buffer_that_has_never_been_saved_is_a_file_like_any_other() {
    // A file the user has created and not saved has no path on disk at all. The overlay answers for it, the
    // include resolves to it, and its summary is built from text no filesystem has seen.
    let files = MemoryFiles::new().with_file(
        "/p/main.cpp",
        "#include \"widget.h\"\nvoid f() { Widget w; }\n",
    );
    let fixture = Memory::new("unsaved", &files);
    let mut session = fixture.session();

    session.did_open("/p/widget.h", "struct Widget { int size; };\n");
    session.did_open(
        "/p/main.cpp",
        "#include \"widget.h\"\nvoid f() { Widget w; }\n",
    );
    assert!(
        session.index_everything() >= 2,
        "both the buffer and its includer"
    );

    let view = session.view("/p/main.cpp").expect("the file reads");
    let at = view
        .source
        .find("Widget w")
        .expect("the use is in the text");
    assert!(
        matches!(session.definition(&view, ReadingOffset::new(at)), Known::Yes(found) if found.file == Path::new("/p/widget.h")),
        "a buffer no file has answers as the declaration's file"
    );
}

#[test]
fn an_edit_replaces_what_the_index_knew_and_the_gap_is_visible() {
    // Two claims in one test because they are one decision: the summary built from the old text is dropped —
    // so a query about the file answers "not read yet" rather than the edit's predecessor — and the file is
    // queued again, so the answer comes back a step later.
    let files = MemoryFiles::new().with_file("/p/widget.h", "struct Widget { int before; };\n");
    let fixture = Memory::new("edit", &files);
    let mut session = fixture.session();

    session.add_project_files([PathBuf::from("/p/widget.h")]);
    session.index_everything();
    assert!(session.is_indexed("/p/widget.h"));
    assert!(session.is_idle());

    session.did_change("/p/widget.h", "struct Widget { int after; };\n");

    assert!(
        !session.is_indexed("/p/widget.h"),
        "the summary describes text the user has replaced"
    );
    assert_eq!(session.pending(), 1, "and the file is queued again");

    let steps = session.advance(4);
    assert_eq!(paths(&steps), ["/p/widget.h"]);
    // **`Unstored` is the right answer for a file read through its own timeline**: the summary is a *rendering*, and
    // a rendering is a function of the environment as well as the text, so it answers this session and is not written
    // under the text-only key — see `SummaryStore::prepare_inner`. What the assertion is about is unchanged: the file
    // was parsed, not served from the cache.
    assert!(
        matches!(steps[0].outcome, StepOutcome::Built | StepOutcome::Unstored),
        "the summary was dropped, so this is a parse and not a cache hit: {:?}",
        steps[0].outcome
    );
    assert_eq!(session.stats().rebuilt, 2, "the first index and this one");

    // **The pump to the end, because the question is semantic.** `advance` reads files into the index and
    // `Pending` returned here is a *cook* — so a view needs the loop that runs the cook as well, and
    // `advance` alone never takes it. The assertions above are about the queue and stay about the queue; this
    // one is about the members a class has, which is a claim about meaning and needs a rendering.
    session.index_everything();
    let view = session.view("/p/widget.h").expect("the file reads");
    match session.members_of(&view, "Widget") {
        Known::Yes(members) => {
            let names: Vec<&str> = members
                .own()
                .map(|member| member.fact.name.as_str())
                .collect();
            assert_eq!(names, ["after"]);
        }
        other => panic!("the edited buffer's class should have members, got {other:?}"),
    }
}

#[test]
fn closing_a_document_goes_back_to_the_file() {
    // An unsaved buffer defines a name the disk does not have. Closing is the client saying "this path is the
    // filesystem's again", and an analysis that kept the buffer would report a declaration that exists nowhere.
    let files = MemoryFiles::new().with_file("/p/widget.h", "struct Widget { int on_disk; };\n");
    let fixture = Memory::new("close", &files);
    let mut session = fixture.session();

    session.did_open("/p/widget.h", "struct Widget { int in_the_buffer; };\n");
    session.index_everything();
    session.did_close("/p/widget.h");

    assert!(!fixture.documents.is_open("/p/widget.h"));
    assert!(!session.is_indexed("/p/widget.h"));

    let steps = session.advance(4);
    assert_eq!(paths(&steps), ["/p/widget.h"]);
    assert_eq!(
        steps[0].priority,
        Priority::Rest,
        "the user has stopped looking at it, so it is not urgent"
    );

    // **The two requests told apart, which is the contract this change introduced.** Closing dropped the buffer
    // and with it the rendering that was made *of the buffer*, so this first request gets no semantic reading and
    // must not be handed one: `None` here means "not this time", and the `advance` above is what has just queued
    // the work that answers it. A caller that could not tell `None` from "no such file" would report a missing
    // file; [`Session::is_indexed`] and [`Session::pending_work`] are how it tells them apart, and both are
    // asserted above.
    assert!(
        session.view("/p/widget.h").is_none(),
        "a buffer's rendering was made of the buffer, and the buffer is closed"
    );

    // Ask again after the work the close queued, and the reading is the disk's — which is the point of the
    // test: a closed document is the filesystem's again, and the analysis must agree.
    session.index_everything();
    let view = session
        .view("/p/widget.h")
        .expect("the file has been read again");
    match session.members_of(&view, "Widget") {
        Known::Yes(members) => {
            let names: Vec<&str> = members
                .own()
                .map(|member| member.fact.name.as_str())
                .collect();
            assert_eq!(names, ["on_disk"]);
        }
        other => panic!("the file's own class should have members, got {other:?}"),
    }
}

// -------------------------------------------------------------------------------------------
// The order
// -------------------------------------------------------------------------------------------

#[test]
fn the_open_file_is_worked_first_and_its_includes_next() {
    // The order fixes, read off the steps: what the user is looking at, then what it
    // includes, and only then the project. A session that worked the project first would answer the first
    // question after ten thousand files.
    let files = MemoryFiles::new()
        .with_file("/p/open.cpp", "#include \"deep.h\"\nvoid f() { }\n")
        .with_file("/p/deep.h", "int deep;\n")
        .with_file("/p/one.cpp", "int one;\n")
        .with_file("/p/two.cpp", "int two;\n");
    let fixture = Memory::new("order", &files);
    let mut session = fixture.session();

    session.add_project_files([PathBuf::from("/p/one.cpp"), PathBuf::from("/p/two.cpp")]);
    session.did_open("/p/open.cpp", "#include \"deep.h\"\nvoid f() { }\n");

    let steps = session.advance(8);
    assert_eq!(
        paths(&steps),
        ["/p/open.cpp", "/p/deep.h", "/p/one.cpp", "/p/two.cpp"]
    );

    assert_eq!(steps[0].priority, Priority::Open);
    assert_eq!(steps[0].depth, 0);
    assert_eq!(
        (steps[1].priority, steps[1].depth),
        (Priority::Open, 1),
        "a header an open file includes is worth reading before the project"
    );
    assert_eq!((steps[2].priority, steps[2].depth), (Priority::Rest, 0));
}

#[test]
fn a_project_file_that_is_opened_moves_to_the_open_half() {
    // The case the two halves exist for: the scan lists every file at open time, and then the user opens one of
    // them. Without the upgrade the file the user is looking at would sit behind everything else in the
    // project, and the queue would look right in every test that never opens anything.
    let files = MemoryFiles::new()
        .with_file("/p/widget.h", "struct Widget { int size; };\n")
        .with_file("/p/one.cpp", "int one;\n");
    let fixture = Memory::new("upgrade", &files);
    let mut session = fixture.session();

    session.add_project_files([PathBuf::from("/p/one.cpp"), PathBuf::from("/p/widget.h")]);
    session.did_open("/p/widget.h", "struct Widget { int size; };\n");

    let steps = session.advance(1);
    assert_eq!(paths(&steps), ["/p/widget.h"]);
    assert_eq!(steps[0].priority, Priority::Open);

    // And the entry it left in the rest half is not a second read of the same file.
    let rest = session.advance(4);
    assert_eq!(paths(&rest), ["/p/one.cpp"]);
    assert!(session.is_idle());
    assert_eq!(session.pending(), 0);
}

#[test]
fn a_file_that_was_worked_is_queued_again_when_its_answer_changes() {
    // The other half of the queue's memory: `add` refuses a path it has already worked, which is what keeps a
    // header included forty times one step — and a change has to get past exactly that rule.
    let files = MemoryFiles::new().with_file("/p/widget.h", "struct Widget { int a; };\n");
    let fixture = Memory::new("again", &files);
    let mut session = fixture.session();

    session.did_open("/p/widget.h", "struct Widget { int a; };\n");
    session.index_everything();
    assert!(session.is_idle());

    let before = session.stats();
    session.did_change("/p/widget.h", "struct Widget { int b; };\n");
    assert_eq!(session.pending(), 1);

    let steps = session.advance(4);
    assert_eq!(paths(&steps), ["/p/widget.h"]);
    assert_eq!(session.stats().since(before).rebuilt, 1);
}

// -------------------------------------------------------------------------------------------
// What the client says changed
// -------------------------------------------------------------------------------------------

#[test]
fn a_reported_change_is_read_again_and_a_reported_removal_is_forgotten() {
    // The "no OS watcher" entry point: the client reports events, the session turns them into work. A modified
    // header is **two** files to re-read — itself, and the file that includes it, whose summary is now a reading of
    // the header's replacement lists (see `Session::invalidate_dependents`) — and a removed one is forgotten
    // together with the files whose includes resolved to it.
    let files = MemoryFiles::new()
        .with_file("/p/widget.h", "struct Widget { int size; };\n")
        .with_file(
            "/p/main.cpp",
            "#include \"widget.h\"\nvoid f() { Widget w; }\n",
        );
    let fixture = Memory::new("client-events", &files);
    let mut session = fixture.session();

    session.add_project_files([PathBuf::from("/p/main.cpp")]);
    session.index_everything();
    assert!(
        session.is_indexed("/p/widget.h"),
        "the closure was followed"
    );

    let modified = session.changed([FileEvent::modified("/p/widget.h")]);
    assert_eq!(modified.reindex, [PathBuf::from("/p/widget.h")]);
    assert!(modified.forgotten.is_empty());
    assert!(!modified.everything);
    assert_eq!(
        session.pending(),
        2,
        "the change and the file whose reading depends on it are both queued"
    );

    let steps = session.advance(4);
    assert_eq!(paths(&steps), ["/p/widget.h", "/p/main.cpp"]);
    assert_eq!(
        steps[0].outcome,
        StepOutcome::Reused,
        "the text did not change, so the key still names the stored summary"
    );

    let removed = session.changed([FileEvent::removed("/p/widget.h")]);
    assert_eq!(removed.forgotten, [PathBuf::from("/p/widget.h")]);
    assert_eq!(
        removed.reindex,
        [PathBuf::from("/p/main.cpp")],
        "the file that resolved to it records a search that would now fail"
    );
    assert!(
        !session.is_indexed("/p/widget.h"),
        "and the declarations are out of the index before anything is re-read"
    );
}

#[test]
fn a_change_the_client_does_not_care_about_is_no_work() {
    // The filter is the session's, so the cache directory and `.git` are dropped once, where the events arrive,
    // rather than in every query. The compile database is the one path that is *reported* rather than dropped.
    let files = MemoryFiles::new().with_file("/p/a.cpp", "int a;\n");
    let fixture = Memory::new("ignored-events", &files);
    let mut session = fixture.session();
    session.add_project_files([PathBuf::from("/p/a.cpp")]);
    session.index_everything();

    let root = fixture.root.clone();
    let quiet = session.changed([
        FileEvent::modified(root.join(".git/index.lock")),
        FileEvent::modified(root.join(".cppls/summaries/ab/cdef.bin")),
        FileEvent::modified(root.join("notes.md")),
    ]);

    assert!(quiet.is_empty(), "{quiet:?}");
    assert!(session.is_idle());

    let configuration = session.changed([FileEvent::modified(root.join("compile_commands.json"))]);
    assert!(configuration.everything);
}

#[test]
fn a_configuration_change_re_seeds_the_project_and_the_open_buffers() {
    // The configuration is part of every summary's key, so one `-I` added to the database makes every stored
    // summary a miss — and the work is the project list again. What the user has open is queued first, because
    // that is the file they are waiting for.
    let files = MemoryFiles::new()
        .with_file("/p/a.cpp", "int a;\n")
        .with_file("/p/b.cpp", "int b;\n")
        .with_file("/p/open.cpp", "int open;\n");
    let fixture = Memory::new("configuration", &files);
    let mut session = fixture.session();

    session.add_project_files([PathBuf::from("/p/a.cpp"), PathBuf::from("/p/b.cpp")]);
    session.did_open("/p/open.cpp", "int open;\n");
    session.index_everything();
    assert!(session.is_idle());

    let response = session.changed([FileEvent::modified(
        fixture.root.join("compile_commands.json"),
    )]);
    assert!(response.everything);

    assert_eq!(
        session.pending(),
        3,
        "the project list and the buffer are all work again"
    );

    let steps = session.advance(8);
    assert_eq!(paths(&steps), ["/p/open.cpp", "/p/a.cpp", "/p/b.cpp"]);
}

#[test]
fn a_configuration_change_re_arms_a_worked_file_and_it_is_rebuilt() {
    // **This asserted `Reused` and could not**: the configuration is part of every summary`s key
    // (`SummaryKey::context_hash`), so a `compile_commands.json` that changed is a different reading of the same
    // text. The neighbour above pins the same fact for the whole project — "one `-I` added makes every stored
    // summary a miss" — and this test was written before that became true. What is worth pinning instead is that
    // re-arming costs one read rather than a lost file: the queue takes it back, the rebuild is counted, and the
    // index holds the same one summary afterwards.
    let files = MemoryFiles::new().with_file("/p/a.cpp", "int a;\n");
    let fixture = Memory::new("rearm", &files);
    let mut session = fixture.session();

    session.add_project_files([PathBuf::from("/p/a.cpp")]);
    session.index_everything();
    assert_eq!(session.index().summaries().count(), 1);

    let before = session.stats();
    session.changed([FileEvent::modified(
        fixture.root.join("compile_commands.json"),
    )]);

    let steps = session.advance(4);
    assert_eq!(paths(&steps), ["/p/a.cpp"], "the file is work again");
    assert!(
        matches!(steps[0].outcome, StepOutcome::Built | StepOutcome::Unstored),
        "a different configuration is a different reading, so the text alone cannot answer for it: {:?}",
        steps[0].outcome
    );
    assert_eq!(session.stats().since(before).rebuilt, 1);
    assert_eq!(
        session.index().summaries().count(),
        1,
        "and the index is the same size: a rebuild is not a second file"
    );
}

// -------------------------------------------------------------------------------------------
// What the answers are, and what they are before the work is done
// -------------------------------------------------------------------------------------------

#[test]
fn a_name_in_a_file_that_has_not_been_read_is_unknown_and_the_queue_says_so() {
    // The honest boundary of lazy indexing, asserted rather than described: the query answers
    // `NotDeclaredHere` — which is what a fully indexed project says about a name that is not there — and the
    // only thing that tells the two apart is whether the queue is empty. A consumer that reports an unresolved
    // name as an error has to ask.
    let files = MemoryFiles::new()
        .with_file("/p/widget.h", "struct Widget { int size; };\n")
        .with_file(
            "/p/main.cpp",
            "#include \"widget.h\"\nvoid f() { Widget w; }\n",
        );
    let fixture = Memory::new("not-read-yet", &files);
    let mut session = fixture.session();

    session.add_project_files([PathBuf::from("/p/main.cpp")]);

    // The file is loaded but **not indexed**: the *index* is what this test is about, and reading it would take
    // the queue step it goes on to assert.
    session.load("/p/main.cpp");

    // **And there is no view yet, which is now a state a caller has to handle rather than an implementation
    // detail.** The file has been read neither by the index nor as a compiler would, so a semantic question has
    // no reading to be answered from — and the two ways of saying "not yet" are both here: `view` answers
    // `None` and does not queue, because nothing has asked for a rendering of it.
    assert!(
        session.view("/p/main.cpp").is_none(),
        "a file nothing has read as a compiler reads it has no semantic view"
    );

    session.index_everything();
    let view = session.view("/p/main.cpp").expect("the pump has read it");
    let at = view
        .source
        .find("Widget w")
        .expect("the use is in the text");

    assert!(session.is_idle());
    assert!(
        matches!(session.definition(&view, ReadingOffset::new(at)), Known::Yes(found) if found.file == Path::new("/p/widget.h")),
        "the same question, answered once the file has been read"
    );
}

#[test]
fn a_view_is_the_buffer_parsed_and_maps_a_position_onto_an_offset() {
    // **Two questions that used to share one answer, and no longer do.** A position is a question about bytes
    // and a definition is a question about meaning; the first is available as soon as the file is held, and the
    // second needs the file read the way a compiler reads it. This test is the pair, side by side.
    let files =
        MemoryFiles::new().with_file("/p/a.cpp", "int on_disk;\nvoid f() { on_disk = 1; }\n");
    let fixture = Memory::new("view", &files);
    let mut session = fixture.session();

    session.did_open("/p/a.cpp", "int in_buffer;\nvoid f() { in_buffer = 1; }\n");

    // **The position, with no reading at all.** `tokens_of` is of the buffer — `load` was not needed and no cook
    // was waited for — and it says which of the two texts it read, which is what a client's offsets are in.
    let tokens = session.tokens_of("/p/a.cpp").expect("the buffer is held");
    assert!(
        tokens.open,
        "the reading says which of the two texts it read"
    );
    let at = tokens
        .source
        .find("in_buffer = 1")
        .expect("the use is in the text");
    assert_eq!(
        tokens.offset_at(1, 11),
        Some(ReadingOffset::new(at)),
        "line 1, column 11 is where `in_buffer` is written on the second line"
    );
    assert_eq!(
        tokens.offset_at(99, 0),
        None,
        "a line past the end is not an offset"
    );

    // **The meaning, after a cook, and it is the buffer's.** The file's own scope answers the query with no index
    // involved at all — and it answers about `in_buffer`, which exists only in the buffer.
    session.index_everything();
    let view = session.view("/p/a.cpp").expect("the pump has read it");
    assert!(
        view.source.contains("in_buffer"),
        "the reading is the buffer's"
    );
    let at = view
        .source
        .find("in_buffer = 1")
        .expect("the use is in the text");

    // And the file's own scope answers the query, with no index involved at all.
    assert!(
        matches!(session.definition(&view, ReadingOffset::new(at)), Known::Yes(found) if found.file == Path::new("/p/a.cpp")),
        "a local declaration is resolved by the file's scopes"
    );

    assert!(session.view("/p/not_there.cpp").is_none());
}

#[test]
fn a_position_maps_back_onto_the_offset_it_came_from() {
    // The direction a diagnostic needs: the parser reports byte offsets and a client wants a position. The two
    // mappings have to agree, and the case that makes that worth a test is a line that is not ASCII — the
    // column a client sends counts **characters**, so a one-byte-per-column round trip is the wrong answer the
    // moment a line contains `é`.
    let files = MemoryFiles::new()
        .with_file("/p/a.cpp", "// é comment\nint x = 1;\n")
        .with_file("/p/crlf.cpp", "int a;\r\nint b;\r\n");
    let fixture = Memory::new("position", &files);
    let mut session = fixture.session();
    // A view is of a file the session is **holding** (`file::vfs`): nothing has read these yet, so they are
    // loaded explicitly — the way a notification or an indexing step loads one.
    session.load("/p/a.cpp");
    session.load("/p/crlf.cpp");

    // **Through `tokens_of`, because this is a question about the text.** It needs a line index and a length and
    // nothing a declaration means, so it does not wait for a cook: positions are available the moment the file is
    // held, which is what a fold, a selection and a diagnostic span all rely on. Asking `view` here would now
    // mean asking a semantic question to get an answer about bytes.
    let view = session.tokens_of("/p/a.cpp").expect("the file reads");
    let at = view
        .source
        .find("x = 1")
        .expect("the statement is in the text");
    assert_eq!(
        view.position_at(ReadingOffset::new(at)),
        Some((1, 4)),
        "the offset of `x` is line 1, column 4"
    );

    // The round trip in both directions, on the line with the two-byte character.
    let (line, column) = view
        .position_at(ReadingOffset::new(at))
        .expect("the offset is in the file");
    assert_eq!(view.offset_at(line, column), Some(ReadingOffset::new(at)));

    let comment = view.source.find('é').expect("the character is in the text");
    assert_eq!(
        view.position_at(ReadingOffset::new(comment)),
        Some((0, 3)),
        "a character counts as one column, whatever it costs in bytes"
    );

    // And a CRLF file is one line break, not two: the `\r` is part of line 0, so line 1 starts after it.
    let crlf = session.tokens_of("/p/crlf.cpp").expect("the file reads");
    let second = crlf
        .source
        .find("int b")
        .expect("the second line is in the text");
    assert_eq!(crlf.position_at(ReadingOffset::new(second)), Some((1, 0)));
    assert_eq!(
        crlf.position_at(ReadingOffset::new(crlf.source.len())),
        Some((2, 0)),
        "the end of the text is a position: it is where a range at EOF sits"
    );

    assert_eq!(
        crlf.position_at(ReadingOffset::new(crlf.source.len() + 1)),
        None,
        "an offset past the end is not a position"
    );
}

// -------------------------------------------------------------------------------------------
// Opening a project on disk
// -------------------------------------------------------------------------------------------

/// A project directory, removed when the test ends — including when it fails.
struct Project {
    root: PathBuf,
}

impl Project {
    fn new(name: &str) -> Self {
        let root = std::env::temp_dir().join("cppls-session-disk").join(name);
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(&root).expect("the fixture directory");

        Project { root }
    }

    fn write(&self, name: &str, text: &str) -> PathBuf {
        let path = self.root.join(name);
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).expect("the fixture directory");
        }
        std::fs::write(&path, text).expect("the fixture writes");
        path
    }

    /// The project's own files, as paths relative to the root with `/` separators.
    fn relative(&self, paths: &[PathBuf]) -> Vec<String> {
        paths
            .iter()
            .filter_map(|path| path.strip_prefix(&self.root).ok())
            .map(|path| path.to_string_lossy().replace('\\', "/"))
            .collect()
    }
}

impl Drop for Project {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.root);
    }
}

#[test]
fn the_scan_finds_the_projects_sources_and_leaves_the_rest() {
    // What a scan is for, and what it must not do: a build tree and `.git` are not project source, a `.md` is
    // not a source at all, and a file with no extension is reached through an include rather than guessed at.
    let project = Project::new("scan");
    project.write("main.cpp", "int main() { return 0; }\n");
    project.write("include/widget.hpp", "struct Widget { int size; };\n");
    project.write("notes.md", "# notes\n");
    project.write("build/generated.cpp", "int generated;\n");
    project.write(".git/hooks/thing.cpp", "int hook;\n");
    project.write("extensionless", "int nothing;\n");

    let documents = OpenDocuments::new();
    let providers = SessionFiles::new(documents, DiskFiles);
    let filter = WatchFilter::new(&project.root).ignore(project.root.join("build"));

    let session = Session::with_config(
        &project.root,
        providers.clone(),
        filter,
        CompilerConfig::default(),
    );

    assert_eq!(
        project.relative(session.project_files()),
        ["include/widget.hpp", "main.cpp"]
    );
    assert_eq!(
        session.pending(),
        2,
        "and the list is the queue's seed, so the work is ready before the first query"
    );
}

#[test]
fn a_class_scoped_by_another_files_macro_body_is_scoped_through_the_session() {
    // The store's second pass, on the closure a **session** builds one file at a time. MSVC's STL is
    // written this way: `<vector>` opens `std` with `_STD_BEGIN`, whose replacement list is in `yvals_core.h`,
    // and it *includes* that file — while a file is read before the files it includes, because its own
    // `#include`s are a product of parsing it. So the first reading of every such file puts its declarations at
    // file scope. Measured on the whole STL through the driver: **0/9** without this pass, **9/9** with it,
    // against 9/9 for the same index built by `SummaryStore::index_includes_from` (which always had one).
    //
    // No compiler and no compile database take part: the body is written in a file of the project, which is
    // what makes this test the same on every machine.
    let project = Project::new("body-pass");
    let open = project.write(
        "open.h",
        "#pragma once\n#define _STD_BEGIN namespace std {\n#define _STD_END }\n",
    );
    let widget = project.write(
        "widget.h",
        "#include \"open.h\"\n_STD_BEGIN\nstruct Widget { int size; };\n_STD_END\n",
    );
    let main = project.write("main.cpp", "#include \"widget.h\"\n");

    let mut session = Session::with_config(
        &project.root,
        SessionFiles::new(OpenDocuments::new(), DiskFiles),
        WatchFilter::new(&project.root),
        CompilerConfig::default(),
    );
    session.index_everything();

    let found = session.index().definition("std::Widget", &main);
    let Known::Yes(found) = found else {
        panic!("`Widget` is declared behind a macro body written in `open.h`: {found:?}");
    };
    assert_eq!(found.file, widget);
    assert_eq!(found.fact.scope.as_deref(), Some("std"));

    // And the scope is a reading **of the body, not a conclusion about it**. The body is in `open.h`; the scope it
    // opens is in `widget.h` only because `widget.h` renders through it. So a changed body has to be a changed
    // answer — and that, rather than a stored note, is what "evidence" means once the parser reads the rendering:
    // there is no scope read out of a replacement list to record (`tests/rendering_scope.rs` prints the rendering:
    // `namespace std {` is literal text there), and what makes the answer follow the body is that the summary *is*
    // the rendering, which [`Session::invalidate_dependents`] drops when a directive of an included file moves.
    assert_eq!(
        session.index().dependents_of(&open).len(),
        2,
        "`widget.h` includes it and `main.cpp` includes that: the index knows both"
    );
    session.did_change(
        &open,
        "#pragma once\n#define _STD_BEGIN namespace studio {\n#define _STD_END }\n",
    );
    assert!(
        !session.is_indexed(&widget),
        "the body moved, so the file that rendered through it has to be read again"
    );
    session.index_everything();

    assert!(
        matches!(
            session.index().definition("std::Widget", &main),
            Known::No | Known::Unknown(_)
        ),
        "the body no longer opens `std`, so nothing may still answer `std::Widget`"
    );
    let moved = session.index().definition("studio::Widget", &main);
    let Known::Yes(moved) = moved else {
        panic!("`Widget` is behind `namespace studio` now: {moved:?}");
    };
    assert_eq!(
        moved.file.file_name(),
        widget.file_name(),
        "the declaration is still `widget.h`'s"
    );
}

/// **A keystroke in a body rebuilds the file's summary *through its timeline*, not from its bytes.**
///
/// The window this closes is the one the four patch layers exist for. An edit drops the file's summary
/// ([`Session::did_change`]) and the next drain rebuilds it; while that rebuild was a parse of the file's own bytes,
/// every answer about the file was the *written* reading until the idle pass got to it — a scope opened by another
/// file's macro was `None`, a return type split by `#if` was the wrong branch. A body edit moves no directive, so the
/// timeline is still in force, and an index step that holds one now renders instead of parsing text.
#[test]
fn a_keystroke_in_a_body_reads_the_file_through_its_timeline() {
    let project = Project::new("keystroke-renders");
    project.write(
        "open.h",
        "#pragma once\n#define _STD_BEGIN namespace std {\n#define _STD_END }\n",
    );
    let widget = project.write(
        "widget.h",
        "#include \"open.h\"\n_STD_BEGIN\nstruct Widget { int size; };\n_STD_END\n",
    );

    let mut session = Session::with_config(
        &project.root,
        SessionFiles::new(OpenDocuments::new(), DiskFiles),
        WatchFilter::new(&project.root),
        CompilerConfig::default(),
    );
    session.add_project_files([widget.clone()]);
    session.index_everything();
    assert!(
        session.index().summary(&widget).is_some_and(|summary| {
            summary
                .declarations
                .iter()
                .any(|fact| fact.name == "Widget" && fact.scope.as_deref() == Some("std"))
        }),
        "the first reading is the timeline's, from the second pass"
    );

    // **The keystroke**: a declaration added to the body. No directive moves, so the timeline still describes this
    // file — which is the case the pump sees on most keystrokes.
    session.did_change(
        &widget,
        "#include \"open.h\"\nint padding;\n_STD_BEGIN\nstruct Widget { int size; };\n_STD_END\n",
    );
    let steps = session.advance(4);
    let step = steps
        .iter()
        .find(|step| step.path == widget)
        .unwrap_or_else(|| panic!("the edited file is read: {:?}", paths(&steps)));
    assert!(
        step.with_the_environment,
        "the rebuild was taken through the file's timeline, so the second pass has nothing to repair: {step:?}"
    );

    // And the facts say so: the scope of a declaration written inside a macro-opened namespace is `std` **now**,
    // before any idle pass could have re-read the file.
    let summary = session.index().summary(&widget).expect("indexed again");
    let widget_fact = summary
        .declarations
        .iter()
        .find(|fact| fact.name == "Widget")
        .expect("the class is declared");
    assert_eq!(
        widget_fact.scope.as_deref(),
        Some("std"),
        "a rendering, not the file's own bytes"
    );
}

/// **A file opened after the project was indexed is read through a timeline that has to be *walked*, not one in hand.**
///
/// The other half of the window [`a_keystroke_in_a_body_reads_the_file_through_its_timeline`] closes. That one
/// pins the cheap case — a body edit keeps the file's timeline — and the timeline table is bounded
/// ([`super::MAX_UNIT_BYTES`], [`super::MAX_UNITS`]), so after a project is indexed the file a reader opens has no
/// entry. The step then used to parse the file's own bytes and leave the repair to the idle pass.
///
///
/// ```text
/// directives   the file's includes, read without a parse (`SummaryStore::directive_summary`)
/// the unit     walked from them, and *refused* when a file the program needs has not been read
/// the parse    of the rendering, which is then the reading every consumer gets
/// ```
#[test]
fn a_file_opened_after_the_index_was_built_is_read_through_a_walked_timeline() {
    let project = Project::new("opened-renders");
    project.write(
        "open.h",
        "#pragma once\n#define _STD_BEGIN namespace std {\n#define _STD_END }\n",
    );
    let widget = project.write(
        "widget.h",
        "#include \"open.h\"\n_STD_BEGIN\nstruct Widget { int size; };\n_STD_END\n",
    );

    let mut session = Session::with_config(
        &project.root,
        SessionFiles::new(OpenDocuments::new(), DiskFiles),
        WatchFilter::new(&project.root),
        CompilerConfig::default(),
    );
    session.add_project_files([widget.clone()]);
    session.index_everything();

    // **The edit that takes the timeline away.** A body edit keeps it ([`Session::directives_moved`] compares the
    // file's directives, and a body is not one); a directive edit moves the layout, which is a change to every offset
    // the timeline recorded — so the entry is dropped, the summary with it, and the file is queued at
    // `Priority::Open`. That is the state the units table's byte budget leaves a reader in after a project is
    // indexed, and it used to mean "read the file's own bytes".
    let edited = format!(
        "{}#define PAD 1\n",
        std::fs::read_to_string(&widget).expect("the fixture reads")
    );
    session.did_change(&widget, &edited);
    assert!(
        session.index().summary(&widget).is_none(),
        "the edit drops the reading: the buffer is the text now"
    );

    // **The walk is the thing being measured**, so it is counted rather than assumed: a timeline in hand would
    // answer this step with no walk at all, and then the test would be about the other one.
    let walked_before = session.unit_stats().walked;
    let steps = session.advance(4);
    let step = steps
        .iter()
        .find(|step| step.path == widget)
        .unwrap_or_else(|| panic!("the opened file is read: {:?}", paths(&steps)));
    assert!(
        session.unit_stats().walked > walked_before,
        "the timeline was walked for this file: {:?}",
        session.unit_stats()
    );
    assert!(
        step.with_the_environment,
        "and the reading taken through it is the program's, so the second pass has nothing to repair: {step:?}"
    );

    let summary = session.index().summary(&widget).expect("indexed again");
    let widget_fact = summary
        .declarations
        .iter()
        .find(|fact| fact.name == "Widget")
        .expect("the class is declared");
    assert_eq!(
        widget_fact.scope.as_deref(),
        Some("std"),
        "the scope comes from another file's macro body, so the timeline is what answered"
    );
}

/// **A file whose program nobody has read yet is read as text, and that is the honest answer rather than a worse one.**
///
/// The guard on the walk above, and the reason it is a condition rather than a retry: a timeline
/// that stops at a file it cannot look up is a timeline of a *smaller* program — the macro is left
/// unexpanded in the rendering — and a rendering is written down and believed.
#[test]
fn a_file_whose_program_has_not_been_read_yet_is_still_read_as_text() {
    let project = Project::new("opened-before-the-program");
    project.write(
        "open.h",
        "#pragma once\n#define _STD_BEGIN namespace std {\n#define _STD_END }\n",
    );
    let widget = project.write(
        "widget.h",
        "#include \"open.h\"\n_STD_BEGIN\nstruct Widget { int size; };\n_STD_END\n",
    );
    let text = std::fs::read_to_string(&widget).expect("the fixture reads");

    // **Nothing is read yet**: the session is told about the project and about the buffer, and no pass has run.
    let mut session = Session::with_config(
        &project.root,
        SessionFiles::new(OpenDocuments::new(), DiskFiles),
        WatchFilter::new(&project.root),
        CompilerConfig::default(),
    );
    session.add_project_files([widget.clone()]);
    session.did_open(&widget, &text);

    let steps = session.advance(4);
    let step = steps
        .iter()
        .find(|step| step.path == widget)
        .unwrap_or_else(|| panic!("the opened file is read: {:?}", paths(&steps)));
    assert!(
        !step.with_the_environment,
        "`open.h` has not been read, so there is no timeline to read this file through: {step:?}"
    );
    assert_eq!(
        step.outcome,
        StepOutcome::Built,
        "and the file's own text is what was read: {step:?}"
    );
}

// -------------------------------------------------------------------------------------------
// The project's own configuration file
// -------------------------------------------------------------------------------------------

#[test]
fn a_project_configuration_narrows_the_scan_and_widens_the_source_list() {
    // The two things `[workspace]` is for: a tree the analysis should not read, and an extension the engine
    // does not know about. Both are read from the project's own file, on disk, by a session the caller
    // configured — which is the path a test can take without running a compiler.
    let project = Project::new("config-scan");
    project.write("main.cpp", "int main() { return 0; }\n");
    project.write("vendor/third_party.cpp", "int vendored;\n");
    project.write("kernels/vector.cuh", "struct FromCuda { int x; };\n");
    project.write(
        ".cppls.toml",
        "[workspace]\nexclude = [\"vendor/**\"]\nsource_extensions = [\"cuh\"]\n",
    );

    let documents = OpenDocuments::new();
    let providers = SessionFiles::new(documents, DiskFiles);
    let session = Session::with_config(
        &project.root,
        providers,
        WatchFilter::new(&project.root),
        CompilerConfig::default(),
    );

    assert_eq!(
        project.relative(session.project_files()),
        ["kernels/vector.cuh", "main.cpp"],
        "the excluded tree is not scanned, and the project's own extension is"
    );
    assert!(
        session.project_config().found(),
        "the file was read: {:?}",
        session.project_config()
    );
    assert!(session.project_config().problems.is_empty());
}

#[test]
fn the_projects_flags_win_over_the_databases_and_extra_args_add_to_the_winner() {
    // The decision `CompileSection::args` records, pinned: `args` wins outright, `extra_args` adds to whatever
    // won, and `remove_args` drops a flag from it. One test because the three keys are one pass over one list —
    // splitting them would let the order they are documented in stop being the order they happen in.
    let project = Project::new("config-flags");
    project.write("main.cpp", "int main() { return 0; }\n");
    let root = project.root.to_string_lossy().replace('\\', "/");

    project.write(
        "compile_commands.json",
        &format!(
            "[\n  {{\"directory\": \"{root}\", \"file\": \"{root}/main.cpp\", \
                 \"arguments\": [\"g++\", \"-DFROM_THE_DATABASE\", \"-std=c++17\", \"-Werror\", \
                 \"-c\", \"{root}/main.cpp\"]}}\n]\n"
        ),
    );
    project.write(
        ".cppls.toml",
        "[compile]\nargs = [\"-DFROM_THE_CONFIG\", \"-std=c++20\"]\nextra_args = [\"-DEXTRA\"]\n",
    );

    let documents = OpenDocuments::new();
    let providers = SessionFiles::new(documents, DiskFiles);
    let session = Session::open(&project.root, providers, WatchFilter::new(&project.root));

    let defines: Vec<&str> = session
        .config()
        .defines
        .iter()
        .map(|define| define.name.as_ref())
        .collect();
    assert_eq!(
        defines,
        ["FROM_THE_CONFIG", "EXTRA"],
        "the file's flags are the compilation, and `extra_args` joins them"
    );
    assert_eq!(
        session.config().standard.as_deref(),
        Some("c++20"),
        "the database's `-std=c++17` is not in effect"
    );
}

#[test]
fn removing_and_adding_a_flag_is_one_pass_in_that_order() {
    // `remove_args` drops from the list that won, and `extra_args` appends to it — removing *first* is what
    // makes "drop the database's `-std=c++17`, add `-std=c++20`" mean c++20 rather than c++17.
    let project = Project::new("config-remove");
    project.write("main.cpp", "int main() { return 0; }\n");
    let root = project.root.to_string_lossy().replace('\\', "/");

    project.write(
            "compile_commands.json",
            &format!(
                "[\n  {{\"directory\": \"{root}\", \"file\": \"{root}/main.cpp\", \
                 \"arguments\": [\"g++\", \"-std=c++17\", \"-DKEEP\", \"-Werror\", \"-c\", \"{root}/main.cpp\"]}}\n]\n"
            ),
        );
    project.write(
        ".cppls.toml",
        "[compile]\nremove_args = [\"-Werror\", \"-std=c++17\"]\nextra_args = [\"-std=c++20\"]\n",
    );

    let documents = OpenDocuments::new();
    let providers = SessionFiles::new(documents, DiskFiles);
    let session = Session::open(&project.root, providers, WatchFilter::new(&project.root));

    assert_eq!(
        session
            .config_for(&project.root.join("main.cpp"))
            .standard
            .as_deref(),
        Some("c++20")
    );
    let per_file = session.config_for(&project.root.join("main.cpp"));
    let defines: Vec<&str> = per_file
        .defines
        .iter()
        .map(|define| define.name.as_ref())
        .collect();
    assert_eq!(defines, ["KEEP"], "a flag nobody removed still applies");
}

/// A database written somewhere no convention predicts, named by the project's own file.
#[test]
fn the_database_can_be_somewhere_no_convention_predicts() {
    let project = Project::new("config-database");
    project.write("main.cpp", "int main() { return 0; }\n");
    let root = project.root.to_string_lossy().replace('\\', "/");
    project.write(
        "out/compile_commands.json",
        &format!(
            "[\n  {{\"directory\": \"{root}\", \"file\": \"{root}/main.cpp\", \
                 \"arguments\": [\"g++\", \"-DFROM_ELSEWHERE\", \"-c\", \"{root}/main.cpp\"]}}\n]\n"
        ),
    );
    project.write(
        ".cppls.toml",
        "[compile]\ndatabase = \"out/compile_commands.json\"\n",
    );

    let documents = OpenDocuments::new();
    let providers = SessionFiles::new(documents, DiskFiles);
    let session = Session::open(&project.root, providers, WatchFilter::new(&project.root));

    assert_eq!(
        session.compile_database().map(crate::CompileCommands::len),
        Some(1)
    );
    let defines: Vec<&str> = session
        .config()
        .defines
        .iter()
        .map(|define| define.name.as_ref())
        .collect();
    assert_eq!(defines, ["FROM_ELSEWHERE"]);
    assert_eq!(project.relative(session.project_files()), ["main.cpp"]);
}

#[test]
fn the_cache_goes_where_the_project_says_and_the_filter_follows_it() {
    // The cache directory is one name with three readers — the store that writes under it, the filter that
    // ignores its events, and the report a user reads — and this is the property that keeps them one answer.
    let project = Project::new("config-cache");
    project.write("main.cpp", "int main() { return 0; }\n");
    project.write(".cppls.toml", "[index]\ncache_dir = \".cppls-cache\"\n");

    let documents = OpenDocuments::new();
    let providers = SessionFiles::new(documents, DiskFiles);
    let mut session = Session::with_config(
        &project.root,
        providers,
        WatchFilter::new(&project.root),
        CompilerConfig::default(),
    );

    session.index_everything();
    assert_eq!(session.stats().rebuilt, 1, "the file was read");

    // **The cache is one database file under the configured directory**, not a tree of summaries. The property this
    // test exists for is that the *name* has three agreeing readers — the store that writes, the filter that ignores
    // its events, and the report a user reads — and a directory is what all three join the name to.
    assert!(
        project.root.join(".cppls-cache").is_dir(),
        "the cache is under the configured directory, not the default: {}",
        project.root.join(".cppls-cache").display()
    );
    assert!(
        !project.root.join(crate::CACHE_DIRECTORY).exists(),
        "and the default directory was not created at all"
    );
}

#[test]
fn the_sections_a_language_server_reads_come_from_the_same_parse() {
    // One file, one parser: the server's keys are read from the session's report rather than by a second
    // TOML reader in the other crate, which is what keeps the two from disagreeing about what it says.
    let project = Project::new("config-server-keys");
    project.write("main.cpp", "int main() { return 0; }\n");
    project.write(
        ".cppls.toml",
        "[diagnostics]\non_change_ms = 250\n\n[hover]\nenable = false\n",
    );

    let documents = OpenDocuments::new();
    let providers = SessionFiles::new(documents, DiskFiles);
    let session = Session::with_config(
        &project.root,
        providers,
        WatchFilter::new(&project.root),
        CompilerConfig::default(),
    );

    let config = &session.project_config().config;
    assert_eq!(config.diagnostics.on_change_ms, Some(250));
    assert_eq!(config.hover.enable, Some(false));
}

#[test]
fn a_configuration_file_with_a_typo_still_analyses_the_project() {
    // The failure mode the section-by-section parse exists for: one bad key must not cost the project its
    // exclusions, and the problem must be visible to whoever asks the session what it thought.
    let project = Project::new("config-typo");
    project.write("main.cpp", "int main() { return 0; }\n");
    project.write("vendor/third_party.cpp", "int vendored;\n");
    project.write(
        ".cppls.toml",
        "[workspace]\nexclude = [\"vendor/**\"]\n\n[index]\ncache_dir = 5\n",
    );

    let documents = OpenDocuments::new();
    let providers = SessionFiles::new(documents, DiskFiles);
    let session = Session::with_config(
        &project.root,
        providers,
        WatchFilter::new(&project.root),
        CompilerConfig::default(),
    );

    assert_eq!(
        project.relative(session.project_files()),
        ["main.cpp"],
        "the exclusions are in effect"
    );
    assert_eq!(session.project_config().problems.len(), 1);
    assert!(
        session.project_config().problems[0]
            .message
            .contains("[index]")
    );
    assert_eq!(session.project_config().errors().count(), 1);
}

#[test]
fn a_database_in_a_build_directory_is_found_and_its_flags_reach_the_session() {
    // The whole point of the build-system half: a project that exports its database into `build/` must be
    // analysed with *those* flags and *that* file list, without anybody naming the path. This is the test that
    // fails if the discovery is written but not wired into the session.
    let project = Project::new("build-directory-database");
    project.write("main.cpp", "int main() { return 0; }\n");
    let root = project.root.to_string_lossy().replace('\\', "/");

    project.write(
        "build/compile_commands.json",
        &format!(
            "[\n  {{\"directory\": \"{root}\", \"file\": \"{root}/main.cpp\", \
                 \"arguments\": [\"g++\", \"-DFROM_THE_BUILD_DIRECTORY\", \"-std=c++20\", \
                 \"-c\", \"{root}/main.cpp\"]}}\n]\n"
        ),
    );

    let documents = OpenDocuments::new();
    let providers = SessionFiles::new(documents, DiskFiles);
    let session = Session::open(&project.root, providers, WatchFilter::new(&project.root));

    assert_eq!(
        session.compile_database().map(crate::CompileCommands::len),
        Some(1),
        "the database in the build directory was read"
    );
    assert_eq!(
        session
            .discovery()
            .database
            .as_ref()
            .map(|found| found.origin),
        Some(crate::DatabaseOrigin::BuildDirectory),
        "and the report says where it was found"
    );
    let per_file = session.config_for(&project.root.join("main.cpp"));
    let defines: Vec<&str> = per_file
        .defines
        .iter()
        .map(|define| define.name.as_ref())
        .collect();
    assert_eq!(defines, ["FROM_THE_BUILD_DIRECTORY"]);
    assert_eq!(
        session
            .config_for(&project.root.join("main.cpp"))
            .standard
            .as_deref(),
        Some("c++20")
    );
    assert!(
        session
            .discovery()
            .problems
            .iter()
            .any(|problem| problem.message.contains("build directory")),
        "and a user reading the report is told: {:?}",
        session.discovery().problems
    );
}

#[test]
/// Restored after a scripted edit ate this header — the body below is unchanged.
fn a_project_without_a_database_is_analysed_against_the_compilers_defaults() {
    // No database and no `[compile].args`: the analysis is about the compiler's own defaults rather than about
    // the project's build. That *works*, and the problem list says what would make it better — which is the
    // whole reason the list exists.
    let project = Project::new("without-a-database");
    project.write("main.cpp", "int main() { return 0; }\n");

    let documents = OpenDocuments::new();
    let providers = SessionFiles::new(documents, DiskFiles);
    let session = Session::open(&project.root, providers, WatchFilter::new(&project.root));

    assert!(session.compile_database().is_none());
    assert!(
        session
            .discovery()
            .problems
            .iter()
            .any(|problem| problem.message.contains("no compile database")),
        "the way to do better is spelled out: {:?}",
        session.discovery().problems
    );
}

#[test]
fn a_compile_database_names_the_files_that_are_here_and_the_flags_they_are_built_with() {
    // The two things a database is read for: which files are compiled — the list is better than a scan, because
    // it is the project's own statement — and the flags, which are the whole reason the configuration is not
    // guessed. An entry naming a file this checkout does not have is dropped rather than queued, because a
    // checked-in database writes the absolute paths of the machine that produced it.
    let project = Project::new("database");
    project.write("main.cpp", "int main() { return 0; }\n");
    let root = project.root.to_string_lossy().replace('\\', "/");

    project.write(
            "compile_commands.json",
            &format!(
                "[\n  {{\"directory\": \"{root}\", \"file\": \"{root}/main.cpp\", \
                 \"arguments\": [\"g++\", \"-DFROM_THE_DATABASE\", \"-I{root}/include\", \"-std=c++20\", \
                 \"-c\", \"{root}/main.cpp\"]}},\n  \
                 {{\"directory\": \"{root}\", \"file\": \"{root}/elsewhere.cpp\", \
                 \"arguments\": [\"g++\", \"-c\", \"{root}/elsewhere.cpp\"]}}\n]\n"
            ),
        );

    let documents = OpenDocuments::new();
    let providers = SessionFiles::new(documents, DiskFiles);
    let session = Session::open(
        &project.root,
        providers.clone(),
        WatchFilter::new(&project.root),
    );

    let database = session.compile_database().expect("the database is read");
    assert_eq!(database.len(), 2);

    let per_file = session.config_for(&project.root.join("main.cpp"));
    let defines: Vec<&str> = per_file
        .defines
        .iter()
        .map(|define| define.name.as_ref())
        .collect();
    assert_eq!(defines, ["FROM_THE_DATABASE"]);
    assert_eq!(
        session
            .config_for(&project.root.join("main.cpp"))
            .standard
            .as_deref(),
        Some("c++20")
    );

    assert_eq!(project.relative(session.project_files()), ["main.cpp"]);
    assert_eq!(
        session.pending(),
        1,
        "the entry for a file that is not here is not work"
    );
}

#[test]
/// Restored after a scripted edit ate this header — the body below is unchanged.
fn a_define_the_compile_database_carries_decides_a_condition_in_a_file() {
    // The whole way a `-D` travels: the database's flags become the configuration, the configuration becomes
    // the macro environment, and the environment decides the `#ifdef` around an `#include`. The *answer*
    // therefore depends on how the project is built while the *summary* does not — which is why a summary
    // stores the question rather than the answer, and why changing `-D` does not throw the cache away.
    let project = Project::new("conditional-include");
    let root = project.root.to_string_lossy().replace('\\', "/");

    project.write("feature.h", "#define FEATURE_ONLY int\n");
    project.write(
        "main.cpp",
        "#ifdef FROM_THE_DATABASE\n#include \"feature.h\"\n#endif\nFEATURE_ONLY x;\n",
    );
    project.write(
            "compile_commands.json",
            &format!(
                "[{{\"directory\": \"{root}\", \"file\": \"{root}/main.cpp\", \
                 \"arguments\": [\"g++\", \"-DFROM_THE_DATABASE\", \"-c\", \"{root}/main.cpp\"]}}]\n"
            ),
        );

    let documents = OpenDocuments::new();
    let providers = SessionFiles::new(documents, DiskFiles);
    let mut session = Session::open(
        &project.root,
        providers.clone(),
        WatchFilter::new(&project.root),
    );

    // **Both files, because the closure of `main.cpp` is what the query walks.**
    session.advance(64);

    let path = project.root.join("main.cpp");
    let _source = std::fs::read_to_string(&path).expect("the fixture reads");

    // **The asking side, which is how a project nobody has opened gets read.**
    //
    // `advance` reads files into the index and never cooks, and nothing here is open — so no file was queued for
    // cooking and the first ask has no rendering to answer from. That is the deferral, and this is what a real
    // caller does with it: the ask **queues** the file, the pump cooks it, the next ask has it. Written as the
    // two steps rather than one because the first answer is `None` by contract and a test that hid that would be
    // asserting a behaviour the product does not have.
    assert!(
        session.view(&path).is_none(),
        "nothing has read this file as a compiler reads it, and that is what the ask is for"
    );
    session.index_everything();

    let view = session
        .view(&path)
        .expect("the ask queued it and the pump cooked it");

    // **The rendering is the proof, and it is a stronger one than the reference list was.**
    //
    // The chain under test is *flags → configuration → environment → the branch an `#ifdef` takes*, and the
    // endpoint of that chain is the text a compiler would parse. `-DFROM_THE_DATABASE` decides
    // `#ifdef FROM_THE_DATABASE`, which decides whether `feature.h` is reached, which decides what
    // `FEATURE_ONLY` — defined there as `int` — expands to. So a rendering of exactly `int x;` says every link
    // held: the define came from the database, the include was taken, and the macro was substituted.
    assert_eq!(
        view.source.as_ref(),
        "int x;",
        "the -D took the branch, the branch included feature.h, and FEATURE_ONLY became int"
    );

    // **And what this test does NOT prove, said rather than implied.** It shows the chain holds *with* the
    // database's flag. It cannot show it *fails* without it, and the reason is the session's contract rather
    // than an oversight here: [`Session::open`] reads `compile_commands.json` whenever the project has one
    // (`session.rs:66`), so a second session over this same directory necessarily has the same `-D`. A negative
    // half was written and **measured to be worthless** — it rendered `int x;` as well, because the flag was
    // there in both sessions:
    //
    // ```text
    //   with no -D the `#ifdef` is false ...: got "int x;"
    // ```
    //
    // A one-sided assertion is the failure mode this test now names instead of hiding: without a session whose
    // flags differ, `int x;` is consistent with reading the include unconditionally. Building that session means
    // opening a project whose database has no flags — a fixture change, not a new assertion here.
    //
    // **And the reference half was removed rather than repaired.** It asked [`Session::macro_references`] about
    // `FEATURE_ONLY`, which needs a *name at an offset* and gets one from a tree; but a macro is **gone** from a
    // rendering — that is what a rendering is — so the question was a category error and answered
    // `Unknown(UnparsableName)`. A macro question wants the file's own tokens plus the closure's macro facts,
    // and `Session::tokens_of` is the first half of that. What is missing is the entry point, not the reading:
    // see the note on `Session::macro_references`.
}

#[test]
fn the_compilation_is_known_only_when_the_compiler_answered_with_its_macros() {
    // The licence for one claim — *a name none of the witnesses mentions is not defined* — pinned on the three
    // shapes a session can be in. The middle one is why this is a function rather than a field read at the call
    // site: a toolchain **exists** on a machine whose headers were found by a convention and whose compiler
    // could not be asked, and its macro table is empty. Claiming completeness there would read all five hundred
    // of the compiler's own names as "not defined" — `#ifdef _MSC_VER` coming out false *on MSVC* — which is a
    // wrong answer rather than a missing one, the direction this layer must never fail in.
    assert!(
        !super::the_compilation_is_known(None),
        "no compiler answered, so nothing witnesses the built-ins"
    );

    let unasked = Toolchain {
        compiler: None,
        version: None,
        system_include_paths: vec![PathBuf::from("/usr/include")],
        builtin_macros: Vec::new(),
        dialect: None,
        cuda: false,
        standard: None,
        source: ToolchainSource::SystemHeaders,
        note: Some("no compiler could be asked".to_string()),
    };
    assert!(
        !super::the_compilation_is_known(Some(&unasked)),
        "directories without a macro table are half a toolchain, and the missing half is the built-ins"
    );

    let asked = Toolchain {
        compiler: Some(PathBuf::from("cl")),
        builtin_macros: vec![CommandLineMacro::defined("_MSC_VER")],
        ..unasked
    };
    assert!(
        super::the_compilation_is_known(Some(&asked)),
        "a compiler that answered is the only witness there is to the names no file defines"
    );
}

/// **The closure, not the direct includes** — the question a *colouring* asks.
///
/// `is_locally_ready` asks whether the file's own includes are read, which is exactly what `catch_up` does and
/// what one name lookup needs. A semantic token pass classifies **every** identifier, so what it needs is the
/// whole closure: `std::endl` is declared in `<ostream>`, reached through `<iostream>`, and a request answered
/// while only the first level was read drew it with the client's own grammar colour (measured from an editor:
/// a variable at startup, a function after any edit).
#[test]
fn a_file_is_closure_ready_only_once_what_it_reaches_is_read() {
    let files = MemoryFiles::new()
        .with_file("/p/mid.h", "#include \"deep.h\"\n")
        .with_file("/p/deep.h", "namespace std { int endl(); }\n")
        .with_file(
            "/p/a.cpp",
            "#include \"mid.h\"\nint main() { return std::endl(); }\n",
        );
    let fixture = Memory::new("is-closure-ready", &files);

    let mut session = fixture.session();
    session.add_project_files([PathBuf::from("/p/a.cpp")]);
    session.index_everything();

    assert!(
        session.is_locally_ready(Path::new("/p/a.cpp")),
        "the file and its direct includes are read"
    );
    assert!(
        session.is_closure_ready(Path::new("/p/a.cpp")),
        "and so is everything they reach"
    );

    // **The distinction, made by dropping the deepest file's summary** — the state a project is in while its
    // queue is still being read: `a.cpp`'s direct include (`mid.h`) is in, its include's (`deep.h`) is not.
    session.store.forget(Path::new("/p/deep.h"));

    assert!(
        session.is_locally_ready(Path::new("/p/a.cpp")),
        "the direct question is unchanged — `catch_up` has nothing left to read"
    );
    assert!(
        !session.is_closure_ready(Path::new("/p/a.cpp")),
        "but a name declared in `deep.h` has no classification, which is the question colouring asks"
    );
}
/// **CUDA's vocabulary is offered in a CUDA project and nowhere else** — the completion half of the family switch.
///
/// `__global__` is an identifier to the lexer and a specifier to `nvcc`, so the list of what may be written at a
/// statement's start depends on the *project*, not on the file: the same text is a kernel definition to a CUDA
/// toolchain and a declaration of a variable called `__global__` to a C++ one. A list that offered the qualifiers
/// everywhere would be teaching a spelling no compiler on that project will accept.
///
/// Measured through the session rather than through the table, because the interesting question is what a reader sees:
/// `__dev` is a prefix, and the list has to filter on it, rank the namespace names around it, and stop at the
/// project boundary.
#[test]
fn cuda_words_are_offered_only_by_a_cuda_project() {
    let text = "void f() {\n    __dev\n}\n";
    let files = MemoryFiles::new().with_file("/p/a.cu", text);
    let fixture = Memory::new("cuda-completion", &files);
    let mut session = fixture.session_with(CompilerConfig::new().with_cuda(true));
    session.did_open("/p/a.cu", text);
    session.index_everything();

    let path = std::path::PathBuf::from("/p/a.cu");
    let view = session.view_of_the_file(&path).expect("a view");
    let at = text.find("__dev\n").expect("the fixture") + "__dev".len();
    let labels = |set: &crate::CompletionSet| {
        set.items
            .iter()
            .map(|item| item.label.clone())
            .collect::<Vec<String>>()
    };

    let cuda = session.completions(&view, crate::file::coordinates::FileOffset::new(at));
    let offered = labels(&cuda);
    assert!(
        offered.iter().any(|label| label == "__device__"),
        "a CUDA project completes `__device__`: {offered:?}"
    );

    // **The same text, read as C++.** The words are gone; what is left is whatever the file itself declares, which for
    // this fixture is nothing that starts with `__dev`.
    let mut session = fixture.session();
    session.did_open("/p/a.cu", text);
    session.index_everything();
    let view = session.view_of_the_file(&path).expect("a view");
    let cpp = session.completions(&view, crate::file::coordinates::FileOffset::new(at));
    let offered = labels(&cpp);
    assert!(
        !offered.iter().any(|label| label.starts_with("__")),
        "a project that is not CUDA is not offered CUDA's vocabulary: {offered:?}"
    );
}

/// **Every kind of CUDA word completes**, not only the qualifiers: a reader typing `thr` wants `threadIdx`, and one
/// typing `float` wants `float4` beside `float`.
#[test]
fn the_built_in_variables_and_vector_types_complete_too() {
    let text = "void f() {\n    thr\n}\n";
    let files = MemoryFiles::new().with_file("/p/a.cu", text);
    let fixture = Memory::new("cuda-completion-kinds", &files);
    let mut session = fixture.session_with(CompilerConfig::new().with_cuda(true));
    session.did_open("/p/a.cu", text);
    session.index_everything();
    let path = std::path::PathBuf::from("/p/a.cu");
    let view = session.view_of_the_file(&path).expect("a view");
    let at = text.find("thr\n").expect("the fixture") + "thr".len();
    let set = session.completions(&view, crate::file::coordinates::FileOffset::new(at));
    let labels: Vec<&str> = set.items.iter().map(|item| item.label.as_str()).collect();
    assert!(
        labels.contains(&"threadIdx"),
        "a built-in variable completes: {labels:?}"
    );
    assert!(
        labels.contains(&"threadIdx") && !labels.contains(&"ThreadIdx"),
        "and it is the spelling that is offered"
    );
}
/// **A module implementation unit sees the interface unit's declarations without importing it.**
///
/// `math.cpp` writes `module math;` (no `export`, no `import`) and defines `Vec2::length`, whose body reads `x_` — a
/// member only `math.cppm` declares. A compiler accepts that because a module implementation unit implicitly imports
/// its own module's interface unit, so the analysis has to model the same edge; it did not, and the reading of a real
/// project was measured: `x_` and `square(x_)` resolved to nothing, every hover in the file was empty, and a
/// completion inside a member function listed two hundred names, all of them macros and functions from the headers
/// the file includes and not one member of `Vec2`.
#[test]
fn an_implementation_unit_sees_its_interface_units_declarations() {
    let interface_text = "export module math;\n\
                          export struct Vec2 {\n\
                          \x20   double x_;\n\
                          \x20   double square(double value) const { return value * value; }\n\
                          \x20   double length() const;\n\
                          };\n";
    let unit_text = "module;\n\
                     #include <cmath>\n\
                     module math;\n\
                     double Vec2::length() const { return std::sqrt(square(x_)); }\n";

    let files = MemoryFiles::new()
        .with_file("/p/math.cppm", interface_text)
        .with_file("/p/math.cpp", unit_text);
    let fixture = Memory::new("implementation-unit", &files);
    let mut session = fixture.session();
    session.add_project_files([
        std::path::PathBuf::from("/p/math.cppm"),
        std::path::PathBuf::from("/p/math.cpp"),
    ]);
    session.did_open("/p/math.cpp", unit_text);
    session.index_everything();
    // **The read the server does before answering a name question**: `import`s, and now the implementation unit's own
    // interface.
    session.read_the_modules_a_file_imports(std::path::Path::new("/p/math.cpp"));
    session.index_everything();
    while session.pending_work() > 0 {
        session.advance(64);
    }

    let path = std::path::PathBuf::from("/p/math.cpp");
    let view = session.view_of_the_file(&path).expect("a view");

    // **`x_` is a member of `Vec2`**, and it is declared in the interface unit alone.
    let at = unit_text.find("x_)").expect("the fixture") + 1;
    let typed = session.type_at(&view, crate::file::coordinates::ReadingOffset::new(at));
    assert!(
        matches!(&typed, Known::Yes(found) if found.type_of.contains("double")),
        "`x_` must have the type the interface unit gives it: {typed:?}"
    );

    // **And a member function of the class completes with its members**, not with the headers' macros.
    let at = unit_text.find("sqrt(").expect("the fixture") + "sqrt(".len();
    let members = session.member_completions(&view, crate::file::coordinates::FileOffset::new(at));
    if let Known::Yes(members) = members {
        let names: Vec<&str> = members
            .members
            .members
            .iter()
            .map(|member| member.fact.name.as_str())
            .collect();
        assert!(
            names.contains(&"x_") || names.contains(&"square"),
            "a member of `Vec2` must be offered: {names:?}"
        );
    }
}
/// **A module's interface unit is a translation unit**: a header it includes can define what a later `#if` asks.
///
/// This is the shape GCC ships the standard module in, in miniature. `bits/std.cc` is `module;` +
/// `#include <bits/stdc++.h>` + `export module std;` + a few thousand `using std::x;` re-exports, and
/// `bits/stdc++.h`'s standard-header block is guarded by `#if _GLIBCXX_HOSTED` — a macro that `bits/c++config.h`
/// defines and that the headers *above* the block include first.
///
/// The module walk recorded *where* each include led and never folded a file's own definitions into its state, so
/// `_GLIBCXX_HOSTED` read as undefined, the block answered `Inactive`, and `#include <vector>` was dropped. Measured on
/// `test_module` with MinGW GCC 15: `include/c++/vector` was not in the visible set, `std::vector` had only the
/// `using std::vector;` re-export as its fact, and the member list was empty — "the class is out of the index".
#[test]
fn a_modules_includes_define_what_a_later_condition_asks() {
    let interface_text = "module;\n\
                          #include \"feature.h\"\n\
                          #include \"library.h\"\n\
                          export module std;\n\
                          export namespace std\n\
                          {\n\
                          \x20   using std::vector;\n\
                          }\n";
    let consumer_text = "import std;\nvoid f() { std::vector<int> v; v.push_back(1); }\n";

    let files = MemoryFiles::new()
        .with_file("/p/std.cppm", interface_text)
        .with_file("/p/feature.h", "#define FEATURE 1\n")
        .with_file(
            "/p/library.h",
            "#if FEATURE\n#include \"detail.h\"\n#endif\n",
        )
        .with_file(
            "/p/detail.h",
            "namespace std { template <class T> struct vector { void push_back(const T &value); }; }\n",
        )
        .with_file("/p/a.cpp", consumer_text);
    let fixture = Memory::new("a-modules-includes", &files);
    let mut session = fixture.session();
    session.add_project_files([
        std::path::PathBuf::from("/p/std.cppm"),
        std::path::PathBuf::from("/p/library.h"),
        std::path::PathBuf::from("/p/detail.h"),
        std::path::PathBuf::from("/p/a.cpp"),
    ]);
    session.did_open("/p/a.cpp", consumer_text);
    session.index_everything();
    // The read the server does before answering a name question, and the drain that follows it.
    session.read_the_modules_a_file_imports(std::path::Path::new("/p/a.cpp"));
    session.index_everything();
    while session.pending_work() > 0 {
        session.advance(64);
    }

    let path = std::path::PathBuf::from("/p/a.cpp");
    let view = session.view_of_the_file(&path).expect("a view");

    // **The class is what `std::vector` names**, not the re-export in the interface unit.
    let at = consumer_text.find("push_back").expect("the fixture") + 2;
    let member = session.member_completions(&view, crate::file::coordinates::FileOffset::new(at));
    let Known::Yes(member) = member else {
        panic!("`v.` must be answered: {member:?}");
    };
    assert_eq!(
        member.class, "std::vector",
        "the object's type is the class the header declares"
    );
    assert_eq!(
        member.members.members.len(),
        1,
        "and its member list is the class's: {:?}",
        member
            .members
            .members
            .iter()
            .map(|member| member.fact.name.as_str())
            .collect::<Vec<_>>()
    );
}

/// **A cook that outlived the text it was made from is dropped.**
///
/// Reported from an editor, and the second half of "编辑不一定改变诊断": a `didChange` deleting a `;` was followed by
/// one pull, and the pull answered **`reading Cooked, 0 error(s)`** — a cooked reading of the *previous* text,
/// filed under the current one. The cause is the shape of cooking itself: it is two halves under two locks
/// (`render_a_cooked` then `commit_a_cooked`), and the pump claims a file, renders it in the background, and
/// commits — so an edit that lands in between is committed *over*. Nothing re-cooks a file that has a cooked
/// reading, which is what made it permanent rather than momentary.
///
/// The commit now compares the hash of the text the rendering was made from against the file's text, and this test
/// is that comparison driven by hand: claim, edit, render, commit.
#[test]
fn a_cook_of_text_that_has_since_changed_is_not_filed() {
    let files = MemoryFiles::new().with_file("/p/a.cpp", "int main() { return 0; }\n");
    let memory = Memory::new("stale-cook", &files);
    let mut session = memory.session();
    let path = PathBuf::from("/p/a.cpp");
    session.add_project_files([path.clone()]);
    session.load(&path);
    session.index_everything();

    // **The claim**, which is what the pump does before it renders: materials carry the text *and* its hash.
    let materials = session
        .cooking_materials(&path)
        .expect("the file has a summary and a unit");
    let rendered = session
        .render_a_cooked(&materials)
        .expect("the renderer reads the file's own text");

    // **The edit**, between the two halves — exactly where a reader's keystroke lands.
    let changed = "int main() { return 0 }\n";
    session.did_change(&path, changed);

    // The commit must refuse it: this rendering is of text nobody has any more.
    assert!(
        session.commit_a_cooked(rendered).is_none(),
        "a rendering of text that has since changed may not be filed under the new text"
    );
    assert!(
        session.diagnostics(&path).is_none(),
        "and the file has no cooked reading, so nothing answers with the old text's errors"
    );

    // **The honest path still works**: cook the new text and the answer is the new text's.
    session.did_change(&path, "int main() { return 0; }\n");
    session.advance(64);
    assert!(
        session.cook(&path).is_some(),
        "the pump re-cooks the file it dropped"
    );
    let found = session
        .diagnostics(&path)
        .expect("a cooked reading of the current text");
    assert_eq!(
        found.errors.len(),
        0,
        "the text has its `;` back: {:?}",
        found.errors
    );
}