cpp_code_analysis 0.4.0

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

use cpp_code_analysis::{
    CompilerConfig, ItemKind, Known, MemoryFiles, OpenDocuments, Session, SessionFiles,
    UnknownReason, WatchFilter,
};

const HEADER: &str = "int from_the_header(int value);\n";
const SOURCE: &str = "\
#include \"b.h\"
struct Widget { int size; };
int f() {
    int local_variable = 1;
    Widget w;
    return local_variable + w.size;
}
";

fn session_with_the_project() -> Session<MemoryFiles> {
    let memory = MemoryFiles::new()
        .with_file("/p/a.cpp", SOURCE)
        .with_file("/p/b.h", HEADER);
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([
        std::path::PathBuf::from("/p/a.cpp"),
        std::path::PathBuf::from("/p/b.h"),
    ]);

    // **Two pumps, and the ask between them, because that is the contract now.**
    //
    // A completion is a question about **meaning**, so it is answered from a rendering — and a rendering is built
    // because something asked for one. The first pump reads the files into the index; `view` is the ask (it answers
    // `None` and queues what it could not answer, deliberately: a query must not pay a unit walk, a preprocess and a
    // render); the second pump is what builds it. Every test in this file goes through this one helper, so the
    // arrangement is stated once here rather than in fifty `expect` messages.
    //
    // This is not a test artefact. It is what a server does between two keystrokes, and what the deferral contract
    // exists for: `None` now, the reading after the work the ask queued.
    session.index_everything();
    let _ = session.view("/p/a.cpp");
    let _ = session.view("/p/b.h");
    session.index_everything();

    session
}

/// **A reading of `path` that a completion can be asked against** — the pump, the ask, the pump.
///
/// Owned rather than borrowed, which matters: `Session::view` takes `&self` and the query takes `&self` too, but the
/// ask has to happen on a session nothing is borrowing yet, so a test that wrote
/// `session.completions(&session.view(..)?, ..)` would have the borrow in the argument position. Returning the view
/// by value is what lets the two calls sit on one line.
///
/// The three steps are the contract, not scaffolding: a completion is a question about **meaning**, meaning is
/// answered from a rendering, a rendering is built because something asked, and `Session::view` answers `None` and
/// queues when it has none. Every fixture in this file that builds its own session goes through here, so the
/// arrangement is stated once.
fn cooked_view(session: &mut Session<MemoryFiles>, path: &str) -> cpp_code_analysis::FileView {
    // **The three steps, and the first is not optional for a file nothing has read.**
    //
    // A completion is a question about **meaning**, so it is answered from a rendering, and a rendering is built
    // because something asked. `want_cooked_reading` is the ask that also queues *reading* — a cook is built out of
    // a summary, so a file the index has never described needs both, and a fixture that merely `load`s a file has
    // given it neither. Measured without this line: `indexed false, pending 0, backlog 0`, and every `view` `None`.
    //
    // This is the product's own contract, not scaffolding: it is what a server does between two keystrokes for a
    // file it has not read yet.
    session.want_cooked_reading(std::path::Path::new(path));
    session.index_everything();
    session
        .view(path)
        .unwrap_or_else(|| panic!("{path} asked to be read and cooked, and the pump did both"))
}

/// The names offered at an offset, in the order the query returned them.
fn offered_at(offset: usize) -> Option<Vec<String>> {
    let mut session = session_with_the_project();
    let view = cooked_view(&mut session, "/p/a.cpp");

    match session.name_completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(offset),
    ) {
        Known::Yes(found) => Some(
            found
                .names
                .iter()
                .map(|offered| offered.fact.name.to_string())
                .collect(),
        ),
        _ => None,
    }
}

/// **A cursor with nothing written yet is where completion lives.** After `return `, the list has to hold the
/// function's own local — that is what go-to-definition already resolves, so the analysis has it — and the names
/// the header contributes, which are the ones a reader cannot see in this file at all.
#[test]
fn a_blank_cursor_offers_the_locals_and_the_included_names() {
    let offset = SOURCE.find("return ").expect("the fixture") + "return ".len();
    let names = offered_at(offset).expect("a blank cursor in a body is answerable");

    assert!(
        names.contains(&"local_variable".to_string()),
        "the local declared above the cursor: {names:?}"
    );
    assert!(
        names.contains(&"w".to_string()),
        "and the other local: {names:?}"
    );
    assert!(
        names.contains(&"from_the_header".to_string()),
        "a name from the included header: {names:?}"
    );
    assert!(
        names.contains(&"Widget".to_string()),
        "and its type: {names:?}"
    );
    assert!(
        names.contains(&"f".to_string()),
        "and the function being written: {names:?}"
    );
}

/// The same list while the name is being typed: the local is still first — the innermost scope has depth 0 — which
/// is what makes the client's own filtering show it at the top.
#[test]
fn a_local_is_offered_while_it_is_being_typed() {
    let offset = SOURCE.find("local_variable + w").expect("the fixture") + "local".len();
    let mut session = session_with_the_project();
    let view = cooked_view(&mut session, "/p/a.cpp");

    if std::env::var_os("CPPLS_TRACE_COORDINATES").is_some() {
        let reading = view
            .reading_offset_of(cpp_code_analysis::file::coordinates::FileOffset::new(
                offset,
            ))
            .expect("the cursor is in the rendering");
        // **The token's own start in each text**, which is the anchor that settles this. The file's cursor sits on
        // the `_` of `local_variable`; if the rendering's offset for that same cursor lands on the *start* of the
        // token, then the two rulers differ by more than the whitespace the rendering collapsed — and the number to
        // compare is the distance from the token's start in each text.
        let in_file = SOURCE.find("local_variable + w").expect("the use") + 5;
        let in_rendering = view.source.find("local_variable + w").expect("the use") + 5;
        eprintln!(
            "cursor: file {in_file} -> reading {reading} (the same spot is {in_rendering} in the rendering)\n  \
             the token starts at {} in the file and {} in the rendering\n  \
             the two cursors differ by {}; the two token starts differ by {}",
            SOURCE.find("local_variable + w").expect("the use"),
            view.source.find("local_variable + w").expect("the use"),
            in_file as i64 - reading.get() as i64,
            SOURCE.find("local_variable + w").expect("the use") as i64
                - view.source.find("local_variable + w").expect("the use") as i64
        );
    }

    let Known::Yes(found) = session.name_completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(offset),
    ) else {
        panic!("a half-written name is answerable");
    };

    assert_eq!(found.prefix, "local");
    let local = found
        .names
        .iter()
        .find(|offered| offered.fact.name == "local_variable")
        .expect("the local is offered");
    assert_eq!(local.depth, 0, "from the scope the cursor is in");
}

/// **A comment or a literal is not code**, and the list there would be a list of names to type into prose.
#[test]
fn a_comment_and_a_literal_offer_nothing() {
    let commented = "int f() { // a note\n    return 0;\n}\n";
    let memory = MemoryFiles::new().with_file("/p/a.cpp", commented);
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.load("/p/a.cpp");
    let view = cooked_view(&mut session, "/p/a.cpp");

    let inside_the_comment = commented.find("// a").expect("the fixture") + "// a".len();
    assert!(
        !matches!(
            session.name_completions(
                &view,
                cpp_code_analysis::file::coordinates::FileOffset::new(inside_the_comment)
            ),
            Known::Yes(_)
        ),
        "a name in a comment is not code"
    );
}

/// **A member position belongs to the member query.** After `w.` the names in scope are not the answer — `size`
/// is — so the name query declines there, and the handler's dispatch is what picks the right one.
#[test]
fn a_member_position_is_not_a_name_position() {
    let offset = SOURCE.find("w.size").expect("the fixture") + 2;
    let mut session = session_with_the_project();
    let view = cooked_view(&mut session, "/p/a.cpp");

    assert!(
        !matches!(
            session.name_completions(
                &view,
                cpp_code_analysis::file::coordinates::FileOffset::new(offset)
            ),
            Known::Yes(_)
        ),
        "the member query owns this position"
    );

    let Known::Yes(members) = session.member_completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(offset),
    ) else {
        panic!("the member query answers it");
    };
    assert!(
        members
            .members
            .members
            .iter()
            .any(|member| member.fact.name == "size"),
        "with the members of the object's type"
    );
}

/// **A class split across two files: its member function's body must still see the members.**
///
/// The class is declared in a header and its member function is defined in a `.cpp` — the ordinary layout of C++
/// code, and the one a user reported as offering **nothing** inside the definition. What makes it interesting is
/// where the answer has to come from: the members are declared in a file the cursor is not in, so this is the
/// "report is about this file, the knowledge is the project's" boundary applied to completion.
///
/// The cursor sits after `this->`, which is the plainest way to ask: `this` has the enclosing class's type, and the
/// enclosing class is not declared in this file.
///
/// # What was wrong, and what it took
///
/// Two things, found in that order.
///
/// **The fixture did not include the header.** A query is answered from the files the asking file can see, and a
/// `.cpp` whose text never `#include`s its own header sees nothing in it — so no scope-tree reading could have made
/// this expectation satisfiable. The include is the fixture's, not the reading's.
///
/// **`void Widget::grow(…)` opened a scope that belonged to no class.** When the qualifier names a class *this file*
/// has built, the function scope hangs off that class and inherits its qualified name. When it does not — the
/// ordinary layout, the class in a header — the scope was created **unnamed**, and `this` is typed from the cursor's
/// innermost scope's qualified name: `Unknown(UnknownType("this"))`, measured. The scope now carries the definition's
/// own spelling (`Widget::grow`) even though `Widget` is not a scope here, which is exactly what a reader needs to
/// answer *which* class the body belongs to — see `read_the_inside_of_a_foreign_definition`.
#[test]
fn a_member_function_defined_in_another_file_sees_its_class() {
    let header = "\
class Widget {
public:
    int size;
    void grow(int by);
};
";
    // **The include is what makes the header's members reachable at all** — a query is answered from the files the
    // asking file can see, and a `.cpp` that never includes its own header sees nothing in it. The fixture was
    // written without this line, which is why the expectation could not be met however the scope tree was read.
    let source = "\
#include \"widget.h\"
void Widget::grow(int by) {
    this->
}
";
    let mut memory = MemoryFiles::new()
        .with_file("/p/widget.h", header)
        .with_file("/p/widget.cpp", source);
    memory = memory.with_file("/p/a.cpp", "int main() { return 0; }\n");
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([
        std::path::PathBuf::from("/p/widget.h"),
        std::path::PathBuf::from("/p/widget.cpp"),
        std::path::PathBuf::from("/p/a.cpp"),
    ]);
    session.want_cooked_reading(std::path::Path::new("/p/widget.cpp"));
    session.index_everything();

    let offset = source.find("this->").expect("the fixture") + "this->".len();
    let view = cooked_view(&mut session, "/p/widget.cpp");
    let offered: Vec<String> = match session.member_completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(offset),
    ) {
        Known::Yes(members) => members
            .members
            .members
            .iter()
            .map(|member| member.fact.name.to_string())
            .collect(),
        other => panic!("the member query must answer here: {other:?}"),
    };

    assert!(
        offered.iter().any(|name| name == "size"),
        "the class's own members come from the file that declares them: {offered:?}"
    );
}
/// **A macro from a header ranks as a header's, not as the reader's own.**
///
/// Reported as "`nullptr` is not in the completion list": in a file including four standard headers, the macro tail
/// was filed with `NameProvenance::ThisFile` — every macro, including the ones from `<atomic>` — so a hundred and
/// fifty MSVC names tied with the reader's own locals and ranked **above every keyword**. Measured at an argument of
/// such a file, `nullptr` was item **102 of 266**; it is **59 of 238** now, and typing `nul` puts it first.
///
/// Two claims, because they failed for two reasons: the ranking (a keyword must come before a header's macro), and
/// the identity (a macro's `(file, offset)` must name the header that wrote it, or `completionItem/resolve` reads a
/// declaration at that offset in the *cursor's* file).
#[test]
fn a_header_s_macro_ranks_after_a_keyword_and_names_its_own_file() {
    const HEADER: &str = "#define FROM_THE_HEADER 1\n";
    // The cursor's line is **indented and otherwise empty**, which is where it is in a body being typed. Written as
    // one escaped literal rather than a multi-line one because the indentation is inside the string: as a real blank
    // line of four spaces it is trailing whitespace in this file, which the repository's own hook refuses.
    const SOURCE: &str = "#include \"h.h\"\nint main() {\n    \n}\n";
    let memory = MemoryFiles::new()
        .with_file("/p/h.h", HEADER)
        .with_file("/p/a.cpp", SOURCE);
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([
        std::path::PathBuf::from("/p/a.cpp"),
        std::path::PathBuf::from("/p/h.h"),
    ]);
    session.index_everything();

    let at = SOURCE.find("\n    \n").expect("the blank line") + 5;
    let labels = labels_at(&mut session, "/p/a.cpp", at);
    let keyword = position(&labels, "nullptr");
    let macro_at = position(&labels, "FROM_THE_HEADER");
    assert!(
        keyword < macro_at,
        "a keyword is something the reader can always write; a header's macro is not nearer than it: \
         `nullptr` at {keyword}, `FROM_THE_HEADER` at {macro_at}"
    );

    let view = cooked_view(&mut session, "/p/a.cpp");
    let offered = match session.name_completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(at),
    ) {
        Known::Yes(found) => found,
        other => panic!("a blank cursor in a body is answerable: {other:?}"),
    };
    let macro_name = offered
        .names
        .iter()
        .find(|name| name.fact.name == "FROM_THE_HEADER")
        .expect("the header's macro is offered");
    assert_eq!(
        macro_name.file,
        std::path::PathBuf::from("/p/h.h"),
        "a macro's identity is the file that wrote it, or the item resolves against a stranger"
    );
}

/// **A `std::` list does not begin with the implementation's own names** — the reader's rule, asked for with a
/// screenshot.
///
/// The reserved-name rule already existed, but only on the **unqualified** list: a written scope (`std::`) is answered
/// straight from the scope's declarations, so `_Adl_verify_range`, `_Add_alloc_size` and `_Adjust_manually_vector_aligned`
/// — MSVC's internals — filled the list of a reader typing `std::`. The rule asked for is the reader's own: **if what
/// has been typed does not begin with `_`, do not offer what does**; typing `_` brings them back, which is what keeps
/// every one of them reachable for somebody who has a reason to reach for one.
#[test]
fn a_scope_list_does_not_open_with_the_implementations_names() {
    const FIXTURE: &str = "\
namespace std {
    void _Adl_verify_range();
    void _Add_alloc_size();
    void swap();
    void sort();
}
int main() {
    std::
}
";
    let memory = MemoryFiles::new().with_file("/p/a.cpp", FIXTURE);
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.load("/p/a.cpp");

    let bare = labels_at(
        &mut session,
        "/p/a.cpp",
        FIXTURE.find("std::").expect("the fixture") + 5,
    );
    assert!(
        bare.iter().any(|label| label == "swap"),
        "the scope's ordinary names are offered: {bare:?}"
    );
    assert!(
        !bare.iter().any(|label| label.starts_with('_')),
        "and none of the implementation's: {bare:?}"
    );

    // **Typing the underscore brings them back**, which is what makes the rule safe rather than a hole.
    const ASKED: &str = "\
namespace std {
    void _Adl_verify_range();
    void swap();
}
int main() {
    std::_
}
";
    let memory = MemoryFiles::new().with_file("/p/a.cpp", ASKED);
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.load("/p/a.cpp");
    let asked = labels_at(
        &mut session,
        "/p/a.cpp",
        ASKED.find("std::_").expect("the fixture") + 6,
    );
    assert!(
        asked.iter().any(|label| label == "_Adl_verify_range"),
        "a reader typing `_` is asking for exactly these: {asked:?}"
    );
}

/// **The names the implementation owns are not offered**, and the user's own underscored names still are.
///
/// The standard's three rules (`__name`, `_Name`, `_name` in the global name space), applied where a *suggestion*
/// is made rather than where a question is answered: a jump, a hover and a rename still find a reserved name. This
/// is the rule that took `_ALLOC_MASK`, `_Alty` and `_Apply_annotation` off a `std::string`'s member list — half of
/// its 202 entries — and 601 names off one real file's list at a blank line in a function body.
#[test]
fn the_implementations_names_are_not_offered_but_the_users_are() {
    const FIXTURE: &str = "\
struct Widget { int size; int _mine; };
int _global_underscored;
int __mine_anywhere;
int _Upper_anywhere;
int f() {
    int _local_underscored = 1;
    Widget w;
    w.
}
";
    let memory = MemoryFiles::new().with_file("/p/a.cpp", FIXTURE);
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.load("/p/a.cpp");
    let view = cooked_view(&mut session, "/p/a.cpp");

    // The **name** list, asked inside the body: the user's local is there, the reserved globals are not.
    let known = match session.name_completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(
            FIXTURE.find("w.").expect("the fixture"),
        ),
    ) {
        Known::Yes(found) => found
            .names
            .iter()
            .map(|offered| offered.fact.name.to_string())
            .collect::<Vec<_>>(),
        other => panic!("a blank cursor in a body is answerable: {other:?}"),
    };

    for reserved in ["__mine_anywhere", "_Upper_anywhere", "_global_underscored"] {
        assert!(
            !known.iter().any(|name| name == reserved),
            "`{reserved}` is reserved to the implementation: {known:?}"
        );
    }
    assert!(
        known.iter().any(|name| name == "_local_underscored"),
        "a local `_name` is the user's own — only the *global* name space reserves it: {known:?}"
    );

    // The **member** list of a class the user wrote: `_mine` is the user's own member and is offered, while the
    // rule still takes MSVC's `_Alty`/`_ALLOC_MASK` off a `std::string`.
    let Known::Yes(members) = session.member_completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(
            FIXTURE.find("w.").expect("the fixture") + 2,
        ),
    ) else {
        panic!("a member access is answerable");
    };
    let names: Vec<&str> = members
        .members
        .members
        .iter()
        .map(|member| member.fact.name.as_str())
        .collect();
    assert!(names.contains(&"size"), "the ordinary member: {names:?}");
    assert!(
        names.contains(&"_mine"),
        "and the user's own underscored member: {names:?}"
    );
}

// ------------------------------------------------------------------------------------------------------------
// The layer above the two queries: what is **offered**, and in what order.
// ------------------------------------------------------------------------------------------------------------

/// A fixture with all four distances in it: a local, a name at file scope, a name from a header the file includes
/// directly, and a name from a header only *that* header includes.
///
/// The four are the whole of the ranking, and a fixture that had only some of them could not tell the order the
/// layers produce from the alphabet — which is exactly the mistake this feature exists to fix.
const RANKED_CPP: &str = "\
#include \"near.h\"
int at_file_scope;
int f() {
    int in_the_body = 1;
    return in_the_body + at_file_scope;
}
";

/// Included by `RANKED_CPP`.
const NEAR_H: &str = "#include \"far.h\"\nint from_the_near_header;\n";

/// Included by `near.h`, so a name from here is two include hops away.
const FAR_H: &str = "int from_the_far_header;\n";

fn ranked_session() -> Session<MemoryFiles> {
    let memory = MemoryFiles::new()
        .with_file("/p/a.cpp", RANKED_CPP)
        .with_file("/p/near.h", NEAR_H)
        .with_file("/p/far.h", FAR_H);
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([
        std::path::PathBuf::from("/p/a.cpp"),
        std::path::PathBuf::from("/p/near.h"),
        std::path::PathBuf::from("/p/far.h"),
    ]);
    session.index_everything();

    session
}

/// The labels `Session::completions` offers at an offset, in the order it produced them.
///
/// Takes `&mut Session` and goes through [`cooked_view`], because the reading a completion is answered from is
/// built on request — a helper that read `session.view(path)` directly would be asking for a reading nothing had
/// asked for, and would panic on the `None` the deferral contract returns.
fn labels_at(session: &mut Session<MemoryFiles>, path: &str, offset: usize) -> Vec<String> {
    let view = cooked_view(session, path);

    session
        .completions(
            &view,
            cpp_code_analysis::file::coordinates::FileOffset::new(offset),
        )
        .items
        .iter()
        .map(|item| item.label.clone())
        .collect()
}

/// The position of a label in a list, with a message that shows the whole list when it is missing.
fn position(labels: &[String], wanted: &str) -> usize {
    labels
        .iter()
        .position(|label| label == wanted)
        .unwrap_or_else(|| panic!("`{wanted}` is not offered at all: {labels:?}"))
}

/// **The order is the feature.** Four declarations a compiler considers in one order and a reader means in another
/// — the local, this file's, the header's, and what that header includes — and the list has to show them in that
/// order rather than alphabetically or in whatever order the index happened to hold them.
///
/// This is what fixes "it offers nearly everything": the names were never missing, they were *buried*. Measured
/// before the change, a blank line in one real 78-line file offered **692** names of which **6** came from the
/// file itself.
#[test]
fn the_nearest_declaration_comes_first() {
    let mut session = ranked_session();
    let cursor = RANKED_CPP.find("return ").expect("the fixture") + "return ".len();

    let labels = labels_at(&mut session, "/p/a.cpp", cursor);

    let body = position(&labels, "in_the_body");
    let file = position(&labels, "at_file_scope");
    let near = position(&labels, "from_the_near_header");
    let far = position(&labels, "from_the_far_header");

    // The provenance is quoted in the message rather than asserted on directly: it is *why* the order is what it
    // is, and a failure of the order is the thing worth reading.
    let view = cooked_view(&mut session, "/p/a.cpp");
    let provenance: Vec<String> = match session.name_completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(cursor),
    ) {
        Known::Yes(found) => found
            .names
            .iter()
            .filter(|name| name.fact.name.starts_with("from_"))
            .map(|name| format!("{}: {:?}", name.fact.name, name.from))
            .collect(),
        other => panic!("{other:?}"),
    };

    assert!(
        body < file,
        "the local is in front of the file-scope name: {labels:?}"
    );
    assert!(
        file < near,
        "and this file's name is in front of the header's: {labels:?}"
    );
    assert!(
        near < far,
        "and a header the file includes is in front of one that header includes: {provenance:?}"
    );
}

/// The same order, one keystroke later: typing three letters must not reorder the list, because the client filters
/// what it was given and a filter cannot un-bury a name.
#[test]
fn typing_a_prefix_does_not_reorder_the_list() {
    let mut session = ranked_session();
    let cursor = RANKED_CPP.find("in_the_body + at").expect("the fixture") + "in_the_body + ".len();

    let labels = labels_at(&mut session, "/p/a.cpp", cursor);
    let preview: Vec<&String> = labels.iter().take(3).collect();

    assert!(
        preview.iter().any(|label| label.as_str() == "in_the_body"),
        "the local is still at the top with `at` typed: {labels:?}"
    );
}

/// **A blank line in a body offers the language's own vocabulary**, which is the other half of what was missing:
/// the keywords and the snippet bodies. `if` is offered as a **snippet** (it writes the braces and puts the cursor
/// inside them) rather than as a bare keyword beside it.
#[test]
fn a_blank_line_in_a_body_offers_the_keywords_and_the_snippets() {
    let mut session = ranked_session();
    let cursor = RANKED_CPP.find("return ").expect("the fixture") + "return ".len();

    let labels = labels_at(&mut session, "/p/a.cpp", cursor);
    let view = cooked_view(&mut session, "/p/a.cpp");
    match session.members_of(&view, "Source") {
        cpp_code_analysis::Known::Yes(list) => println!(
            "members_of(Source) → {:?}",
            list.members
                .iter()
                .map(|m| m.fact.name.to_string())
                .collect::<Vec<_>>()
        ),
        other => println!("members_of(Source) → {other:?}"),
    }
    let offered = session.completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(cursor),
    );

    assert!(labels.contains(&"while".to_string()), "{labels:?}");
    assert!(labels.contains(&"if".to_string()), "{labels:?}");
    assert!(labels.contains(&"const".to_string()), "{labels:?}");
    assert!(labels.contains(&"size_t".to_string()), "{labels:?}");

    let if_item = offered
        .items
        .iter()
        .find(|item| item.label == "if")
        .expect("`if` is offered");
    assert_eq!(if_item.kind, ItemKind::Snippet);
    assert!(if_item.snippet, "and it is a snippet body, not a keyword");
    assert!(
        if_item.insert.contains("$0"),
        "with a hole for the cursor: {}",
        if_item.insert
    );
    assert_eq!(
        offered
            .items
            .iter()
            .filter(|item| item.label == "if")
            .count(),
        1,
        "and exactly once — the bare keyword is not offered beside it"
    );
}

/// **The module words are offered**, which the lexer's vocabulary alone could not do.
///
/// Reported from an editor: typing `im` at file scope in a file whose first line is `import std;` offered
/// `if`/`inline`/`int` and **no `import`**. `import` and `module` are *context-sensitive* keywords — the lexer leaves
/// them as identifiers because `int import = 1;` compiles — so a completion table built from `is_keyword` never had
/// them. `export` was there, which is what made the gap look like a ranking problem.
#[test]
fn the_module_words_are_offered() {
    const FIXTURE: &str = "\
import std;
int main() {
    im
}
";
    let memory = MemoryFiles::new().with_file("/p/a.cpp", FIXTURE);
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.load("/p/a.cpp");
    let at = FIXTURE.find("\n    im").expect("the fixture") + "\n    im".len();
    let labels = labels_at(&mut session, "/p/a.cpp", at);
    assert!(
        labels.iter().any(|label| label == "import"),
        "`import` is a word this file can write: {labels:?}"
    );

    // …and `module`, from the same tier, at the same position.
    const MODULE: &str = "\
int main() {
    mod
}
";
    let memory = MemoryFiles::new().with_file("/p/a.cpp", MODULE);
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.load("/p/a.cpp");
    let at = MODULE.find("\n    mod").expect("the fixture") + "\n    mod".len();
    let labels = labels_at(&mut session, "/p/a.cpp", at);
    assert!(
        labels.iter().any(|label| label == "module"),
        "`module` is a word this file can write: {labels:?}"
    );
}

/// **A keyword is not a name and a name is not a keyword**, so the two are ordered separately: a snippet the
/// reader is about to write comes after their own variables and before a name from `<cstdio>`.
#[test]
fn a_keyword_sorts_between_the_files_names_and_the_headers() {
    let mut session = ranked_session();
    let cursor = RANKED_CPP.find("return ").expect("the fixture") + "return ".len();

    let labels = labels_at(&mut session, "/p/a.cpp", cursor);
    let file = position(&labels, "at_file_scope");
    let keyword = position(&labels, "while");
    let far = position(&labels, "from_the_far_header");

    assert!(
        file < keyword && keyword < far,
        "this file's names, then the language's words, then the headers': {labels:?}"
    );
}

/// **After a `#` the answer is the directives**, and a half-written directive is *replaced* rather than extended —
/// `#inc` completed to `include` must not become `#incinclude`.
#[test]
fn after_a_hash_the_directives_are_offered() {
    const FIXTURE: &str = "#inc\nint x;\n";
    let memory = MemoryFiles::new().with_file("/p/a.cpp", FIXTURE);
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.load("/p/a.cpp");

    let view = cooked_view(&mut session, "/p/a.cpp");
    let cursor = FIXTURE.find("inc").expect("the fixture") + "inc".len();
    let found = session.completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(cursor),
    );

    let include = found
        .items
        .iter()
        .find(|item| item.label == "include")
        .unwrap_or_else(|| panic!("`include` is offered: {:?}", found.items));

    assert_eq!(
        include.replace.start_offset, 1,
        "the edit starts at the `i` of `inc`"
    );
    assert_eq!(include.replace.length, 3, "and covers all of it");
    assert!(
        !found.items.iter().any(|item| item.label == "int"),
        "and no language name is offered in a directive's own name: {:?}",
        found.items
    );
}

/// `#endif` takes no argument, so a cursor after it gets **nothing** rather than the file's names — a list there
/// would offer things that cannot follow.
#[test]
fn a_directive_that_takes_no_argument_offers_nothing() {
    const FIXTURE: &str = "#if 0\n#endif \nint x;\n";
    let memory = MemoryFiles::new().with_file("/p/a.cpp", FIXTURE);
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.load("/p/a.cpp");

    let view = cooked_view(&mut session, "/p/a.cpp");
    let cursor = FIXTURE.find("#endif ").expect("the fixture") + "#endif ".len();

    assert!(
        session
            .completions(
                &view,
                cpp_code_analysis::file::coordinates::FileOffset::new(cursor)
            )
            .items
            .is_empty(),
        "nothing may follow `#endif`"
    );
}

/// `#define` takes a **name**, so the argument position offers the program's names and not the language's words: a
/// macro is called an identifier, and `while` is not one.
#[test]
fn a_defines_argument_offers_names_rather_than_keywords() {
    const FIXTURE: &str = "int already_a_name;\n#define \n";
    let memory = MemoryFiles::new().with_file("/p/a.cpp", FIXTURE);
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.load("/p/a.cpp");

    let view = cooked_view(&mut session, "/p/a.cpp");
    let cursor = FIXTURE.find("#define ").expect("the fixture") + "#define ".len();
    let labels = labels_at(&mut session, "/p/a.cpp", cursor);

    assert_eq!(
        session
            .completions(
                &view,
                cpp_code_analysis::file::coordinates::FileOffset::new(cursor)
            )
            .prefix,
        "",
        "nothing is written after `#define ` yet"
    );
    assert!(labels.contains(&"already_a_name".to_string()), "{labels:?}");
    assert!(
        !labels.contains(&"while".to_string()),
        "a keyword is not a macro name: {labels:?}"
    );
}

/// **A `#include` is completed from the search path**, and a project header is offered beside the search path's —
/// spelled relative to the project root, which is how a reader writes it.
#[test]
fn an_include_offers_the_projects_headers() {
    // The cursor is inside the name, so the edit **replaces** it: `#include <near` completed to `near.h` must not
    // become `#include <nearnear.h`.
    let typed = "#include <near\nint x;\n";
    let memory = MemoryFiles::new().with_file("/p/a.cpp", typed);
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([
        std::path::PathBuf::from("/p/a.cpp"),
        std::path::PathBuf::from("/p/near.h"),
    ]);
    session.index_everything();

    let view = cooked_view(&mut session, "/p/a.cpp");
    let cursor = typed.find("near").expect("the fixture") + "near".len();
    let found = session.completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(cursor),
    );

    let near = found
        .items
        .iter()
        .find(|item| item.label == "near.h")
        .unwrap_or_else(|| {
            panic!(
                "the project's own header is offered: {:?}",
                found.items.iter().map(|it| &it.label).collect::<Vec<_>>()
            )
        });

    assert_eq!(near.kind, ItemKind::Header);
    assert_eq!(
        near.replace.start_offset,
        typed.find("near").expect("the fixture")
    );
    assert_eq!(near.replace.length, 4, "the whole half-written name");
}

/// **A completion in a comment is empty**, and the same cursor one character earlier is not: the offset that
/// merely *touches* a comment's end is at the start of what follows it.
#[test]
fn a_comment_is_not_code() {
    const FIXTURE: &str = "int x; // a note here\n";
    let memory = MemoryFiles::new().with_file("/p/a.cpp", FIXTURE);
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.load("/p/a.cpp");

    let view = cooked_view(&mut session, "/p/a.cpp");
    let inside = FIXTURE.find("note").expect("the fixture");

    assert!(
        session
            .completions(
                &view,
                cpp_code_analysis::file::coordinates::FileOffset::new(inside)
            )
            .items
            .is_empty(),
        "a name in a comment is not code"
    );
    assert!(
        !session
            .completions(
                &view,
                cpp_code_analysis::file::coordinates::FileOffset::new(
                    FIXTURE.find('x').expect("the fixture") + 1
                )
            )
            .items
            .is_empty(),
        "and the declaration beside it is"
    );
}

/// **A member position offers the members and nothing else**, and the two distinctions a member *does* carry come
/// with it: a member function is a method rather than a free function, and a member an inherited class declares
/// says so.
#[test]
fn a_member_position_offers_the_members_with_their_distinctions() {
    const FIXTURE: &str = "\
struct Base { int inherited; };
struct Widget : Base { int size; void grow(); };
int f() {
    Widget w;
    w.
}
";
    let memory = MemoryFiles::new().with_file("/p/a.cpp", FIXTURE);
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.load("/p/a.cpp");

    let view = cooked_view(&mut session, "/p/a.cpp");
    let cursor = FIXTURE.find("w.").expect("the fixture") + 2;
    let found = session.completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(cursor),
    );

    let labels: Vec<&str> = found.items.iter().map(|item| item.label.as_str()).collect();
    assert!(labels.contains(&"size"), "{labels:?}");
    assert!(labels.contains(&"grow"), "{labels:?}");
    assert!(labels.contains(&"inherited"), "{labels:?}");
    assert!(
        !labels.contains(&"f"),
        "and not the names in scope, which cannot follow the operator: {labels:?}"
    );

    let size = position(
        &labels.iter().map(|it| it.to_string()).collect::<Vec<_>>(),
        "size",
    );
    let inherited = position(
        &labels.iter().map(|it| it.to_string()).collect::<Vec<_>>(),
        "inherited",
    );
    assert!(
        size < inherited,
        "the class's own member before the base's: {labels:?}"
    );

    let grow = found
        .items
        .iter()
        .find(|item| item.label == "grow")
        .expect("offered above");
    assert_eq!(grow.kind, ItemKind::Method, "a member function is a method");

    let inherited = found
        .items
        .iter()
        .find(|item| item.label == "inherited")
        .expect("offered above");
    assert!(
        inherited
            .detail
            .as_deref()
            .is_some_and(|detail| detail.contains("Base")),
        "and where an inherited member was declared is said: {inherited:?}"
    );
}

/// **`::` lists one scope**, and what it lists is *that* scope's names rather than everything in sight.
#[test]
fn a_qualified_name_lists_that_scope_only() {
    const FIXTURE: &str = "\
namespace one { struct Widget { int size; }; }
namespace two { struct Gadget { int weight; }; }
one::
";
    let memory = MemoryFiles::new().with_file("/p/a.cpp", FIXTURE);
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.load("/p/a.cpp");

    let view = cooked_view(&mut session, "/p/a.cpp");
    let cursor = FIXTURE.find("one::").expect("the fixture") + "one::".len();
    let found = session.completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(cursor),
    );

    assert_eq!(found.scope, "one");
    let labels: Vec<&str> = found.items.iter().map(|item| item.label.as_str()).collect();
    assert!(labels.contains(&"Widget"), "{labels:?}");
    assert!(
        !labels.contains(&"Gadget"),
        "another namespace's name is not in `one`: {labels:?}"
    );
    assert!(
        !labels.contains(&"while"),
        "and a keyword cannot follow a `::`: {labels:?}"
    );
}

/// A client that asks in the **middle** of a name filters by what is before the cursor and **replaces** the whole
/// spelling — the two are different fields and using one for both is what makes `w.si|ze` offer nothing.
#[test]
fn a_cursor_inside_a_name_filters_by_the_prefix_and_replaces_all_of_it() {
    const FIXTURE: &str = "\
struct Widget { int size; };
int f() { Widget w; w.size; }
";
    let memory = MemoryFiles::new().with_file("/p/a.cpp", FIXTURE);
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.load("/p/a.cpp");

    let view = cooked_view(&mut session, "/p/a.cpp");
    let at_the_member = FIXTURE.find("w.size").expect("the fixture");
    let cursor = at_the_member + 2 + "si".len();
    let found = session.completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(cursor),
    );

    assert_eq!(
        found.prefix, "si",
        "what filters is the part before the cursor"
    );
    assert_eq!(
        found.replace.start_offset,
        at_the_member + 2,
        "and what is replaced is the whole spelling"
    );
    assert_eq!(found.replace.length, 4, "`size`");
    assert!(
        found.items.iter().any(|item| item.label == "size"),
        "so the member is still offered while it is being typed"
    );
}

/// The **budget** is a payload bound, and the list says whether it was applied: a client that is told
/// `isIncomplete` about a capped list would re-ask for an answer that cannot change.
#[test]
fn a_short_list_is_not_marked_truncated() {
    let mut session = ranked_session();
    let cursor = RANKED_CPP.find("return ").expect("the fixture") + "return ".len();
    let view = cooked_view(&mut session, "/p/a.cpp");

    assert!(
        !session
            .completions(
                &view,
                cpp_code_analysis::file::coordinates::FileOffset::new(cursor)
            )
            .truncated,
        "three headers do not fill a budget of two hundred"
    );
}

/// **An `#include` points at a file**, which is the fourth answer a jump can give and the one nothing else in the
/// analysis can produce: `#include "near.h"` declares nothing, so the scope walk, the index by name and the macro
/// table all answer "nothing found" for a line whose whole purpose is to name a file.
#[test]
fn an_include_points_at_the_header_it_names() {
    let mut session = ranked_session();
    let view = cooked_view(&mut session, "/p/a.cpp");

    // Inside the spelling: `#include "near.h"` — character 12 is the `e` of `near`.
    let cursor = RANKED_CPP.find("near.h").expect("the fixture");
    let Known::Yes(found) = session.header_at(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(cursor),
    ) else {
        panic!("the cursor is on a header name");
    };

    assert_eq!(found.spelling, "near.h");
    assert_eq!(found.resolved, std::path::PathBuf::from("/p/near.h"));
    assert_eq!(
        RANKED_CPP[..found.range.end_offset()].trim_end(),
        "#include \"near.h\"",
        "the range is the whole directive — the `#`, the name and any trailing comment — because that is \
         what the reader pointed at"
    );

    // The `#` and the word `include` are part of the directive rather than of the name. Nothing in this analysis
    // depends on which one a reader points at — `Session::header_at` is asked with a *cursor*, and every client
    // sends the same requests for a ctrl-click wherever it lands on the line — so the assertions here are about
    // the boundary being where it is documented to be rather than about a user-visible difference.
    assert!(
        !matches!(
            session.header_at(
                &view,
                cpp_code_analysis::file::coordinates::FileOffset::new(
                    RANKED_CPP.find("#include").expect("the fixture")
                )
            ),
            Known::Yes(_)
        ),
        "the `#` is not the header's name"
    );

    // A name that is not a header is **not** this query's business — and the answer says so rather than saying
    // "nothing found", which is what keeps it from swallowing a jump that has a real declaration behind it.
    let on_a_declaration = RANKED_CPP.find("at_file_scope").expect("the fixture");
    match session.header_at(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(on_a_declaration),
    ) {
        Known::Unknown(reason) => assert_eq!(
            reason.describe(),
            UnknownReason::UnparsableName.describe(),
            "`at_file_scope` is not a header name at all"
        ),
        other => panic!("a variable is not a header: {other:?}"),
    }
}

/// **An `#include` that resolves to nothing is `Unknown` and names the header** — the same distinction the rest of
/// the crate keeps: "the index cannot find it" is a different claim from "there is no such file", and the reader
/// whose project has no `-I` for a header deserves to be told the first.
#[test]
fn an_include_that_resolves_to_nothing_says_so() {
    const FIXTURE: &str = "#include \"nowhere.h\"\nint x;\n";
    let memory = MemoryFiles::new().with_file("/p/a.cpp", FIXTURE);
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
    session.index_everything();

    let view = cooked_view(&mut session, "/p/a.cpp");
    let cursor = FIXTURE.find("nowhere").expect("the fixture");

    match session.header_at(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(cursor),
    ) {
        Known::Unknown(reason) => assert!(
            reason.describe().contains("nowhere.h"),
            "the reason names the header nobody could find: {}",
            reason.describe()
        ),
        other => panic!("a header that resolves to nothing is `Unknown`: {other:?}"),
    }
}

// ------------------------------------------------------------------------------------------------------------
// The cursor's file must be **read before it is asked about**, and the state it is read in is the bug.
// ------------------------------------------------------------------------------------------------------------

/// A file whose type is declared in a **header**, which is where a stale reading actually shows: `Widget`'s members
/// come from `widget.h`'s summary, so that header has to have been read for `w.` to be answerable at all.
const FRESHNESS_HEADER: &str = "struct Widget { int size; };\n";
const FRESHNESS_USES_HEADER: &str = "\
#include \"widget.h\"
int f() {
    Widget w;
    w.
}
";

/// **An edit replaces the text *and drops the summary*, and completion must not run between those two steps.**
///
/// `Session::buffer_changed` does the first immediately — the scope tree is rebuilt from the new text on every parse,
/// so a local's declarator is always right — and queues the second (the summary is rebuilt when the pump reaches the
/// file). A completion asked inside that window sees the new text with the **old facts**, and the damage is not an
/// error but a *different list*: the member query cannot work out the object's type, declines, and the client is
/// handed the names in scope, which is a list of everything that cannot follow a `.`.
///
/// That is what a user reported, with a screenshot: the popup after `myName.firstName.` was `printf`, `full`, `sum`,
/// `main` and the keywords. The fix is [`Session::catch_up`], which the completion handler calls before the query: it
/// re-reads the one file, and does nothing at all when there is nothing waiting.
#[test]
fn a_completion_after_an_edit_is_about_the_file_the_edit_wrote() {
    let memory = MemoryFiles::new()
        .with_file("/p/a.cpp", FRESHNESS_USES_HEADER)
        .with_file("/p/widget.h", FRESHNESS_HEADER);
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([
        std::path::PathBuf::from("/p/a.cpp"),
        std::path::PathBuf::from("/p/widget.h"),
    ]);
    session.index_everything();

    // The edit: the type gains a member, and the header's text is replaced exactly as `didChange` replaces it. **The
    // pump is deliberately not advanced** — that is the window this test is about, and it is the state a real server
    // is in when the keystroke that asked the question arrives.
    let edited = "struct Widget { int size; int extra; };\n";
    session.did_change("/p/widget.h", edited);
    assert!(
        session.pending() > 0,
        "the edit dropped the summary and queued the file, which is the state under test"
    );

    let cursor = FRESHNESS_USES_HEADER.find("w.").expect("the fixture") + 2;
    // **A view without a pump, because the state under test is the un-pumped one.** `cooked_view` asks for the reading
    // *and drains the queue* — which is exactly the catch-up whose **absence** this half of the test measures: with it
    // the header's summary was already rebuilt and the first assertion read `["extra", "size"]` instead of the stale
    // list. `FileView::parse_with` builds the file's own view from what the VFS holds and touches no queue, so the
    // window stays open until `catch_up` below closes it.
    let held = session.files().held("/p/a.cpp").expect("the file is held");
    let view =
        cpp_code_analysis::FileView::parse_with(held, &cpp_parser::MacroEnvironment::default());

    // **Without the catch-up**: the header's summary is the old one, so `Widget` still has only `size`.
    let stale = session.completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(cursor),
    );
    let stale_labels: Vec<&str> = stale.items.iter().map(|item| item.label.as_str()).collect();
    assert!(
        !stale_labels.contains(&"extra"),
        "the index is one edit behind until something reads the file: {stale_labels:?}"
    );

    // **With it**: one parse of one file, and the answer is about the text the user is looking at.
    session.catch_up(std::path::Path::new("/p/widget.h"));
    let fresh = session.completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(cursor),
    );
    let labels: Vec<&str> = fresh.items.iter().map(|item| item.label.as_str()).collect();

    assert!(
        labels.contains(&"extra") && labels.contains(&"size"),
        "both members of the type the header now declares: {labels:?}"
    );
    assert!(
        !labels.contains(&"f"),
        "and the names in scope are not — a `.` is not a name position: {labels:?}"
    );
    assert_eq!(
        session.pending(),
        0,
        "the synchronous read is the queue's work, done early: the file is not read a second time when the pump \
         gets to it"
    );
}

/// **A name declared below the cursor is not in scope yet**, which is the other half of what a user reported: the
/// popup at the top of `main` offered `sum` — a variable whose declaration is three lines further down.
///
/// A *scope* holds every binding written inside its braces, so a list built from them contains names the language
/// has not reached. The rule is textual and it applies to **bodies** only: a class's members are reachable
/// regardless of where in the class they are written (`void f() { x = 1; } int x;` is legal), so filtering those by
/// position would remove names a reader can write.
#[test]
fn a_name_declared_below_the_cursor_is_not_offered() {
    const FIXTURE: &str = "\
int f() {
    int above = 1;
    int also_above = 2;

    int sum = above + also_above;
    return sum;
}
";
    let memory = MemoryFiles::new().with_file("/p/a.cpp", FIXTURE);
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
    session.index_everything();

    // At the blank line **above** `int sum`, where a reader would type the declaration that uses it.
    let blank = FIXTURE.find("\n\n    int sum").expect("the fixture") + 1;
    let labels = labels_at(&mut session, "/p/a.cpp", blank);

    assert!(
        labels.contains(&"above".to_string()) && labels.contains(&"also_above".to_string()),
        "what was declared above the cursor is offered: {labels:?}"
    );
    assert!(
        !labels.contains(&"sum".to_string()),
        "and what is declared below it is not — the language has not reached it: {labels:?}"
    );

    // …and the same name **is** offered once the cursor is below its declaration, which is what keeps this from
    // being a filter that removes too much.
    let after = FIXTURE.find("return sum").expect("the fixture") + "return ".len();
    let labels = labels_at(&mut session, "/p/a.cpp", after);
    assert!(
        labels.contains(&"sum".to_string()),
        "below the declaration it is in scope: {labels:?}"
    );
}

/// **The sequence a server is in when the very first completion arrives** — `did_open`, then the request, with the
/// pump *not* advanced in between.
///
/// This is the order the LSP layer actually runs: `handlers::initialized` builds the session, `didOpen` replaces the
/// buffer (which **drops that file's summary**), and a completion arrives before anything has read the file again.
/// `Session::catch_up` is what the handler calls first, and the question this test holds fixed is whether that one
/// call is **enough** — a completion that needs a name from a header needs the header to have been read *by someone*,
/// and if `catch_up` rebuilds the file's summary without the index ever following its includes, the answer is an
/// empty member list for a type the file plainly includes.
///
/// No standard library: the same shape with a local header, so that the test is about the sequence rather than about
/// how long MSVC's `<string>` takes to read.
#[test]
fn the_first_completion_of_a_session_finds_the_type_in_an_included_header() {
    let memory = MemoryFiles::new()
        .with_file("/p/main.cpp", FRESHNESS_USES_HEADER)
        .with_file("/p/widget.h", FRESHNESS_HEADER);
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([
        std::path::PathBuf::from("/p/main.cpp"),
        std::path::PathBuf::from("/p/widget.h"),
    ]);

    // **The server's sequence, and only that**: the client opens the document, and the pump has not run.
    session.did_open("/p/main.cpp", FRESHNESS_USES_HEADER);
    session.catch_up(std::path::Path::new("/p/main.cpp"));

    let cursor = FRESHNESS_USES_HEADER.find("w.").expect("the fixture") + 2;
    let view = cooked_view(&mut session, "/p/main.cpp");
    let found = session.completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(cursor),
    );

    let labels: Vec<&str> = found.items.iter().map(|item| item.label.as_str()).collect();
    assert!(
        labels.contains(&"size"),
        "the members of the type the file includes, from a session that has read nothing yet — `catch_up` has to be \
         enough on its own, or the first completion of every session is empty: {labels:?}"
    );
}

/// **A file that has not been edited is not read again.** The pump drains after every edit, so the ordinary
/// keystroke asks [`Session::catch_up`] about a path that is not in the queue — and the answer has to be free, or
/// every completion would pay a parse.
#[test]
fn a_file_that_is_not_stale_is_not_read_again() {
    let memory = MemoryFiles::new()
        .with_file("/p/a.cpp", FRESHNESS_USES_HEADER)
        .with_file("/p/widget.h", FRESHNESS_HEADER);
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([
        std::path::PathBuf::from("/p/a.cpp"),
        std::path::PathBuf::from("/p/widget.h"),
    ]);
    session.index_everything();

    let before = session.stats();
    session.catch_up(std::path::Path::new("/p/widget.h"));
    let after = session.stats();

    assert_eq!(
        after, before,
        "nothing was read, parsed or written: the file was not stale"
    );
}

/// **The operator on the last line of a body, asked at either of the two offsets a caret on it can mean.**
///
/// The fourth report of "No suggestions" under `full2.`, and the narrowest: the line is the **last of the body**,
/// so the `}` follows it and the parser's recovery has nowhere to put the unfinished expression. Two things then
/// went wrong together, and both are about the *cursor* rather than about the type:
///
/// * the tree's access node ends before the operator, so a reader that asked the tree only answered "the name
///   `full2`, then something else" — and the client got the names in scope, a list of things that cannot follow a
///   `.`;
/// * a caret is drawn **between two characters**, and a client sends the position of the caret. For `full2|.` that
///   is the operator's own column, and for `full2.|` it is one past it. Both mean "after the operator" to a reader,
///   so both must answer the same list — and the diagnostic for the same keystroke must not say the opposite of
///   what the list says. It did: "the cursor is not a member access at all" was logged beside 55 members, because
///   the diagnostic asked the index layer's tree-only shape reader while the list asked the context reader.
///
/// No standard library here: a local header gives the same shape without paying for MSVC's `<string>`, which is
/// what `a_member_access_on_a_standard_library_type_offers_its_members` in `cpp_ls`'s handshake suite is for.
#[test]
fn a_member_access_on_the_last_line_of_a_body_offers_its_members_at_either_caret() {
    const FIXTURE: &str = "\
#include \"widget.h\"
int main() {
    Widget w;
    w.
}
";
    let memory = MemoryFiles::new()
        .with_file("/p/a.cpp", FIXTURE)
        .with_file("/p/widget.h", FRESHNESS_HEADER);
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([
        std::path::PathBuf::from("/p/a.cpp"),
        std::path::PathBuf::from("/p/widget.h"),
    ]);
    session.index_everything();

    let view = cooked_view(&mut session, "/p/a.cpp");
    let dot = FIXTURE.find("w.").expect("the fixture") + 1;
    assert_eq!(&FIXTURE[dot..dot + 1], ".", "the fixture's operator");

    for offset in [dot, dot + 1] {
        let found = session.completions(
            &view,
            cpp_code_analysis::file::coordinates::FileOffset::new(offset),
        );
        let labels: Vec<&str> = found.items.iter().map(|item| item.label.as_str()).collect();

        assert!(
            labels.contains(&"size"),
            "the caret at {offset} is on the operator, and `w` is a `Widget` declared a line above: {labels:?}"
        );
        assert!(
            !labels.contains(&"w"),
            "and not the names in scope, which cannot follow a `.`: {labels:?}"
        );

        // The sentence a failure is diagnosed with comes from the same reading as the list, so an empty list is
        // always explained by the step that emptied it — and `why_no_members` is handed a **tree**, so its offset is
        // the rendering's. Passing the fixture's own offset here was `Bad offset: range 0..27 offset 52` inside
        // `rowan`: the file is 52 bytes and its rendering (the header inlined, the directive gone) is 27.
        let in_the_reading = view
            .reading_offset_of(cpp_code_analysis::file::coordinates::FileOffset::new(
                offset,
            ))
            .expect("the cursor is in the rendering");
        let why = cpp_code_analysis::why_no_members(
            session.index(),
            &view.scopes,
            &view.root,
            &view.path,
            in_the_reading,
        );
        assert!(
            why.contains("the member query answered"),
            "the diagnosis agrees with the list at {offset}: {why}"
        );
    }
}

/// **A constructor's parameters are in scope in its body and in its member-initializer list.**
///
/// Reported as a missing completion: inside `Name(const std::string& f, ...) { first_| }` the list did not hold
/// `firstName`, and the semantic tokens pass says why — `firstName`, `middleName` and `lastName` are classified
/// as the **class's fields** and `f`, `m`, `l` are classified as **nothing at all**, where a plain member
/// function's parameter is classified `Parameter`. So the constructor's parameters are not in the scope tree,
/// and two questions are answered wrongly from the same gap.
///
/// Both positions are checked, because they are answered by different machinery: the initializer list is read
/// before the body exists, and the body is an ordinary block.
/// **Still failing on the member-initializer list, and the repro is left in place.**
///
/// What is fixed: a constructor is now recognised as a declaration that *names* something. Its declaration is a
/// bare `Declarator` rather than an `InitDeclarator` — there is no return type, so no `decl-specifier-seq` — and
/// `CppDeclaration::get_name_token` only looked at `InitDeclarator`. So the name was not found, the declaration
/// was read as "unnamed", and `is_unnamed_declaration` skipped it entirely: the constructor's parameters were
/// bound nowhere. Measured after the fix: `f` and `m` are `Parameter` where they are declared, and the
/// constructor itself is a `Method` rather than a bare `Type`.
///
/// What is not: their **uses**. `f` inside `: first(f)` and inside the body is still unclassified. The body is a
/// `CompoundStat` that is **not a child of the declaration** — instrumented, the declaration's children are
/// `["Declarator", "MemberInitializer", "MemberInitializer"]` while a `CompoundStat` for that body exists
/// elsewhere in the tree — so `function_body` does not find it and nothing is walked into the function scope.
/// The member-initializer walk added beside it therefore has no scope to walk into.
///
/// `#[ignore]` rather than deleted: it is the measurement, and the next round starts from here.
#[test]
fn a_constructors_parameters_are_in_scope() {
    let source = "struct Name {\n\
                      Name(const int f, const int m)\n\
                          : first(f), second(m) {\n\
                          int here = f;\n\
                      }\n\
                      int first;\n\
                      int second;\n\
                  };\n";
    let files = MemoryFiles::new().with_file("/p/ctor.cpp", source);
    let providers = SessionFiles::new(OpenDocuments::new(), files);
    let mut session = cpp_code_analysis::Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.load("/p/ctor.cpp");
    let view = session
        .view_of_the_file(std::path::Path::new("/p/ctor.cpp"))
        .expect("a view");

    for scope in view.scopes.scopes() {
        println!(
            "{:?} range={:?} bindings={:?}",
            scope.kind,
            scope.range.map(|r| (r.start_offset, r.end_offset())),
            scope
                .bindings
                .iter()
                .map(|b| (b.name.text(), b.name_range.start_offset))
                .collect::<Vec<_>>()
        );
    }

    for (what, needle) in [
        ("the member-initializer list", ": first("),
        ("the body", "int here = "),
    ] {
        let at = source.find(needle).expect("the fixture writes it") + needle.len();
        let names = match session.name_completions(
            &view,
            cpp_code_analysis::file::coordinates::FileOffset::new(at),
        ) {
            Known::Yes(found) => found
                .names
                .iter()
                .map(|offered| offered.fact.name.to_string())
                .collect::<Vec<_>>(),
            other => panic!("{what} should be answerable, got {other:?}"),
        };
        assert!(
            names.iter().any(|name| name == "f"),
            "the constructor's own parameter, in {what}: {names:?}"
        );
        assert!(
            names.iter().any(|name| name == "m"),
            "and the second one, in {what}: {names:?}"
        );
        assert!(
            names.iter().any(|name| name == "first"),
            "and the field it initialises, in {what}: {names:?}"
        );
    }
}
/// **A missing `;` is a parse error and has to reach the client.**
///
/// Reported: `std::cout << middleName << std::endl` with no semicolon produced no diagnostic, however long the user
/// waited. The question this pins is the first one — whether the answer exists at all — because a missing diagnostic
/// is either "nothing was found" or "it was found and never published", and the two are fixed in different places.
#[test]
fn a_missing_semicolon_is_reported() {
    let source = "int g();\nstruct Name {\n    void print(int i) {\n        std::cout << middleName << std::endl\n    }\n};\n";
    let files = MemoryFiles::new().with_file("/p/a.cpp", source);
    let providers = SessionFiles::new(OpenDocuments::new(), files);
    let mut session = cpp_code_analysis::Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.load("/p/a.cpp");
    session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
    session.want_cooked_reading(std::path::Path::new("/p/a.cpp"));
    session.index_everything();
    println!(
        "before the edit: {:?}",
        session
            .diagnostics(std::path::Path::new("/p/a.cpp"))
            .map(|found| found.errors.len())
    );

    // What a user typing does: the session is told the file's new text.
    session.did_open(std::path::Path::new("/p/a.cpp"), source);
    println!(
        "right after the edit: {:?}",
        session
            .diagnostics(std::path::Path::new("/p/a.cpp"))
            .map(|found| found.errors.len())
    );
    session.want_cooked_reading(std::path::Path::new("/p/a.cpp"));
    session.index_everything();
    println!(
        "after re-indexing: {:?}",
        session
            .diagnostics(std::path::Path::new("/p/a.cpp"))
            .map(|found| found.errors.len())
    );

    let found = session
        .diagnostics("/p/a.cpp")
        .expect("the file is held, so it has an answer");
    println!(
        "reading={:?} errors={} unplaced={}",
        found.reading,
        found.errors.len(),
        found.unplaced
    );
    for error in &found.errors {
        println!("  {error:?}");
    }
    assert!(
        found
            .errors
            .iter()
            .any(|error| error.message.contains(';') || error.message.contains("expected")),
        "the missing `;` is a parse error and nothing else: {:?}",
        found
            .errors
            .iter()
            .map(|e| e.message.clone())
            .collect::<Vec<_>>()
    );
}

/// **A macro is not a function** — its completion row carries no signature.
///
/// Reported from an editor: `FULL_NAME_FORMAT` is `#define FULL_NAME_FORMAT "Full name: {}"` and the completion
/// listed it with the detail `int ()`. A detail comes from `DeclFact`'s `returns`/`parameter_list`, and a macro has
/// neither — so the row was built from a fact whose four "what type does this declare" questions had been answered
/// about a *different* declaration: the macro's name offset is inside no declaration shape, so the shape lookup that
/// answers those questions found whatever enclosed it — here `int main()`, hence `int` and `()`.
#[test]
fn a_macro_is_not_shown_with_a_signature() {
    let source = "#define FULL_NAME_FORMAT \"Full name: {}\"\nint main() { FULL_NAME_FORMAT }\n";
    let memory = MemoryFiles::new().with_file("/p/a.cpp", source);
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
    let view = cooked_view(&mut session, "/p/a.cpp");

    let cursor = source.rfind("FULL_NAME_FORMAT").expect("the fixture") + "FULL_NAME_FORMAT".len();
    match session.members_of(&view, "Source") {
        cpp_code_analysis::Known::Yes(list) => println!(
            "members_of(Source) → {:?}",
            list.members
                .iter()
                .map(|m| m.fact.name.to_string())
                .collect::<Vec<_>>()
        ),
        other => println!("members_of(Source) → {other:?}"),
    }
    let offered = session.completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(cursor),
    );
    let item = offered
        .items
        .iter()
        .find(|item| item.label == "FULL_NAME_FORMAT")
        .expect("the macro is offered");
    println!(
        "item: kind={:?} detail={:?} fact={:?}",
        item.kind,
        item.detail,
        item.fact
            .as_ref()
            .map(|fact| (&fact.kind, &fact.returns, fact.parameter_list()))
    );
    assert_eq!(
        item.detail,
        None,
        "a macro has no returns and no parameters: {:?}",
        item.fact
            .as_ref()
            .map(|fact| (&fact.kind, &fact.returns, fact.parameter_list()))
    );

    // **And its identity is the macro's own position.** The item a client resolves is a `(file, offset)` pair taken
    // from `name_range`, while the fact behind it is a clone of the file's first declaration — so a clone that kept
    // the template's range named `int main()`, and the popup showed `FULL_NAME_FORMAT` with the detail **`int ()`**.
    // Asserted on the offset rather than on the detail because the detail is read back by the server
    // (`completionItem/resolve`) from this offset: this layer is what has to give it the right one.
    let fact = item.fact.as_ref().expect("a macro item carries its fact");
    let at = source.find("FULL_NAME_FORMAT").expect("the fixture");
    assert_eq!(
        fact.name_range.start_offset, at,
        "the item's identity is the macro's name, not the template declaration's"
    );
    assert_eq!(
        fact.range.start_offset, at,
        "and its declaration range is the same place"
    );
    assert_eq!(fact.scope, None, "a `#define` is at file scope");
}

/// **The typed word is the range the client replaces, and the prefix the server filters on** — one report, both
/// halves.
///
/// From an editor, with `#include`s above the cursor:
///
/// ```text
///   auto x = a|        the list has every name in scope          ← no prefix, so nothing was filtered
///   auto x = an|       the list has only the keywords            ← the prefix was "n", and `anotherVec` does not
///                                                                  begin with "n"
///   accepting the item at `a|` wrote `aanotherVec`               ← the replace range was empty
/// ```
///
/// The three follow from one thing: the range the analysis answers with is in the **rendering's** coordinates,
/// while the client is looking at the file — and the two differ by everything the cook removed, which here is two
/// `#include` lines. See `text_edit` in the server, which converts; this test pins what the analysis answers, so
/// that a conversion with nothing to convert is not mistaken for the answer.
#[test]
fn the_typed_prefix_is_the_word_being_replaced() {
    let header =
        "namespace std { template <class T> struct vector { void push_back(const T&); }; }\n";

    // **One session per typed word**, because the word is part of the file: the cursor at `a|` and the cursor at
    // `an|` are two different texts, and a fixture that writes only `a` cannot be asked the second.
    for typed in ["a", "an"] {
        let source = format!(
            "#include \"v.h\"\nint main()\n{{\n    std::vector<int> anotherVec;\n    auto x = {typed}\n    return 0;\n}}\n"
        );
        let files = MemoryFiles::new()
            .with_file("/p/v.h", header)
            .with_file("/p/a.cpp", &source);
        let providers = SessionFiles::new(OpenDocuments::new(), files);
        let mut session = Session::with_config(
            "/p",
            providers,
            WatchFilter::new("/p"),
            CompilerConfig::default(),
        );
        session.add_project_files([
            std::path::PathBuf::from("/p/v.h"),
            std::path::PathBuf::from("/p/a.cpp"),
        ]);
        let view = cooked_view(&mut session, "/p/a.cpp");

        let at = source.find("auto x = ").expect("the fixture") + "auto x = ".len() + typed.len();
        match session.members_of(&view, "Source") {
            cpp_code_analysis::Known::Yes(list) => println!(
                "members_of(Source) → {:?}",
                list.members
                    .iter()
                    .map(|m| m.fact.name.to_string())
                    .collect::<Vec<_>>()
            ),
            other => println!("members_of(Source) → {other:?}"),
        }
        let offered = session.completions(
            &view,
            cpp_code_analysis::file::coordinates::FileOffset::new(at),
        );
        let labels: Vec<&str> = offered
            .items
            .iter()
            .map(|item| item.label.as_str())
            .collect();
        println!(
            "`{typed}|`: prefix {:?} replace {}..{} (len {}) → {:?}",
            offered.prefix,
            offered.replace.start_offset,
            offered.replace.end_offset(),
            offered.replace.length,
            &labels[..labels.len().min(10)]
        );
        assert_eq!(
            offered.prefix, typed,
            "the prefix is what is being typed, so that the server filters on it"
        );
        assert_eq!(
            offered.replace.length,
            typed.len(),
            "and the range covers exactly that word, so that accepting an item replaces it"
        );
        assert!(
            labels.contains(&"anotherVec"),
            "`anotherVec` begins with `{typed}`: {:?}",
            &labels[..labels.len().min(12)]
        );
    }
}

#[test]
fn a_statement_position_prefix_is_read_too() {
    for typed in ["a", "an"] {
        let source =
            format!("int main()\n{{\n    int anotherVec = 1;\n    {typed}\n    return 0;\n}}\n");
        let files = MemoryFiles::new().with_file("/p/a.cpp", &source);
        let providers = SessionFiles::new(OpenDocuments::new(), files);
        let mut session = Session::with_config(
            "/p",
            providers,
            WatchFilter::new("/p"),
            CompilerConfig::default(),
        );
        session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
        let view = cooked_view(&mut session, "/p/a.cpp");

        let at = source.find(&format!("    {typed}\n")).expect("the fixture") + 4 + typed.len();
        match session.members_of(&view, "Source") {
            cpp_code_analysis::Known::Yes(list) => println!(
                "members_of(Source) → {:?}",
                list.members
                    .iter()
                    .map(|m| m.fact.name.to_string())
                    .collect::<Vec<_>>()
            ),
            other => println!("members_of(Source) → {other:?}"),
        }
        let offered = session.completions(
            &view,
            cpp_code_analysis::file::coordinates::FileOffset::new(at),
        );
        let labels: Vec<&str> = offered
            .items
            .iter()
            .map(|item| item.label.as_str())
            .collect();
        println!(
            "statement `{typed}|`: prefix {:?} replace {}..{} (len {}) → {:?}",
            offered.prefix,
            offered.replace.start_offset,
            offered.replace.end_offset(),
            offered.replace.length,
            &labels[..labels.len().min(10)]
        );
        assert_eq!(
            offered.prefix, typed,
            "the statement position reads the word too"
        );
        assert_eq!(offered.replace.length, typed.len());
        assert!(
            labels.contains(&"anotherVec"),
            "{:?}",
            &labels[..labels.len().min(12)]
        );
    }
}

#[test]
fn a_macro_that_expands_to_a_scope_offers_its_members() {
    let source = "\
#define STD std::
namespace std { int cout; int cin; int size; }
int main()
{
    STD s
    return 0;
}
";
    let files = MemoryFiles::new().with_file("/p/a.cpp", source);
    let providers = SessionFiles::new(OpenDocuments::new(), files);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
    let view = cooked_view(&mut session, "/p/a.cpp");
    println!("rendering: {:?}", view.source);

    let at = source.find("    STD s").expect("the fixture") + "    STD s".len();
    match session.members_of(&view, "Source") {
        cpp_code_analysis::Known::Yes(list) => println!(
            "members_of(Source) → {:?}",
            list.members
                .iter()
                .map(|m| m.fact.name.to_string())
                .collect::<Vec<_>>()
        ),
        other => println!("members_of(Source) → {other:?}"),
    }
    let offered = session.completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(at),
    );
    let labels: Vec<&str> = offered
        .items
        .iter()
        .map(|item| item.label.as_str())
        .collect();
    println!(
        "after the macro `STD s|`: prefix {:?} scope {:?} replace {}..{} → {:?}",
        offered.prefix,
        offered.scope,
        offered.replace.start_offset,
        offered.replace.end_offset(),
        &labels[..labels.len().min(8)]
    );

    // **The macro is expanded before the question is asked**, which is the point: `STD` is `std::` in the cook, so
    // the position is a *qualified* name with `s` written — the scope is `std` and the names are its members.
    assert_eq!(
        offered.scope, "std",
        "the expansion made this a qualified name"
    );
    assert_eq!(offered.prefix, "s");
    assert_eq!(
        offered.replace.length, 1,
        "the range covers the `s` that was typed"
    );
    assert!(labels.contains(&"size"), "{labels:?}");
    assert!(
        !labels.contains(&"main"),
        "and the file own names are not in `std`: {labels:?}"
    );
}

/// **A documentation comment answers two questions**: the command vocabulary after `@`, and the name the command
/// takes after `@param`.
///
/// Reported from an editor: "in comments there is no completion for doxygen commands, and if the command is
/// `param`, no completion for the parameter names". Before this the whole of a comment was refused — a `//` is
/// prose to every other question `context_at` asks, and the refusal was one line above every answer.
///
/// The parameter names come from the **fact of the declaration below the comment**, which is why the fixture writes
/// one: `DeclFact::parameter_list` is the spelling, and the names are read out of it the same way the inlay hints
/// read them, so a default argument and a `const T&` are the same question here as there.
#[test]
fn a_documentation_comment_offers_its_commands_and_their_names() {
    let source = "\
/// Frobnicates the widget.
/// @par
/// @param\x20
int frobnicate(const Widget& widget, int count);

struct Widget { int size; };
";
    let files = MemoryFiles::new().with_file("/p/a.cpp", source);
    let providers = SessionFiles::new(OpenDocuments::new(), files);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
    let view = cooked_view(&mut session, "/p/a.cpp");

    // **After `@par`** — the vocabulary, filtered by what was typed.
    let after_par = source.find("/// @par").expect("the fixture") + "/// @par".len();
    match session.members_of(&view, "Source") {
        cpp_code_analysis::Known::Yes(list) => println!(
            "members_of(Source) → {:?}",
            list.members
                .iter()
                .map(|m| m.fact.name.to_string())
                .collect::<Vec<_>>()
        ),
        other => println!("members_of(Source) → {other:?}"),
    }
    let offered = session.completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(after_par),
    );
    let labels: Vec<&str> = offered
        .items
        .iter()
        .map(|item| item.label.as_str())
        .collect();
    println!(
        "after `@par`: prefix {:?} → {:?}",
        offered.prefix,
        &labels[..labels.len().min(8)]
    );
    assert_eq!(
        offered.prefix, "par",
        "the command's name is what is being typed"
    );
    assert!(
        labels.contains(&"param"),
        "`param` is a command that begins with `par`: {labels:?}"
    );

    // **After `@param `** — the parameters of the declaration the comment documents, and nothing else.
    // **The space after `@param` is written `\x20` in the fixture**, so the file has no trailing whitespace
    // for a hook to trim and the string still ends the command with the space this half asserts about.
    let after_param = source.find("/// @param").expect("the fixture") + "/// @param ".len();
    match session.members_of(&view, "Source") {
        cpp_code_analysis::Known::Yes(list) => println!(
            "members_of(Source) → {:?}",
            list.members
                .iter()
                .map(|m| m.fact.name.to_string())
                .collect::<Vec<_>>()
        ),
        other => println!("members_of(Source) → {other:?}"),
    }
    let offered = session.completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(after_param),
    );
    let labels: Vec<&str> = offered
        .items
        .iter()
        .map(|item| item.label.as_str())
        .collect();
    println!(
        "after `@param `: prefix {:?} → {:?}",
        offered.prefix, labels
    );
    assert_eq!(offered.prefix, "", "nothing is typed yet");
    assert!(labels.contains(&"widget"), "{labels:?}");
    assert!(labels.contains(&"count"), "{labels:?}");
    assert!(
        !labels.contains(&"size"),
        "a member of a later class is not a parameter of this function: {labels:?}"
    );
}

/// **`#define` 的替换列表里补全它自己的形参** —— 那些名字只存在于这一行,索引和 scope 都不知道它们。
#[test]
fn a_macro_body_offers_its_own_parameters() {
    let source =
        "#define MAX(a, b) ((a) > (b) ? (a) : (b))\n#define MAX3(a, b, c) MAX(MAX(a, b), c)\n";
    let files = MemoryFiles::new().with_file("/p/a.cpp", source);
    let providers = SessionFiles::new(OpenDocuments::new(), files);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
    let view = cooked_view(&mut session, "/p/a.cpp");

    // Inside the second replacement list, on the `b` of `MAX(a, b)`.
    let at = source
        .find("MAX3(a, b, c) MAX(MAX(a, b)")
        .expect("the fixture")
        + "MAX3(a, b, c) MAX(MAX(a, ".len();
    match session.members_of(&view, "Source") {
        cpp_code_analysis::Known::Yes(list) => println!(
            "members_of(Source) → {:?}",
            list.members
                .iter()
                .map(|m| m.fact.name.to_string())
                .collect::<Vec<_>>()
        ),
        other => println!("members_of(Source) → {other:?}"),
    }
    let offered = session.completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(at),
    );
    let labels: Vec<&str> = offered
        .items
        .iter()
        .map(|item| item.label.as_str())
        .collect();
    println!("prefix {:?} → {labels:?}", offered.prefix);
    // **The macro's parameters first**, then the macros already defined — at the start of the replacement list,
    // which is where a reader begins to write one.
    //
    // **And the predefined ones, which no file declares.** `__LINE__`, `__FILE__`, `__cplusplus` and the `__STDC_*`
    // family are defined by the compiler, so neither this file nor its headers list them; a replacement list is one of
    // the places they are written. Reported (fig 1): a completion in a preprocessor position knew only the project's
    // own macros.
    assert_eq!(
        labels,
        vec![
            "a",
            "b",
            "c",
            "MAX",
            "MAX3",
            "__DATE__",
            "__FILE__",
            "__LINE__",
            "__STDC_HOSTED__",
            "__STDC_VERSION__",
            "__STDC__",
            "__TIME__",
            "__cplusplus",
        ],
        "{labels:?}"
    );
    assert_eq!(
        offered.replace.length, 0,
        "nothing is typed yet, so the range is where the caret is"
    );
}

/// **`#if` / `#elif` / `#ifdef` 里补全宏** —— 条件在任何声明存在之前就被求值,所以那里只有宏和 `defined`。
#[test]
fn a_conditional_directive_offers_the_macros() {
    let source = "\
#define VERSION 3
#define FEATURE 1

#if VERSION > 2 && defined(FEATURE)
int newer;
#elif defined(FEATU)
int older;
#else
int neither;
#endif
";
    let files = MemoryFiles::new().with_file("/p/a.cpp", source);
    let providers = SessionFiles::new(OpenDocuments::new(), files);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
    let view = cooked_view(&mut session, "/p/a.cpp");

    // After `defined(` in the `#elif`: the macros are the answer, filtered by `FEATU`.
    let at = source.find("#elif defined(FEATU").expect("the fixture") + "#elif defined(FEATU".len();
    match session.members_of(&view, "Source") {
        cpp_code_analysis::Known::Yes(list) => println!(
            "members_of(Source) → {:?}",
            list.members
                .iter()
                .map(|m| m.fact.name.to_string())
                .collect::<Vec<_>>()
        ),
        other => println!("members_of(Source) → {other:?}"),
    }
    let offered = session.completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(at),
    );
    let labels: Vec<&str> = offered
        .items
        .iter()
        .map(|item| item.label.as_str())
        .collect();
    println!("prefix {:?} at {at} → {labels:?}", offered.prefix);
    assert_eq!(offered.prefix, "FEATU", "the word being typed");
    assert_eq!(labels, vec!["FEATURE"], "and only the macro that matches");

    // Right after `#if `: every macro the file defines, plus `defined`.
    let blank = source.find("#if VERSION").expect("the fixture") + "#if ".len();
    match session.members_of(&view, "Source") {
        cpp_code_analysis::Known::Yes(list) => println!(
            "members_of(Source) → {:?}",
            list.members
                .iter()
                .map(|m| m.fact.name.to_string())
                .collect::<Vec<_>>()
        ),
        other => println!("members_of(Source) → {other:?}"),
    }
    let offered = session.completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(blank),
    );
    let labels: Vec<&str> = offered
        .items
        .iter()
        .map(|item| item.label.as_str())
        .collect();
    println!("blank prefix {:?} → {labels:?}", offered.prefix);
    assert!(labels.contains(&"VERSION"), "{labels:?}");
    assert!(labels.contains(&"defined"), "{labels:?}");
    assert!(
        !labels.contains(&"newer"),
        "a variable is not a word a condition can mean: {labels:?}"
    );
}

/// **半写完的 `it->` 也要有成员补全** —— 解析器在 `->` 后面没有名字时报错,补全必须从文本恢复这个访问。
#[test]
fn a_half_typed_arrow_still_offers_the_members() {
    let source = "\
#include \"map.h\"
#include \"string.h\"
int f() {
    std::map<int, std::string> myMap;
    auto it = myMap.begin();
    it->
    return 0;
}
";
    let map = "namespace std { template <class K, class V> struct map { }; template <class A, class B> struct pair { A first; B second; }; }\n";
    let string = "namespace std { template <class C> struct basic_string { }; typedef basic_string<char> string; }\n";
    let files = MemoryFiles::new()
        .with_file("/p/map.h", map)
        .with_file("/p/string.h", string)
        .with_file("/p/a.cpp", source);
    let providers = SessionFiles::new(OpenDocuments::new(), files);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([
        std::path::PathBuf::from("/p/map.h"),
        std::path::PathBuf::from("/p/string.h"),
        std::path::PathBuf::from("/p/a.cpp"),
    ]);
    session.index_everything();
    let view = cooked_view(&mut session, "/p/a.cpp");

    let at = source.find("it->\n").expect("the fixture") + "it->".len();
    let reading = view
        .reading_offset_of(cpp_code_analysis::file::coordinates::FileOffset::new(at))
        .expect("the cursor is in the rendering");
    println!(
        "context: {:?}",
        cpp_code_analysis::completion::context_at(&view.root, reading.get())
    );
    match session.members_of(&view, "Source") {
        cpp_code_analysis::Known::Yes(list) => println!(
            "members_of(Source) → {:?}",
            list.members
                .iter()
                .map(|m| m.fact.name.to_string())
                .collect::<Vec<_>>()
        ),
        other => println!("members_of(Source) → {other:?}"),
    }
    let offered = session.completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(at),
    );
    let labels: Vec<&str> = offered
        .items
        .iter()
        .map(|item| item.label.as_str())
        .collect();
    println!(
        "why: {}",
        cpp_code_analysis::completion::why_no_members(
            session.index(),
            &view.scopes,
            &view.root,
            &view.path,
            reading
        )
    );
    println!("after `it->`: {labels:?}");
    assert!(
        labels.contains(&"first") && labels.contains(&"second"),
        "the element's members: {labels:?}"
    );
}

/// **The original problem**: in a `.cpp` of separated definitions, a completion in the body of `Source::GetLine` cannot name
/// `Source`'s members.
///
/// # What was measured, and why this is not fixed here
///
/// The chain at that cursor is `[Function, Class("Source"), TranslationUnit]` once `names_a_scope_this_file_has` accepts a
/// qualifier this file has not built, and `members_of("Source")` then answers `["GetLine"]` — so the two structural pieces do
/// work when forced. Forcing them **breaks an invariant**: `sema::resolve::tests::a_qualifier_that_names_nothing_is_unknown_
/// rather_than_guessed` fails, because synthesising a class scope from a qualifier is exactly the guess that test forbids.
///
/// So the fix is **not** in the scope tree. The completion path should ask the question directly — "the declarator that
/// encloses this cursor is `Source::GetLine`, so the members of `Source` are in scope here" — using the declarator node and
/// `members_of`, which is what `CppDeclaration`/`CppDeclSpecifierSeq` already expose. That keeps the resolver's rule (a
/// qualifier names nothing until something declares it) and gives the completion what it needs.
#[test]
fn a_member_is_completed_in_a_separated_definition() {
    let header = "class Source {\npublic:\n    int _offset;\n    int GetLine(int n);\n};\n";
    let source = "#include \"a.h\"\nint Source::GetLine(int n) {\n    return _;\n}\n";
    let files = MemoryFiles::new()
        .with_file("/p/a.h", header)
        .with_file("/p/a.cpp", source);
    let providers = SessionFiles::new(OpenDocuments::new(), files);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([
        std::path::PathBuf::from("/p/a.h"),
        std::path::PathBuf::from("/p/a.cpp"),
    ]);
    session.index_everything();
    let view = cooked_view(&mut session, "/p/a.cpp");
    let at = source.find("return _").expect("the fixture") + "return _".len();
    let reading = view
        .reading_offset_of(cpp_code_analysis::file::coordinates::FileOffset::new(at))
        .expect("the cursor is in the rendering");
    if let Some(innermost) = view.scopes.scope_at(reading.get()) {
        for id in view.scopes.scope_chain(innermost) {
            if let Some(scope) = view.scopes.scope(id) {
                println!(
                    "  chain: kind {:?} name {:?} prefix {:?}",
                    scope.kind,
                    scope.name,
                    view.scopes.qualification_prefix_of(id)
                );
            }
        }
    }
    match session.members_of(&view, "Source") {
        cpp_code_analysis::Known::Yes(list) => println!(
            "members_of(Source) → {:?}",
            list.members
                .iter()
                .map(|m| m.fact.name.to_string())
                .collect::<Vec<_>>()
        ),
        other => println!("members_of(Source) → {other:?}"),
    }
    let offered = session.completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(at),
    );
    let labels: Vec<&str> = offered
        .items
        .iter()
        .map(|item| item.label.as_str())
        .collect();
    println!("offered: {labels:?}");
    // `_offset` is a member too, but a name beginning with `_` inside a body is the implementation's by this crate's rule
    // (see `unused`'s note), so the assertion is the plain-named member — which is what the completion had none of before.
    assert!(
        labels.contains(&"_offset"),
        "the body of a separated definition names the class's own members: {labels:?}"
    );
}
/// **`->` reaches the class the arrow means**, which is not the object's own class.
///
/// Reported: "operator 的支持还没做完,比如智能指针的补全没有考虑到指向的内容". A smart pointer's own members are
/// `operator->`, `operator*`, `reset`, … — none of which `->` can reach — so a list built from the object's class is
/// the wrong list twice over: it offers what the arrow cannot name and omits what it means.
///
/// The chain is followed through the type: a pointer's pointee, or a class's own `operator->` return type and then its
/// pointee. `Widget* pointer;` and `std::unique_ptr<Widget> smart;` therefore answer the same member list.
#[test]
fn an_arrow_reaches_the_class_through_the_pointer_and_through_operator_arrow() {
    let source = "\
namespace std {
template <class T>
struct unique_ptr {
    T* operator->() const;
    T& operator*() const;
};
}
struct Widget {
    int size;
    void draw();
};
Widget* pointer;
std::unique_ptr<Widget> smart;
void f() {
    pointer->;
    smart->;
}
";
    let mem = MemoryFiles::new().with_file("/p/a.cpp", source);
    let providers = SessionFiles::new(OpenDocuments::new(), mem);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
    session.index_everything();
    let _ = session.view("/p/a.cpp");
    session.index_everything();

    for (needle, what) in [
        ("pointer->", "a raw pointer"),
        ("smart->", "a smart pointer"),
    ] {
        let at = source.find(needle).expect("the fixture writes it") + needle.len();
        let labels = labels_at(&mut session, "/p/a.cpp", at);
        println!("{what} at {at}: {labels:?}");
        assert!(
            labels.iter().any(|label| label == "size"),
            "{what}: the pointee's member is offered: {labels:?}"
        );
        assert!(
            labels.iter().any(|label| label == "draw"),
            "{what}: and its member function: {labels:?}"
        );
        assert!(
            !labels.iter().any(|label| label == "operator->"),
            "{what}: the pointer's own `operator->` is not what the arrow reaches: {labels:?}"
        );
    }
}

/// **A handle whose `operator->` is inherited still reaches its pointee** — the shape `std::shared_ptr` has.
///
/// libstdc++ declares `shared_ptr : public __shared_ptr<_Tp>` and `__shared_ptr : public __shared_ptr_access<_Tp, _Lp>`,
/// and the `operator->` is in the **specialization two levels down**. Measured on a real project,
/// `members_of("shared_ptr")` answers fifteen members — the constructors, the assignment operators, `element_type`,
/// `weak_type` and two friends — and **not one `operator->`**, because the base's facts were not at hand when the list
/// was built. The arrow then listed the handle's own members (`element_type`, `operator=`, `shared_ptr`) instead of
/// `State`'s.
///
/// The rule is the standard's: **a class that declares `element_type` is pointer-like** — that is the member
/// `std::pointer_traits` is written in terms of — and requiring the class's *own* `operator->` made the answer depend
/// on whether a base's file happened to have been read. The guard it replaces is still wanted, and is still kept by the
/// `element_type` name: no container declares one (`std::string` declares `value_type`, which is why `std::string* p;
/// p->` must not become "the members of `char`").
#[test]
fn an_inherited_operator_arrow_still_reaches_the_pointee() {
    // **The base is declared and nothing more** — which is the state the real project was in: `__shared_ptr` lives in
    // `<bits/shared_ptr_base.h>`, and when that file has not been read the member list is the handle's own. The
    // `element_type` the handle re-exports is then the only thing left that says what its arrow reaches.
    let source = "\
namespace std {
template <typename T, int Lp>
class __shared_ptr;
template <typename T>
class shared_ptr : public __shared_ptr<T, 2> {
public:
    using element_type = T;
    using weak_type = shared_ptr;
    shared_ptr() = default;
    shared_ptr& operator=(const shared_ptr&) = default;
};
}
struct State { bool called; int value; };
std::shared_ptr<State> state_;
void f() { state_->called = true; }
";
    let mem = MemoryFiles::new().with_file("/p/a.cpp", source);
    let providers = SessionFiles::new(OpenDocuments::new(), mem);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
    session.index_everything();
    let _ = session.view("/p/a.cpp");
    session.index_everything();

    let at = source.find("state_->").expect("the fixture writes it") + "state_->".len();
    let labels = labels_at(&mut session, "/p/a.cpp", at);
    println!("shared_ptr arrow: {labels:?}");
    assert!(
        labels.iter().any(|label| label == "called"),
        "the pointee's member is offered through the inherited operator: {labels:?}"
    );
    assert!(
        !labels.iter().any(|label| label == "element_type"),
        "the handle's own members are not what the arrow reaches: {labels:?}"
    );
}

/// **A `.` typed on a pointer lists the pointee's members**, which is what the reader meant — the operator they
/// should have typed is the client's business, and the list is the same one `->` gives.
#[test]
fn a_dot_on_a_pointer_lists_the_pointee() {
    let source = "\
struct Widget {
    int size;
};
Widget* pointer;
void f() {
    pointer.;
}
";
    let mem = MemoryFiles::new().with_file("/p/a.cpp", source);
    let providers = SessionFiles::new(OpenDocuments::new(), mem);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
    session.index_everything();
    let _ = session.view("/p/a.cpp");
    session.index_everything();
    let at = source.find("pointer.").expect("the fixture") + "pointer.".len();
    let labels = labels_at(&mut session, "/p/a.cpp", at);
    println!("dot at {at}: {labels:?}");
    assert!(
        labels.iter().any(|label| label == "size"),
        "the pointee's member is offered after a `.` on a pointer: {labels:?}"
    );
}
/// **A `.` on a class with `operator->` lists *that class's* members** — the pointee is reached with `->`, which is what the
/// language says and what the arrow path already does.
///
/// This test used to assert the opposite. The rule was: a `.` on a class that declares `operator->` is the same mistake as
/// a `.` on a pointer, so the list is the pointee's and the operator is replaced. The first half of that is true of a smart
/// pointer and **false of `std::optional`**, which declares `operator->` *and* `value_type`:
///
/// ```cpp
/// std::optional<std::string> maybe;
/// maybe.has_value();     // offered `append`, `c_str`, `capacity` — the string's sixty-eight
/// maybe->size();         // right, through `operator->`
/// ```
///
/// Measured on a C++ project: the dot answered the *contained* type's members for `optional<string>`, and **nothing** for
/// `optional<int>` (following `value_type` to `int`, which has no members). The two classes are indistinguishable by shape,
/// so the rule cannot be "follow the operator" — it is now **`element_type`**, the standard's own pointer protocol, which
/// `unique_ptr`/`shared_ptr`/`weak_ptr` declare and `optional` does not.
///
/// The fixture below declares `operator->` and no `element_type`, so it is a class whose dot is its own list — the rule this
/// test now pins, with the same shape the old one was written for.
#[test]
fn a_dot_on_a_class_with_operator_arrow_lists_that_class() {
    let source = "\
namespace std {
template <class T>
struct shared_ptr {
    T* operator->() const;
    long use_count() const;
};
}
struct LuaEditorConfig {
    bool code_style_check;
    void OpenFile();
};
struct Config {
    std::shared_ptr<LuaEditorConfig> Editorconfig;
};
void f(Config config) {
    config.Editorconfig.;
}
";
    let mem = MemoryFiles::new().with_file("/p/a.cpp", source);
    let providers = SessionFiles::new(OpenDocuments::new(), mem);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
    session.index_everything();
    let _ = session.view("/p/a.cpp");
    session.index_everything();

    let at =
        source.find("config.Editorconfig.").expect("the fixture") + "config.Editorconfig.".len();
    let labels = labels_at(&mut session, "/p/a.cpp", at);
    println!("dot on a class with operator-> at {at}: {labels:?}");
    assert!(
        labels.iter().any(|label| label == "use_count"),
        "the object's own member is offered: {labels:?}"
    );
    assert!(
        !labels.iter().any(|label| label == "code_style_check"),
        "and the pointee's is not — that is what `->` is for: {labels:?}"
    );
}

/// **A `.` typed on a pointer is completed as `->`**: the range the client replaces covers the operator itself, and
/// the insertion carries `->`.
///
/// Reported as "我们通过.补全的时候也应该补全时替换为->". The list is the pointee's (see the test above), and the operator
/// is the one thing the reader got wrong — `.size` on a `Widget*` does not compile — so the answer replaces it rather
/// than completing a member onto text that cannot use one.
#[test]
fn a_dot_on_a_pointer_is_completed_as_an_arrow() {
    let source = "\
struct Widget {
    int size;
};
Widget* pointer;
void f() {
    pointer.;
}
";
    let mem = MemoryFiles::new().with_file("/p/a.cpp", source);
    let providers = SessionFiles::new(OpenDocuments::new(), mem);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
    session.index_everything();
    let _ = session.view("/p/a.cpp");
    session.index_everything();

    // **The last one**: the fixture declares `pointer` and then uses it, and the use is what the cursor is on.
    let dot = source.rfind("pointer.").expect("the fixture") + "pointer".len();
    let at_in_the_file = dot + 1;
    let view = cooked_view(&mut session, "/p/a.cpp");
    let answered = session.completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(at_in_the_file),
    );
    // **The answer's offsets are the rendering's**, and the rendering is not the file byte for byte (the cook drops
    // what the preprocessor consumed). The cursor therefore has to be read in the same numbering before the two are
    // compared — the mistake this test made first, and the reason both numbers are printed below.
    let at = view
        .reading_offset_of(cpp_code_analysis::file::coordinates::FileOffset::new(
            at_in_the_file,
        ))
        .expect("the offset is in the rendering")
        .get();
    println!(
        "replace {:?} items {:?}",
        answered.replace,
        answered
            .items
            .iter()
            .map(|item| (&item.label, &item.insert))
            .collect::<Vec<_>>()
    );

    // **A rendering's offsets, not the fixture's**: the answer is in the cooked text's numbering, which is what the
    // client's range is in. What matters is the character the range covers and where it sits relative to the cursor.
    assert_eq!(
        answered.replace.length, 1,
        "the replacement covers one character — the operator: {:?}",
        answered.replace
    );
    assert_eq!(
        at - answered.replace.start_offset,
        1,
        "and that character is the one immediately before the cursor: {:?} at {at}",
        answered.replace
    );
    assert_eq!(
        &view.source[answered.replace.start_offset..answered.replace.end_offset()],
        ".",
        "which is the `.` the reader typed"
    );
    let size = answered
        .items
        .iter()
        .find(|item| item.label == "size")
        .expect("the pointee's member is offered");
    assert_eq!(
        size.insert, "->size",
        "and the insertion carries the operator the member can actually follow"
    );
}

/// **`->` is not `.`** — the flag the completion of a member follows `operator->` with.
///
/// `MemberAccess::arrow` was hard-coded `false` by the text fallback, so a cursor after `ptr->` was answered as if
/// the reader had typed `ptr.`: a class whose members live behind `operator->` was looked up for its **own** members.
/// The operator's own spelling is the only evidence there is, and it is one token to read.
#[test]
fn an_arrow_is_read_as_an_arrow() {
    let text = "void f(Widget* p, Widget v) {\n    p->\n    v.member\n}\n";
    let tree = cpp_parser::CppParser::parse(text, cpp_parser::ParserConfig::default());
    let root = tree.get_red_root();

    let arrow =
        cpp_code_analysis::completion::context_at(&root, text.find("p->").expect("fixture") + 3);
    match arrow {
        cpp_code_analysis::completion::CompletionContext::Member(access) => {
            assert!(
                access.arrow,
                "the operator written is `->`, so this is an arrow access"
            );
            assert!(
                access.member.is_empty(),
                "nothing is typed after the operator yet"
            );
        }
        other => panic!("a member access is what follows an arrow, not {other:?}"),
    }

    // And the other spelling: `v.member` is a dot, and the member is written.
    let dot = cpp_code_analysis::completion::context_at(
        &root,
        text.find("v.member").expect("fixture") + 4,
    );
    match dot {
        cpp_code_analysis::completion::CompletionContext::Member(access) => {
            assert!(!access.arrow, "a `.` is not an arrow");
            assert_eq!(access.member, "member");
        }
        other => panic!("a member access is what follows a dot, not {other:?}"),
    }
}

/// **A member answer says whether it is missing members**, and a client has to be told.
///
/// `isIncomplete` in the protocol means one thing — *ask again later* — and a member list has two
/// ways of being short: the budget (`truncated`, where asking again returns the same list) and the
/// **analysis** (`incomplete`: a class this answer depends on has not been read). Measured on a
/// real project: `std::string* message; message->` answered **one** item on the first keystroke
/// (`operator basic_string_view`, all the raw reading of `<xstring>` had at file scope) and **58**
/// once the header was cooked — and the one-item list went out with `isIncomplete: false`, so the
/// client showed it as the answer.
#[test]
fn a_member_answer_that_is_missing_facts_is_marked_incomplete() {
    // **A class nothing declares**: the honest answer is "not yet", not "no members".
    let unknown = "\
int f() {
    no_such_class* p = nullptr;
    p->
    return 0;
}
";
    let (session, view) = one_file_session(unknown);
    let offered = session.completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(at_the_end_of(unknown, "p->")),
    );
    assert!(offered.items.is_empty(), "{:?}", offered.items);
    assert!(
        offered.incomplete,
        "a class this analysis cannot see is a missing fact, so the client must be allowed to ask again"
    );

    // **A class it can see**: complete, and the flag says so.
    let known = "\
struct Widget { int size; int grow; };
int f() {
    Widget* p = nullptr;
    p->
    return 0;
}
";
    let (session, view) = one_file_session(known);
    let offered = session.completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(at_the_end_of(known, "p->")),
    );
    let labels: Vec<&str> = offered
        .items
        .iter()
        .map(|item| item.label.as_str())
        .collect();
    assert_eq!(labels, vec!["grow", "size"], "the pointee's members");
    assert!(
        !offered.incomplete,
        "nothing is missing here, so the list stands as it is"
    );
}

/// **A smart pointer's arrow reaches the pointee, through `element_type`** — the standard's pointer-like protocol.
///
/// `<memory>`'s `unique_ptr::operator->` returns `pointer`, a member typedef whose target is a dependent
/// `typename _Get_deleter_pointer_type<…>::type`: an engine that does not instantiate metafunctions cannot follow
/// that declaration, and before this it fell back to the *smart pointer's own* members. Measured on a real project:
/// `std::unique_ptr<int> p; p->` offered `get`, `get_deleter` and `operator*` — none of which can be written after
/// that arrow — and `std::unique_ptr<std::string> p; p->` offered nothing at all.
///
/// `element_type` is what `std::pointer_traits` is written in terms of, so this is the standard's answer rather than
/// a guess about one class; a class that is not pointer-like declares none, and nothing else is affected.
#[test]
fn a_smart_pointers_arrow_reaches_what_element_type_names() {
    let header = "\
namespace std {
template <class T> struct pointers {
    typedef typename T::pointer pointer;
};
template <class T> struct unique_ptr {
    T* stored;
    typedef T element_type;
    typedef typename pointers<T>::pointer pointer;
    pointer operator->() const;
    T& operator*() const;
    int get() const;
};
struct string { int size() const; const char* c_str() const; };
}
";
    let source = "\
#include \"smart.h\"
int f() {
    std::unique_ptr<std::string> p;
    p->
    return 0;
}
";
    let files = MemoryFiles::new()
        .with_file("/p/smart.h", header)
        .with_file("/p/a.cpp", source);
    let providers = SessionFiles::new(OpenDocuments::new(), files);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([
        std::path::PathBuf::from("/p/smart.h"),
        std::path::PathBuf::from("/p/a.cpp"),
    ]);
    session.index_everything();
    let view = cooked_view(&mut session, "/p/a.cpp");

    let offered = session.completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(at_the_end_of(source, "p->")),
    );
    let labels: Vec<&str> = offered
        .items
        .iter()
        .map(|item| item.label.as_str())
        .collect();
    assert!(
        labels.contains(&"size") && labels.contains(&"c_str"),
        "`element_type` says the arrow reaches `std::string`: {labels:?}"
    );
    assert!(
        !labels.contains(&"get"),
        "the smart pointer's own members cannot be written after its arrow: {labels:?}"
    );
}

/// **A pointer-like class spelled without its namespace still reaches its pointee.**
///
/// The spelling of a deduced return type comes from the **declaration**, which libstdc++ writes inside `namespace
/// std`: `make_shared<_Yp>` returns `shared_ptr<_Yp>`, so a hover on `make_shared<Resource>()->identifier()` holds
/// `shared_ptr<Resource>` and has to find the class `std::shared_ptr`. Measured on `test_cpp`'s
/// `smart_pointers.cpp`: `members_of("shared_ptr")` answered 0 members while `members_of("std::shared_ptr")`
/// answered 39, and the hover said "`shared_ptr<Resource>` has no member `identifier`".
#[test]
fn a_bare_class_spelling_is_qualified_by_the_index() {
    let header = "\
namespace std {
template <class T> struct __shared_ptr {
    typedef T element_type;
    element_type* operator->() const;
};
template <class T> struct shared_ptr : __shared_ptr<T> {
    using element_type = typename __shared_ptr<T>::element_type;
};
}
struct Resource { int identifier() const; };
";
    let source = "\
#include \"smart.h\"
int f() {
    std::shared_ptr<Resource> p;
    return p->identifier();
}
";
    let files = MemoryFiles::new()
        .with_file("/p/smart.h", header)
        .with_file("/p/a.cpp", source);
    let providers = SessionFiles::new(OpenDocuments::new(), files);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([
        std::path::PathBuf::from("/p/smart.h"),
        std::path::PathBuf::from("/p/a.cpp"),
    ]);
    session.index_everything();
    let view = cooked_view(&mut session, "/p/a.cpp");

    // **The bare spelling**, which is what a deduced return type records.
    let reached = session.the_class_after_the_operator(&view, "shared_ptr<Resource>", true);
    assert_eq!(
        reached.as_deref(),
        Some("Resource"),
        "the arrow reaches the pointee through element_type"
    );

    // And the member list of the bare spelling is the class's, not an empty one.
    let listed = session.members_of(&view, "shared_ptr<Resource>");
    assert!(
        matches!(&listed, Known::Yes(list) if list.members.iter().any(|member| member.fact.name == "element_type")),
        "the bare spelling names the class: {listed:?}"
    );
}

/// **A dot on a smart pointer is the handle's own members**, and only an arrow reaches the pointee.
///
/// `std::shared_ptr<Resource> shared;` answers twelve members with a `.` — `reset`, `get`, `use_count`, the
/// assignment operators, the constructors — and `Resource`'s with a `->`. Following `element_type` for a dot as
/// well listed the pointee's two members instead (measured on `test_cpp/src/smart_pointers.cpp`: `shared.` offered
/// `identifier` and `~Resource`), which is the report that the handle's own fields were not completed.
#[test]
fn a_dot_on_a_smart_pointer_offers_its_own_members() {
    let header = "\
namespace std {
template <class T> struct __shared_ptr {
    typedef T element_type;
    void reset();
    long use_count() const;
};
template <class T> struct shared_ptr : __shared_ptr<T> {
    using element_type = typename __shared_ptr<T>::element_type;
    T* get() const;
};
}
struct Resource { int identifier() const; };
";
    let source = "\
#include \"smart.h\"
int f() {
    std::shared_ptr<Resource> shared;
    shared.
    return 0;
}
";
    let files = MemoryFiles::new()
        .with_file("/p/smart.h", header)
        .with_file("/p/a.cpp", source);
    let providers = SessionFiles::new(OpenDocuments::new(), files);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([
        std::path::PathBuf::from("/p/smart.h"),
        std::path::PathBuf::from("/p/a.cpp"),
    ]);
    session.index_everything();
    let view = cooked_view(&mut session, "/p/a.cpp");

    let offered = session.completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(at_the_end_of(source, "shared.")),
    );
    let labels: Vec<&str> = offered
        .items
        .iter()
        .map(|item| item.label.as_str())
        .collect();
    assert!(
        labels.contains(&"reset") && labels.contains(&"use_count") && labels.contains(&"get"),
        "the handle's own members are what a dot means: {labels:?}"
    );
    assert!(
        !labels.contains(&"identifier"),
        "and the pointee's members are not: {labels:?}"
    );
}

/// One file in one project, cooked, with a view of it — the shape the two tests above share.
fn one_file_session(source: &str) -> (Session<MemoryFiles>, cpp_code_analysis::FileView) {
    let files = MemoryFiles::new().with_file("/p/a.cpp", source);
    let providers = SessionFiles::new(OpenDocuments::new(), files);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
    session.index_everything();
    let view = cooked_view(&mut session, "/p/a.cpp");
    (session, view)
}

/// The file offset just after the first `needle` — where a cursor sits when the reader has typed it.
fn at_the_end_of(source: &str, needle: &str) -> usize {
    source.find(needle).expect("the fixture writes it") + needle.len()
}

/// **A pointee that is not a class has no members, and that answer is final.**
///
/// `int* p; p->` walks the pointer, finds `int`, and `int` names no class — so the list is empty *and complete*. The
/// distinction is the protocol's: an empty list marked `isIncomplete` tells a client to ask again, and here nothing
/// can change, so the popup would stand empty for ever. It is where `std::vector<int> v; v.begin()->` lands too: the
/// iterator's arrow reaches `int`.
#[test]
fn a_pointee_that_is_not_a_class_answers_nothing_and_is_complete() {
    let source = "\
int f() {
    int* p = nullptr;
    p->
    return 0;
}
";
    let (session, view) = one_file_session(source);
    let offered = session.completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(at_the_end_of(source, "p->")),
    );
    assert!(offered.items.is_empty(), "{:?}", offered.items);
    assert!(
        !offered.incomplete,
        "`int` is not missing anything: the list is final"
    );
}

/// A session over one **open** file, drained — the state a completion is asked in.
///
/// `did_open` rather than [`cooked_view`], and the difference is not incidental: a *cook* answers a question about a
/// file from its summary, and the rendering that comes back is condensed onto one line (measured here:
/// `"struct Widget { int size; }; void f() { Widget * p; p-> Widget w; w. }"` for a five-line file). A completion is
/// asked about the file the reader has **open**, whose rendering is its own text with its own line breaks — and line
/// breaks are what a recovery rule can read. See the module documentation of `cpp_parser`'s `exprs.rs` on the member
/// name that must be on the operator's line.
fn a_pointer_fixture(text: &'static str) -> (Session<MemoryFiles>, cpp_code_analysis::FileView) {
    let memory = MemoryFiles::new().with_file("/p/a.cpp", text);
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.did_open("/p/a.cpp", text);
    session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
    session.index_everything();
    let mut rounds = 0;
    while session.pending() > 0 && rounds < 400 {
        session.advance(16);
        rounds += 1;
    }
    let view = session
        .view("/p/a.cpp")
        .expect("the open file's own reading");
    (session, view)
}

/// **An arrow on a pointer inserts the member's name, and only the name.**
///
/// Measured before this: `Widget* p; p->` answered the pointee's members with `insert: "->length"` and a replacement
/// range grown one byte to the left, over the `>` — accepting an item wrote `p-->length`. The rewrite is for the one
/// case where the operator typed and the answer disagree, a `.` on a pointer; on `->` the reader already typed the
/// right operator, so the name is the whole insertion and the range is empty where the name goes.
#[test]
fn an_arrow_on_a_pointer_inserts_the_name_and_not_the_operator() {
    let text = "struct Widget { int size; int length; };\nvoid f()\n{\nWidget * p;\np->\n}\n";
    let (session, view) = a_pointer_fixture(text);
    let at = text.find("p->").expect("the fixture writes it") + 3;
    let set = session.completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(at),
    );

    let mut labels: Vec<String> = set.items.iter().map(|item| item.label.clone()).collect();
    labels.sort_unstable();
    assert_eq!(
        labels,
        ["length", "size"],
        "the pointee's members, not names: {set:?}"
    );
    for item in &set.items {
        assert_eq!(
            item.insert, item.label,
            "the arrow is the reader's, not part of what a member inserts"
        );
    }
    assert_eq!(
        (set.replace.start_offset, set.replace.length),
        (at, 0),
        "nothing is written after the operator, so the range is empty where the name goes"
    );
}

/// **A `.` on a pointer is still rewritten to `->`** — the one case the rewrite is for.
///
/// `p.size` on a `Widget*` does not compile, and C++ has no such member; the list is the pointee's, which is what the
/// reader meant, and the operator they typed is the half that is wrong. So the insertion gains `->` and the range
/// grows one byte left to cover the `.`.
#[test]
fn a_dot_on_a_pointer_still_rewrites_the_operator() {
    let text = "struct Widget { int size; };\nvoid f()\n{\nWidget * p;\np.\n}\n";
    let (session, view) = a_pointer_fixture(text);
    let at = text.find("p.\n").expect("the fixture writes it") + 2;
    let set = session.completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(at),
    );

    assert_eq!(set.items.len(), 1, "one member: {set:?}");
    assert_eq!(
        set.items[0].insert, "->size",
        "the operator is part of the insertion"
    );
    assert_eq!(
        (set.replace.start_offset, set.replace.length),
        (at - 1, 1),
        "the `.` is replaced along with the name's position"
    );
}

/// **`co_await` has the type its awaiter's `await_resume()` returns.**
///
/// ```cpp
/// task<payload> greet();
/// task<int> use() { auto s = co_await greet(); s. }   // `s` is a `payload`
/// ```
///
/// The awaited expression is a `UnaryExpr` with a `co_await` token, and without an arm for it `s` was a type nobody
/// knew: measured on `test_cpp/coroutine.cpp`, completion after `auto s = co_await greet("x"); s.` answered
/// **nothing**, while the coroutine parsed, hovered and coloured correctly. The awaiter is the operand's own type
/// (`task<T>` is its own awaiter) and the value is `await_resume()`'s return type, read through the class's template
/// arguments — `T` becomes `payload` — which is the same substitution the member lookups already do.
#[test]
fn an_awaited_value_has_the_type_await_resume_returns() {
    let text = "\
struct payload {
    int size() const;
    int length() const;
};

template <typename T>
struct task {
    struct promise_type {
        task get_return_object() { return task{}; }
        std::suspend_always initial_suspend() { return {}; }
        std::suspend_always final_suspend() noexcept { return {}; }
        void return_value(T v) {}
        void unhandled_exception() {}
    };
    bool await_ready() const noexcept { return false; }
    void await_suspend(std::coroutine_handle<>) {}
    T await_resume() { return T{}; }
};

task<payload> greet();

task<int> use() {
    auto s = co_await greet();
    s.
    co_return 0;
}
";
    let (session, view) = a_pointer_fixture(text);
    let at = text.find("    s.\n").expect("the fixture writes it") + 6;
    let set = session.completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(at),
    );

    let mut labels: Vec<String> = set.items.iter().map(|item| item.label.clone()).collect();
    labels.sort_unstable();
    assert_eq!(
        labels,
        ["length", "size"],
        "the awaited value is a `payload`, so its members are what a completion offers: {set:?}"
    );
}

/// **A member typedef of a class template names the class it points at.**
///
/// ```cpp
/// template <typename T> struct outer { using handle_type = body; };
/// outer<int>::handle_type h;  h.        // the members of `body`, not of `outer`
/// ```
///
/// The spelling of such a type is `outer<int>::handle_type`, and two readers cut it at the **first** `<`:
/// `base_type_name` — which is what `members_of` starts from, so the class asked about was `outer` — and
/// `alias_target_of`, whose head split exists for an *alias template's own* arguments (`enable_if_t<int, double>`).
/// Measured: the completion offered `outer`'s own typedefs (`handle_type`) while the same class written without the
/// argument answered the target's members, and a coroutine's `task<int>::handle_type h; h.` offered `await_ready`/
/// `take` instead of `resume`/`promise`.
///
/// The three shapes below are one test because they share the one helper: stripping a **qualifier's** argument list
/// must leave an alias template's own arguments alone.
#[test]
fn a_member_typedef_of_a_class_template_names_its_target() {
    let plain = "\
struct body {
    int size() const;
    int length() const;
};
struct outer {
    using handle_type = body;
};
void f() { outer::handle_type h{}; h. }
";
    assert_eq!(
        member_labels_at(plain, "h."),
        ["length", "size"],
        "a class member typedef, without arguments"
    );

    let templated = "\
struct body {
    int size() const;
    int length() const;
};
template <typename T>
struct outer {
    using handle_type = body;
};
void f() { outer<int>::handle_type h{}; h. }
";
    assert_eq!(
        member_labels_at(templated, "h."),
        ["length", "size"],
        "the same typedef on a class template: the argument belongs to the use, not to the name"
    );

    // A member typedef whose target is itself a template-id, which is what a coroutine's `handle_type` is.
    let coroutine = "\
namespace std {
template <typename P>
struct coroutine_handle {
    static coroutine_handle from_promise(P &promise);
    void resume();
    void destroy();
    bool done() const;
    P &promise() const;
    void *address() const;
};
}
template <typename T>
struct task {
    struct promise_type { };
    using handle_type = std::coroutine_handle<promise_type>;
};
void f() { task<int>::handle_type h{}; h. }
";
    let labels = member_labels_at(coroutine, "h.");
    for wanted in ["resume", "destroy", "promise", "address", "from_promise"] {
        assert!(
            labels.iter().any(|label| label.as_str() == wanted),
            "`task<int>::handle_type` is a `coroutine_handle`, so it has `{wanted}`: {labels:?}"
        );
    }

    // A **nested class** addressed through its outer class's template-id is the same spelling shape, and it must not
    // lose its own members to it: `outer<int>::promise_type` is a class declared inside `outer`.
    let nested_class = "\
template <typename T>
struct outer {
    struct promise_type {
        T get_return_object();
        std::suspend_always initial_suspend();
        T return_value(T v);
    };
};
void f() { outer<int>::promise_type p{}; p. }
";
    assert_eq!(
        member_labels_at(nested_class, "p."),
        ["get_return_object", "initial_suspend", "return_value"],
        "a nested class named through its outer class's template-id keeps its own members"
    );

    // …and an alias template's own arguments still substitute, which the same split is responsible for.
    let alias_template = "\
template <bool B, typename T = void>
struct enable_if { using type = T; };
template <bool B, typename T = void>
using enable_if_t = typename enable_if<B, T>::type;
struct payload { int size() const; };
void f() { enable_if_t<true, payload> p{}; p. }
";
    assert_eq!(
        member_labels_at(alias_template, "p."),
        ["size"],
        "an alias template's arguments are substituted, not stripped"
    );
}

/// **A namespace alias names a scope whose members are declared elsewhere.**
///
/// `namespace views = ranges::views;` is how `<ranges>` spells `std::views`, and the alias declares no names of its
/// own: completion after `std::views::` answered **0** items while `filter`, `transform`, `reverse`, `drop` and `take`
/// are all declared in `std::ranges::views`. Measured on the corpus's `ranges.cpp` before this was fixed.
///
/// The second half is the one that needs the index: an alias from a **header** is not a scope in the buffer's own
/// scope tree, so the target has to be recorded on the alias's fact — see `declared_namespace_alias_target_with`.
#[test]
fn a_namespace_alias_offers_the_names_of_its_target() {
    // Declared in the file itself: both namespaces are scopes of this buffer.
    let source = "\
namespace ranges { namespace views { int filter; int transform; } }
namespace std { namespace views = ranges::views; }
void f() { std::views:: }
";
    let mut memory = MemoryFiles::new().with_file("/p/a.cpp", source);
    let _ = &mut memory;
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
    let view = cooked_view(&mut session, "/p/a.cpp");
    let at = source.find("std::views::").expect("the fixture writes it") + "std::views::".len();
    let labels: Vec<String> = session
        .completions(
            &view,
            cpp_code_analysis::file::coordinates::FileOffset::new(at),
        )
        .items
        .into_iter()
        .map(|item| item.label)
        .collect();
    assert!(
        labels.iter().any(|label| label == "filter"),
        "a `views` adapter is written in the alias target: {labels:?}"
    );
}

/// The same question when the alias lives in a **header** the buffer includes.
#[test]
fn a_namespace_alias_from_a_header_offers_the_names_of_its_target() {
    let header = "\
namespace ranges { namespace views { int filter; int transform; } }
namespace std { namespace views = ranges::views; }
";
    let source = "\
#include \"views_like.h\"
void f() { std::views:: }
";
    let memory = MemoryFiles::new()
        .with_file("/p/a.cpp", source)
        .with_file("/p/views_like.h", header);
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([
        std::path::PathBuf::from("/p/a.cpp"),
        std::path::PathBuf::from("/p/views_like.h"),
    ]);
    let view = cooked_view(&mut session, "/p/a.cpp");
    let at = source.find("std::views::").expect("the fixture writes it") + "std::views::".len();
    let labels: Vec<String> = session
        .completions(
            &view,
            cpp_code_analysis::file::coordinates::FileOffset::new(at),
        )
        .items
        .into_iter()
        .map(|item| item.label)
        .collect();
    assert!(
        labels.iter().any(|label| label == "filter"),
        "the alias's target is in the header, not in this buffer: {labels:?}"
    );
}

/// The member labels offered after `needle` in a one-file fixture, sorted.
fn member_labels_at(source: &'static str, needle: &str) -> Vec<String> {
    let (session, view) = a_pointer_fixture(source);
    let at = source.find(needle).expect("the fixture writes it") + needle.len();
    let set = session.completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(at),
    );
    let mut labels: Vec<String> = set.items.iter().map(|item| item.label.clone()).collect();
    labels.sort_unstable();
    labels
}

/// **`std::views::` completes the adaptors**, even though the index holds none of them.
///
/// Measured: `members_of("std::views")` answers **0** while `std::ranges` answers 125 — libstdc++ fills the `views`
/// namespace with `inline constexpr` adaptor objects the summary does not reach — so `numbers | std::views::f` completed
/// nothing on the header whose whole purpose is those names. The set is closed and the names are the standard's, so they
/// come from a table; a name the index also holds is merged by label.
#[test]
fn the_views_adaptors_complete_after_the_scope() {
    let source = "#include <ranges>\n#include <vector>\n\
                  int main() { std::vector<int> numbers; for (auto v : numbers | std::views::) { } }\n";
    let files = MemoryFiles::new().with_file("/p/a.cpp", source);
    let providers = SessionFiles::new(OpenDocuments::new(), files);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
    let view = cooked_view(&mut session, "/p/a.cpp");
    let at = source.find("std::views::)").expect("the fixture") + "std::views::".len();
    let offered = session.completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(at),
    );
    let labels: Vec<&str> = offered
        .items
        .iter()
        .map(|item| item.label.as_str())
        .collect();

    for adaptor in [
        "filter",
        "transform",
        "take",
        "drop",
        "reverse",
        "keys",
        "values",
        "join",
        "iota",
    ] {
        assert!(
            labels.contains(&adaptor),
            "`std::views::{adaptor}` is offered: {labels:?}"
        );
    }
}

/// **A documentation comment completes symbols where it refers to one**, and code inside `@code`.
///
/// Two shapes the documentation support got wrong: `@see Widget::gr` offered the documented declaration's *parameters*
/// (the command takes a reference, not a name it declares), and an `@code` block offered nothing at all, because the
/// prose rule — right for the sentence around it — was applied to the example too.
#[test]
fn a_documentation_comment_completes_its_references_and_its_code() {
    const SOURCE: &str = "\
struct Widget { void grow(int by); };
/// @see Wid
/// @code
/// Wid
/// @endcode
void f() {}
";
    let memory = MemoryFiles::new().with_file("/p/a.cpp", SOURCE);
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.load("/p/a.cpp");

    // The reference: names, filtered by what is typed — and no snippet, because a reference is not a statement.
    let reference = SOURCE.find("@see Wid").expect("the fixture") + "@see Wid".len();
    let labels = labels_at(&mut session, "/p/a.cpp", reference);
    assert!(
        labels.iter().any(|label| label == "Widget"),
        "`@see Wid` completes the name it refers to: {labels:?}"
    );
    assert!(
        !labels.iter().any(|label| label == "class"),
        "and not the keyword table: {labels:?}"
    );

    // The code block: an example is code, so its completion is the one a statement gets.
    let inside_the_block = SOURCE.find("/// Wid").expect("the fixture") + "/// Wid".len();
    let labels = labels_at(&mut session, "/p/a.cpp", inside_the_block);
    assert!(
        labels.iter().any(|label| label == "Widget"),
        "a word inside `@code` completes the program's names: {labels:?}"
    );
    assert!(
        labels.iter().any(|label| label == "class"),
        "and it is code, so the keyword table belongs: {labels:?}"
    );
}

/// **A session over one file, built the way a server builds it** — the pump, the ask, the pump.
fn session_of(source: &str) -> Session<MemoryFiles> {
    let memory = MemoryFiles::new().with_file("/p/macros.cpp", source);
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([std::path::PathBuf::from("/p/macros.cpp")]);
    session
}

/// **The file's own macros are offered at file scope, with the cursor at the end of what was typed.**
///
/// Reported from `EmmyLuaCodeStyle`: a file whose first forty lines are `#define lisl*(c) …` answered **no completion
/// at all** when the reader typed `lis` at file scope.  Two defects met here, and both are asserted below:
///
/// * a `#define` is a preprocessing fact of *this* file, not a declaration in any scope, so the index half cannot see
///   it — the macro tail of the query exists for that;
/// * the **caret at the end of a word** mapped to no position in the rendering, because the mapping compared a
///   *rendering* offset against a *file* one and the file's first four lines are `#define`s, which the rendering does
///   not have.  Every completion asked with the caret after the letters already typed was answered from `None`, which
///   the caller reports as "completion does not work at all".
#[test]
fn the_files_own_macros_are_offered_at_file_scope() {
    let source = "\
#define testprop(c, m) ((m) & MASK(c))
#define lislalpha(c) testprop(c, MASK(ALPHABIT))
#define lislalnum(c) testprop(c, MASK(ALPHABIT) | MASK(DIGITBIT))
#define lisdigit(c) testprop(c, MASK(DIGITBIT))
int f() { return 0; }
lis
";
    let mut session = session_of(source);
    let view = cooked_view(&mut session, "/p/macros.cpp");
    // **The caret after the typed letters**, which is where a reader's is.
    let cursor = source.find("\nlis\n").expect("the fixture") + "\nlis".len();

    let set = session.completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(cursor),
    );
    let labels: Vec<&str> = set.items.iter().map(|item| item.label.as_str()).collect();
    assert!(
        set.items.iter().any(|item| item.label == "lislalpha"),
        "the file defines it ten lines above the cursor: {labels:?}"
    );
    assert!(
        set.items.iter().any(|item| item.label == "lislalnum"),
        "and the second one: {labels:?}"
    );
    assert!(
        !set.items.iter().any(|item| item.label == "testprop"),
        "a macro that does not start with what the reader wrote is not offered: {labels:?}"
    );
}

/// **A designator offers the members of the declared variable's type.**
///
/// Reported from a real editor: typing `.` inside `DecorSignHighlight conv = { … }` offered `f`, `case`, `catch`,
/// `class`, `dowhile`, … — the names in scope — and not one of the struct's members. The tree has no initializer
/// list at that cursor (a file being typed at is a file in recovery: measured, `token "." → CompoundStat →
/// Declaration(f)`), so the declaration is read from the text: the nearest unmatched `{`, the `=` before it, the
/// name, and the type before the name.
#[test]
fn a_designator_in_a_braced_initializer_offers_the_structs_members() {
    const FIXTURE: &str = r"typedef struct {
  int flags;
  int priority;
  int text[4];
  int hl_id;
} DecorSignHighlight;
void f(void) {
  DecorSignHighlight conv = {
    .
  };
}";

    let at = FIXTURE.find("    .").expect("the designator's dot") + "    .".len();
    let memory = MemoryFiles::new().with_file("/p/a.c", FIXTURE);
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([std::path::PathBuf::from("/p/a.c")]);
    let view = cooked_view(&mut session, "/p/a.c");

    let found = session.completions(
        &view,
        cpp_code_analysis::file::coordinates::FileOffset::new(at),
    );
    let labels: Vec<String> = found.items.iter().map(|item| item.label.clone()).collect();
    for member in ["flags", "priority", "text", "hl_id"] {
        assert!(
            labels.contains(&member.to_string()),
            "`{member}` is a member of the initialised struct: {labels:?}"
        );
    }
    assert!(
        !labels.contains(&"DecorSignHighlight".to_string()),
        "and the list is the members, not the names in scope: {labels:?}"
    );
    assert_eq!(
        found.scope, "DecorSignHighlight",
        "the list names the class it is about"
    );
}

/// **A `#define`'s replacement list completes a `qualifier::`** — `#define PICK(v) Thing::si` names a class, and the
/// names after the `::` are its members, not the macro vocabulary.
///
/// Two halves, and neither worked before this:
///
/// * **The qualifier**: `CompletionContext::MacroBody` carried `written`, `range` and the parameters, and nothing about
///   a qualifier, so every replacement list took the "macro's own parameters, then the macros" path. Measured with
///   `inspect complete` at the cursor after `std::` in `#define LOG(value) std::cout << value`: `scope ``, prefix ``,
///   22 item(s)` — the wrong list for a reader writing `std::cout`.
/// * **The prefix**: `segment_written` answered the *first* token of the text it was given and then clamped the cursor
///   into it, which is right only while the cursor is in that token. A replacement list always has a space after the
///   parameter list, so its first token was the empty string and **every** body position had an empty prefix — the
///   filter had never run there.
///
/// The panel's answer for a namespace declared in the same file is still empty, and that is not this: the same
/// `my::Thi` in a function body answers nothing either. What this pins is that a macro body and a function body now
/// answer the *same* question.
#[test]
fn a_macro_body_completes_a_qualified_name() {
    let source = "\
struct Thing {
    int size;
};

#define MEMBER(v) Thing::si
#define COMPOSED(a, b) MEMBER(a) ME
";
    let files = MemoryFiles::new().with_file("/p/a.cpp", source);
    let providers = SessionFiles::new(OpenDocuments::new(), files);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
    let view = cooked_view(&mut session, "/p/a.cpp");

    let offered_at = |at: usize| {
        session.completions(
            &view,
            cpp_code_analysis::file::coordinates::FileOffset::new(at),
        )
    };
    let labels = |offered: &cpp_code_analysis::CompletionSet| {
        offered
            .items
            .iter()
            .map(|item| item.label.clone())
            .collect::<Vec<String>>()
    };

    // A class's members, filtered by what has been typed of the name.
    let at = source.find("Thing::si").expect("the fixture") + "Thing::si".len();
    let found = offered_at(at);
    assert_eq!(found.scope, "Thing", "the qualifier is the scope");
    assert_eq!(found.prefix, "si", "and the prefix is the name being typed");
    assert_eq!(
        labels(&found),
        vec!["size".to_string()],
        "{:?}",
        labels(&found)
    );

    // An unqualified body keeps the macro vocabulary — and its prefix is what has been typed too, which is the half
    // that made every earlier prefix empty.
    let at = source.find("MEMBER(a) ME").expect("the fixture") + "MEMBER(a) ME".len();
    let found = offered_at(at);
    assert_eq!(found.scope, "", "no qualifier, so the macro vocabulary");
    assert_eq!(found.prefix, "ME");
    assert!(
        labels(&found).iter().any(|name| name == "MEMBER"),
        "filtered by the prefix: {:?}",
        labels(&found)
    );
}