cpp_ls 0.3.0

A C, C++ and CUDA language server.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
//! An end-to-end test over the server's own stdio: the handshake, one edit, and the answers this server gives.
//!
//! Everything below `server/` is unit-tested — the analysis engine has a thousand tests of its own — and none of
//! that proves the *shell* works: that a client can say `initialize`, get capabilities back, open a file, and
//! receive a diagnostic, a definition and a hover over the wire. That is what this test is for, and it is the only
//! place in the crate that speaks the protocol as a **client** does.
//!
//! ```text
//! initialize ──▶ capabilities          definition ──▶ the declaration's file and range
//! initialized ─▶ the workspace opens   hover ──────▶ markdown about the name under the cursor
//! didOpen ────▶ the buffer is the text textDocument/diagnostic ──▶ the file's report
//! ```
//!
//! # Why diagnostics are **pulled** and not awaited
//!
//! The server does not publish diagnostics. `textDocument/diagnostic` is asked, and `Server::pull_diagnostics` is
//! how these tests ask it — the same request a client makes, so every diagnostic assertion here exercises the path
//! a user's editor takes. There used to be a push half beside it, and a client that declared
//! `textDocument.diagnostic` got that instead; two channels for one answer is how a screen ends up holding an
//! answer about text that is gone.
//!
//! # Why the definition is asked for more than once
//!
//! Because the index is **lazy on purpose**: `didOpen` queues the file, the background loop reads it and follows
//! its includes, and a query that arrives in between legitimately answers "not declared here yet" — the analysis
//! says so rather than guessing (`Session::pending` is how a caller tells that apart from a real absence). A test
//! that asked once would be asserting about the scheduler, so this one asks until it gets an answer, with a
//! deadline. A wrong answer is a wrong answer whenever it arrives; a slow one is not a failure.

use std::io::{BufRead, BufReader, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::mpsc::{Receiver, RecvTimeoutError, channel};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use serde_json::{Value, json};

/// How long any single expectation may take. Generous: a debug build parses a project's first file, and CI is slow.
/// How long a test waits for an answer before calling it a failure.
///
/// Thirty seconds is generous for a project of fixture files and it is **not** generous for one that pulls in the
/// standard library: `#include <string>` is a closure of thousands of MSVC headers, and the first request about a
/// name inside it waits for the index to read them. A test whose subject *is* that closure therefore waits longer —
/// see [`STD_LIBRARY_TIMEOUT`] — rather than the whole file being given a longer deadline, because a fixture that
/// hangs should still fail in half a minute.
const TIMEOUT: Duration = Duration::from_secs(30);

/// The deadline for a test that makes the analysis read a standard-library header, which is real work.
const STD_LIBRARY_TIMEOUT: Duration = Duration::from_secs(180);

const WIDGET_H: &str = "struct Widget { int size; };\n";

/// A file with two things to find and one thing to report: a use of `Widget`, a member access, and a class whose
/// brace is never closed.
///
/// The unclosed `{` is deliberate and it is the *only* error in the file: the parser reports `expected ;` at the
/// end of the last line, which gives the diagnostic assertion a line and a column to check rather than a count.
/// (`int g() { return 1 }` — a missing semicolon before a closing brace — is **not** reported by this parser; that
/// is a real gap in its error reporting and it is recorded.)
const MAIN_CPP: &str = "#include \"widget.h\"\n\nvoid f() {\n    Widget w;\n    w.size = 1;\n}\nstruct Unclosed { int x;\n";

/// **A client that pulls gets a report, not `null`.**
///
/// The reported symptom was that diagnostics did not change while typing, and this is the layer it was in. A client
/// that advertises `textDocument.diagnostic` is answered by `textDocument/diagnostic`, and that handler went through
/// `snapshot_query` → `query_blocking` → `RequestOutcome::Missing`, which `ServerContext::task` turns into
/// **`Response::new_ok(id, Value::Null)`**.
///
/// `null` is not a `DocumentDiagnosticReport`. A client that asked for one and got `null` cannot tell it from a
/// failure, so it keeps the diagnostics it already had — which is precisely "输入代码之后诊断不改变".
///
/// There were **two** ways to reach `Missing` and both are fixed in the handler:
///
/// ```text
/// the file was never read         `prepare` queues cooking and returns, so the query found no reading
/// `diagnose_file` answered None   …which was then reported as `Missing` rather than as "nothing wrong"
/// ```
///
/// So this asserts what a pull client needs: the answer is an **object with an `items` array** (the shape the
/// protocol requires), it is non-empty for a file with a parse error, and **asking twice gives the same answer** —
/// a pulling client re-asks after every edit, and a screen that flickers between answers is one nobody trusts.
///
/// This is also the test that says the push half is gone: it declares the pull capability, and no test in this file
/// waits for a `publishDiagnostics` notification any more, because the server does not send one.
#[test]
fn a_pulling_client_gets_a_report_and_not_null() {
    let project = Project::new("pull-diagnostics");
    project.write("widget.h", WIDGET_H);
    project.write("main.cpp", MAIN_CPP);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    let initialized = server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                // **The pull capability**, which is what routes diagnostics to the request instead of the
                // notification. Its absence is what the other tests exercise.
                "textDocument": { "diagnostic": { "dynamicRegistration": false } },
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    assert_eq!(
        initialized["result"]["capabilities"]["diagnosticProvider"]["interFileDependencies"],
        json!(true),
        "the server advertises the provider a pulling client looks for: {initialized}"
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": MAIN_CPP }
        }),
    );

    let report = server.ask_until(100, |id| {
        json!({
            "id": id,
            "method": "textDocument/diagnostic",
            "params": { "textDocument": { "uri": main_uri } },
        })
    });

    assert!(
        !report["result"].is_null(),
        "`null` is what a client cannot act on, and it is what this answered: {report}"
    );
    let items = report["result"]["items"].as_array().unwrap_or_else(|| {
        panic!("a full document diagnostic report has an `items` array: {report}")
    });
    assert!(
        !items.is_empty(),
        "the file has an unclosed class, so a report with no items is \"clean\" and wrong: {report}"
    );
    assert!(
        items.iter().any(|item| item["message"]
            .as_str()
            .is_some_and(|message| message.contains(';'))),
        "and the parse error is the one the push test also expects: {report}"
    );

    // --- **Asking twice is answered twice, and the second answer is the same** -----------------------
    //
    // A pulling client re-asks after every edit, so the request is made repeatedly against unchanged text. The
    // answer must be the *same* answer and not, say, one that depends on whether the reading happened to be cached —
    // which is the property that makes a pull client's screen stable.
    //
    // **And it is where a duplicate was found**: measured, this same file reported its `expected \`;\`` **twice** on
    // the second ask. `prepare_for_a_diagnostic` re-reads and re-cooks the file, and a path that is cooked twice can
    // be counted twice by whatever reads the errors.
    // asserted about it.
    let again = server.ask_until(200, |id| {
        json!({
            "id": id,
            "method": "textDocument/diagnostic",
            "params": { "textDocument": { "uri": main_uri } },
        })
    });
    assert_eq!(
        again["result"]["items"].as_array().map(Vec::len),
        Some(items.len()),
        "the same text has to give the same answer twice: first {report}, then {again}"
    );

    server.request(999, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}

#[test]
fn a_client_can_open_a_file_and_get_diagnostics_a_definition_and_a_hover() {
    let project = Project::new("handshake");
    project.write("widget.h", WIDGET_H);
    project.write("main.cpp", MAIN_CPP);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    // --- initialize -------------------------------------------------------------------------------
    let initialized = server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                // No `textDocument.diagnostic`: this client wants diagnostics **pushed**, which is the half of the
                // diagnostic design that has no request in it.
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );

    let capabilities = &initialized["result"]["capabilities"];
    assert_eq!(capabilities["definitionProvider"], json!(true));
    assert_eq!(capabilities["hoverProvider"], json!(true));
    assert_eq!(
        capabilities["diagnosticProvider"]["workspaceDiagnostics"],
        json!(false),
        "a file's parse errors are the whole answer, so there is nothing a workspace request would add"
    );
    assert!(
        capabilities["textDocumentSync"].is_object(),
        "the document lifecycle is what every other capability needs: {capabilities}"
    );

    server.notify("initialized", json!({}));

    // --- one open document ------------------------------------------------------------------------
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": MAIN_CPP }
        }),
    );

    let reported = server.pull_diagnostics(90, &main_uri);
    assert!(
        !reported.is_empty(),
        "the last class is never closed, so a parse error is expected: {reported:?}"
    );
    assert_eq!(
        reported[0]["severity"],
        json!(1),
        "a parse error is an error, not a warning"
    );
    assert_eq!(
        reported[0]["range"]["start"]["line"],
        json!(6),
        "the error is on the last line: {reported:?}"
    );
    assert!(
        reported[0]["message"]
            .as_str()
            .is_some_and(|message| message.contains(';')),
        "and it is the parser's own message about the missing `;`: {reported:?}"
    );

    // --- definition: the member declared in the included header ------------------------------------
    let location = server.ask_until(100, |id| {
        json!({
            "id": id,
            "method": "textDocument/definition",
            "params": {
                "textDocument": { "uri": main_uri },
                "position": { "line": 4, "character": 6 },  // `w.size`
            },
        })
    });

    let found_uri = location["result"]["uri"]
        .as_str()
        .unwrap_or_else(|| panic!("a definition was expected, got {location}"));
    assert!(
        found_uri.ends_with("widget.h"),
        "`size` is declared in the header: {location}"
    );
    assert_eq!(
        location["result"]["range"]["start"]["line"],
        json!(0),
        "and the range is the name in that file, not the top of it: {location}"
    );
    assert_eq!(location["result"]["range"]["start"]["character"], json!(20));

    // --- definition on the `#include` itself: the header it names -----------------------------------
    // The fourth answer a jump can give, and the one that used to be missing entirely: `#include "widget.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. The cursor is inside the spelling (character 12 is the `d`
    // of `widget.h`), and the range that comes back is the file's first line rather than a point at its start —
    // an editor *selects* a scalar location, and a zero-width range would select nothing.
    let header = server.ask_until(150, |id| {
        json!({
            "id": id,
            "method": "textDocument/definition",
            "params": {
                "textDocument": { "uri": main_uri },
                "position": { "line": 0, "character": 12 },  // inside `"widget.h"`
            },
        })
    });

    let header_uri = header["result"]["uri"]
        .as_str()
        .unwrap_or_else(|| panic!("a header was expected, got {header}"));
    assert!(
        header_uri.ends_with("widget.h"),
        "the include names widget.h: {header}"
    );
    assert_eq!(
        header["result"]["range"]["start"],
        json!({ "line": 0, "character": 0 }),
        "from the top of the header: {header}"
    );
    assert_eq!(
        header["result"]["range"]["end"],
        json!({ "line": 1, "character": 0 }),
        "to the start of the second line, which is where the header's first line ends: {header}"
    );

    // --- hover on the same name: **which file the search found** ------------------------------------
    // The other half of a jump whose target the reader cannot see: the line they wrote names a *spelling*, and a
    // search turns it into one of the thousands of files on this machine's include path. The popup says which.
    let about_the_header = server.ask_until(170, |id| {
        json!({
            "id": id,
            "method": "textDocument/hover",
            "params": {
                "textDocument": { "uri": main_uri },
                "position": { "line": 0, "character": 12 },
            },
        })
    });
    let markdown = about_the_header["result"]["contents"]["value"]
        .as_str()
        .unwrap_or_else(|| panic!("a hover was expected, got {about_the_header}"));
    assert!(
        markdown.contains("#include \"widget.h\""),
        "the line as the file writes it: {markdown}"
    );
    // The path is compared **case-insensitively**, because the session resolves it through the VFS and the
    // temporary directory the fixture lives in is spelled in lower case there on Windows. What is being asserted
    // is that the popup carries the resolved *file*, not the spelling the reader wrote.
    let resolved = markdown.to_lowercase();
    assert!(
        resolved.contains("widget.h") && resolved.contains("cppls-handshake-tests"),
        "and where it resolved to: {markdown}"
    );

    // The `#` is part of the directive rather than of the name, and the analysis answers `null` there — which is
    // the same "nothing to go to" it gave before this round for the *whole* line. Asserted so that the boundary is
    // pinned: a client that sends a ctrl-click on the `#` must not be sent to a file the analysis guessed at.
    let on_the_hash = server.request(
        160,
        "textDocument/definition",
        json!({
            "textDocument": { "uri": main_uri },
            "position": { "line": 0, "character": 0 },
        }),
    );
    assert_eq!(
        on_the_hash["result"],
        Value::Null,
        "the `#` is not the header's name: {on_the_hash}"
    );

    // --- hover: the type of a local, then the declaration of the member ---------------------------
    // The two positions below are `Widget w;` on line 3 and the `size` of `w.size` on line 4.
    let hover = server.ask_until(200, |id| {
        json!({
            "id": id,
            "method": "textDocument/hover",
            "params": {
                "textDocument": { "uri": main_uri },
                "position": { "line": 3, "character": 6 },  // `Widget w;`
            },
        })
    });
    let markdown = hover["result"]["contents"]["value"]
        .as_str()
        .unwrap_or_else(|| panic!("a hover was expected, got {hover}"));
    assert!(
        markdown.contains("struct Widget"),
        "the declaration as the file writes it: {markdown}"
    );
    assert!(markdown.contains("widget.h"), "{markdown}");

    let member = server.ask_until(300, |id| {
        json!({
            "id": id,
            "method": "textDocument/hover",
            "params": {
                "textDocument": { "uri": main_uri },
                "position": { "line": 4, "character": 7 },  // `w.size`
            },
        })
    });
    let markdown = member["result"]["contents"]["value"]
        .as_str()
        .unwrap_or_else(|| panic!("a hover for the member was expected, got {member}"));
    assert!(markdown.contains("size"), "{markdown}");
    assert!(markdown.contains("int"), "its type is shown: {markdown}");

    // --- a hover where there is nothing to say answers null, rather than an empty popup ------------
    let nothing = server.request(
        900,
        "textDocument/hover",
        json!({
            "textDocument": { "uri": main_uri },
            "position": { "line": 1, "character": 0 },  // the blank line
        }),
    );
    assert_eq!(
        nothing["result"],
        Value::Null,
        "there is nothing at the position, and that is what the client is told"
    );

    // --- shutdown ---------------------------------------------------------------------------------
    let shutdown = server.request(901, "shutdown", Value::Null);
    assert_eq!(shutdown["result"], Value::Null);
    server.notify("exit", Value::Null);
    assert!(
        server.wait_for_exit(),
        "the server exits when the client says exit"
    );
}

/// **`shutdown` ends the process even when the client never sends `exit`.**
///
/// The protocol asks for `exit` after the shutdown answer, and a client that sends it gets to see the answer
/// first. A client that only says `shutdown` — and holds the pipe open, the way an editor does — is still a
/// client that expects the process to end: waiting for a notification that will not come is a server an editor
/// has to kill, which is what happened (the wait was thirty seconds, and the process outlived it).
#[test]
fn a_shutdown_ends_the_process_while_the_client_keeps_the_pipe() {
    let project = Project::new("shutdown-without-exit");
    project.write("main.cpp", "int main() { return 0; }\n");

    let mut server = Server::start(project.root());
    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    server.notify("initialized", json!({}));

    // Let the workspace come up, the way a client has been talking to the server for a while before it closes.
    server.pull_diagnostics(90, &uri_of(&project.root().join("main.cpp")));

    let shutdown = server.request(901, "shutdown", Value::Null);
    assert_eq!(shutdown["result"], Value::Null);

    // **No `exit`, and `stdin` stays open** — the server holds it, so only its own code can end the process.
    assert!(
        server.wait_for_exit(),
        "the process must end after shutdown, not wait for an exit notification"
    );
}

/// The project's own `.cppls.toml` is read by the engine and honoured by the **server**.
///
/// The engine's tests prove the file is parsed; what they cannot prove is that a setting in it reaches the layer
/// that acts on it — the one file is parsed once, in the engine, and the server reads the same struct
/// (`Session::project_config`). Hover is the setting with an observable answer: with `hover.enable = false` the
/// same request that answers with a declaration in the test above answers `null`, and nothing else changes.
#[test]
fn a_formatting_request_returns_edits_for_the_whole_file() {
    let project = Project::new("formatting");
    // The file the server must be able to format: two spaces where one belongs, and a line indented with three.
    project.write("main.cpp", "int  x = 1;\n   int y = 2;\n");

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    let initialized = server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": { "textDocument": { "formatting": { "dynamicRegistration": false } } },
        }),
    );
    let capabilities = &initialized["result"]["capabilities"];
    assert_eq!(
        capabilities["documentFormattingProvider"],
        json!(true),
        "the server advertises whole-file formatting: {capabilities}"
    );
    assert_eq!(capabilities["documentRangeFormattingProvider"], json!(true));

    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": {
                "uri": main_uri,
                "languageId": "cpp",
                "version": 1,
                "text": "int  x = 1;\n   int y = 2;\n",
            }
        }),
    );

    let response = server.request(
        2,
        "textDocument/formatting",
        json!({
            "textDocument": { "uri": main_uri },
            "options": { "tabSize": 4, "insertSpaces": true },
        }),
    );

    let edits = response["result"]
        .as_array()
        .unwrap_or_else(|| panic!("edits were expected, got {response}"));
    assert!(
        !edits.is_empty(),
        "the file is not formatted, so there is work: {response}"
    );
    let text = edits
        .iter()
        .filter_map(|edit| edit["newText"].as_str())
        .collect::<String>();
    assert!(
        text.contains("int x = 1;"),
        "the double space between `int` and `x` is closed up: {response}"
    );
    assert!(
        !text.contains("   int y"),
        "and the three spaces before `int y` are gone: {response}"
    );

    // --- the same file, a range that covers only the first line ------------------------------------
    let response = server.request(
        3,
        "textDocument/rangeFormatting",
        json!({
            "textDocument": { "uri": main_uri },
            "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 5 } },
            "options": { "tabSize": 4, "insertSpaces": true },
        }),
    );
    let ranged = response["result"]
        .as_array()
        .unwrap_or_else(|| panic!("a range answer is a list, possibly empty: {response}"));
    assert!(
        ranged.len() <= edits.len(),
        "a range never returns more than the whole file did: {response}"
    );
    // **A range must not touch a line outside it**: line 1 (`int y`) is not in the requested range, so no edit
    // may carry its text.
    let ranged_text = ranged
        .iter()
        .filter_map(|edit| edit["newText"].as_str())
        .collect::<String>();
    assert!(
        !ranged_text.contains("int y"),
        "the range formatted only line 0: {ranged_text:?}"
    );

    // --- willSaveWaitUntil: the edits the client applies before saving --------------------------------------
    let response = server.request(
        5,
        "textDocument/willSaveWaitUntil",
        json!({
            "textDocument": { "uri": main_uri },
            "reason": 1,
        }),
    );
    let edits = response["result"]
        .as_array()
        .unwrap_or_else(|| panic!("the save-time edits are a list: {response}"));
    assert!(
        !edits.is_empty(),
        "the file is still unformatted, so saving must offer the edits: {response}"
    );
}

#[test]
fn a_project_configuration_reaches_the_servers_behaviour() {
    let project = Project::new("configured");
    project.write("widget.h", WIDGET_H);
    project.write("main.cpp", MAIN_CPP);
    project.write(".cppls.toml", "[hover]\nenable = false\n");

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": MAIN_CPP }
        }),
    );

    // The same position the test above gets a declaration from — `Widget w;` on line 3.
    let hover = server.request(
        2,
        "textDocument/hover",
        json!({
            "textDocument": { "uri": main_uri },
            "position": { "line": 3, "character": 6 },
        }),
    );

    assert_eq!(
        hover["result"],
        Value::Null,
        "the project turned the popup off, and the server read the project's file to find that out: {hover}"
    );

    let shutdown = server.request(3, "shutdown", Value::Null);
    assert_eq!(shutdown["result"], Value::Null);
    server.notify("exit", Value::Null);
    assert!(server.wait_for_exit());
}

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

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

        Project { root }
    }

    fn root(&self) -> &Path {
        &self.root
    }

    fn write(&self, name: &str, text: &str) {
        std::fs::write(self.root.join(name), text).expect("the fixture writes");
    }
}

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

fn uri_of(path: &Path) -> String {
    // A client's own conversion, deliberately not the server's: a test that reused `util::uri` would agree with a
    // bug in it. Only what a temp path can hold is escaped (a space, which `%TEMP%` on Windows may have).
    let text = path
        .to_string_lossy()
        .replace('\\', "/")
        .replace(' ', "%20");
    format!("file:///{}", text.trim_start_matches('/'))
}

/// **Where a cursor at the end of a needle is**, as the protocol's line and character.
///
/// The offset *past* the needle — `full.` puts the cursor after the operator, which is where a reader who has just
/// typed it is. A test that states a position by hand states it wrong sooner or later, and the failure is silent:
/// the request still gets an answer, about a position nobody is looking at. Counting the line(s) and characters of
/// the fixture is a line of code and cannot drift away from the text it is about.
fn position_of(source: &str, needle: &str) -> (u32, u32) {
    let at = source
        .find(needle)
        .unwrap_or_else(|| panic!("{needle:?} is not in the fixture"))
        + needle.len();

    let before = &source[..at];
    let line = before.matches('\n').count();
    let character = before
        .rsplit('\n')
        .next()
        .expect("rsplit always yields one piece")
        .chars()
        .count();

    (line as u32, character as u32)
}

/// The server, as a client sees it: a process, a pipe, and the messages it sent.
struct Server {
    child: Child,
    stdin: ChildStdin,
    messages: Receiver<Value>,
    /// What the server logged, kept so that a failure says *why* rather than only that.
    log: Arc<Mutex<String>>,
}

impl Server {
    fn start(root: &Path) -> Server {
        // **The server's own level and log path, under the test's control.** Both are command-line flags
        // (`--log-level`, default `info`; `--log-path`, default `none`) rather than `RUST_LOG`, so a test could not
        // ask the server to say what it did — and the first attempt to diagnose the handshake failures ended exactly
        // there: the trace line exists in the handler and the level dropped it. Run this suite with
        // `CPPLS_TEST_LOG_LEVEL=debug` and `CPPLS_TEST_LOG_PATH=<file>` when a request has to be watched.
        let mut command = Command::new(env!("CARGO_BIN_EXE_cpp_ls"));
        command
            .arg("--log-path")
            .arg(std::env::var("CPPLS_TEST_LOG_PATH").unwrap_or_else(|_| "none".to_string()));
        if let Ok(level) = std::env::var("CPPLS_TEST_LOG_LEVEL") {
            command.arg("--log-level").arg(level);
        }
        let mut child = command
            .current_dir(root)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .expect("the server starts");

        let stdin = child.stdin.take().expect("stdin is piped");
        let stdout = child.stdout.take().expect("stdout is piped");
        let stderr = child.stderr.take().expect("stderr is piped");

        let (tx, messages) = channel();
        std::thread::spawn(move || read_messages(stdout, tx));

        // The log goes to stderr; if nobody reads it a full pipe would block the server mid-test, and if nobody
        // *keeps* it a failing test says only that the server did not answer.
        let log = Arc::new(Mutex::new(String::new()));
        let sink = log.clone();
        std::thread::spawn(move || {
            let mut reader = BufReader::new(stderr);
            let mut line = String::new();
            while reader.read_line(&mut line).unwrap_or(0) > 0 {
                sink.lock()
                    .expect("the log is not poisoned")
                    .push_str(&line);
                line.clear();
            }
        });

        Server {
            child,
            stdin,
            messages,
            log,
        }
    }

    fn send(&mut self, message: Value) {
        let body = serde_json::to_string(&message).expect("the message serializes");
        write!(self.stdin, "Content-Length: {}\r\n\r\n{body}", body.len())
            .expect("the message is written");
        self.stdin.flush().expect("the message is flushed");
    }

    fn notify(&mut self, method: &str, params: Value) {
        self.send(json!({ "jsonrpc": "2.0", "method": method, "params": params }));
    }

    /// Send a request and wait for its response, answering anything the server asks on the way.
    fn request(&mut self, id: i64, method: &str, params: Value) -> Value {
        self.send(json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params }));
        self.wait_for(|message| message["id"] == json!(id))
    }

    /// Send a request until its answer is not `null`, or give up.
    ///
    /// What the lazy index needs: a query that arrives before the file has been read answers "not yet", and the
    /// test's job is to assert the *answer*, not the schedule. Each attempt gets its own id, so a retry can never
    /// be confused with the answer to the attempt before it.
    fn ask_until(&mut self, first_id: i64, build: impl Fn(i64) -> Value) -> Value {
        let deadline = Instant::now() + TIMEOUT;
        let mut id = first_id;

        loop {
            let request = build(id);
            let method = request["method"]
                .as_str()
                .expect("the closure builds a request")
                .to_string();
            let response = self.request(id, &method, request["params"].clone());

            if let Some(error) = response.get("error") {
                panic!("the server answered with an error: {error}");
            }

            if !response["result"].is_null() {
                return response;
            }

            if Instant::now() >= deadline {
                panic!("no answer within {TIMEOUT:?}, only `null`: {response}");
            }

            id += 1;
            std::thread::sleep(Duration::from_millis(50));
        }
    }

    /// **Ask for a file's diagnostics, the way a client does** — `textDocument/diagnostic`, the pull half.
    ///
    /// The server used to publish these; it does not any more, and every test that used to wait for a
    /// `publishDiagnostics` notification asks here instead. That is not a test convenience: it is the same request a
    /// client makes, and going through it is what makes these tests exercise the path a user's editor takes.
    ///
    /// `first_id` is the caller's, so two pulls in one test cannot be confused with each other. The answer must be a
    /// **report** — the `items` array — because a `null` result is what the handler used to return and no client can
    /// act on it.
    fn pull_diagnostics(&mut self, first_id: i64, uri: &str) -> Vec<Value> {
        let report = self.ask_until(first_id, |id| {
            json!({
                "id": id,
                "method": "textDocument/diagnostic",
                "params": { "textDocument": { "uri": uri } },
            })
        });
        report["result"]["items"]
            .as_array()
            .unwrap_or_else(|| {
                panic!("a pull request is answered with a report, not `null`: {report}")
            })
            .clone()
    }

    /// [`Server::ask_until`] for a request whose answer can arrive **worth having but not yet complete**: keeps
    /// asking until the closure accepts one.
    ///
    /// A completion is the request that needs this. Its answer before the project has been read is an **empty
    /// list** — not `null`, which is why [`Server::ask_until`] would take it — and the protocol's own answer to
    /// that is `isIncomplete: true`, which tells the client to ask again as the user types. This is that loop, so
    /// a test asserts what a well-behaved client would eventually see rather than what a fast one happens to get.
    fn ask_until_it(
        &mut self,
        first_id: i64,
        build: impl Fn(i64) -> Value,
        accept: impl Fn(&Value) -> bool,
    ) -> Value {
        self.ask_until_it_within(first_id, TIMEOUT, build, accept)
    }

    /// [`Server::ask_until_it`] with the caller's own deadline, for a test whose subject is genuinely slow.
    fn ask_until_it_within(
        &mut self,
        first_id: i64,
        within: Duration,
        build: impl Fn(i64) -> Value,
        accept: impl Fn(&Value) -> bool,
    ) -> Value {
        let deadline = Instant::now() + within;
        let mut id = first_id;

        loop {
            let request = build(id);
            let method = request["method"]
                .as_str()
                .expect("the closure builds a request")
                .to_string();
            let response = self.request(id, &method, request["params"].clone());

            if let Some(error) = response.get("error") {
                panic!("the server answered with an error: {error}");
            }

            if accept(&response) {
                return response;
            }

            if Instant::now() >= deadline {
                panic!(
                    "no answer the test accepts within {within:?}; the last one was: {response}"
                );
            }

            id += 1;
            std::thread::sleep(Duration::from_millis(50));
        }
    }

    /// Wait for a message the closure accepts, answering the server's own requests while waiting.
    fn wait_for(&mut self, accept: impl Fn(&Value) -> bool) -> Value {
        let deadline = Instant::now() + TIMEOUT;

        loop {
            let remaining = deadline
                .checked_duration_since(Instant::now())
                .unwrap_or_else(|| panic!("the server did not answer within {TIMEOUT:?}"));

            let message = match self.messages.recv_timeout(remaining) {
                Ok(message) => message,
                Err(RecvTimeoutError::Timeout) => {
                    panic!("the server did not answer within {TIMEOUT:?}")
                }
                Err(RecvTimeoutError::Disconnected) => panic!("the server closed its stdout"),
            };

            // A request *from* the server: `workspace/configuration`, `client/registerCapability`, a progress
            // token. Answering is part of being a client, and a test that did not would leave the server waiting.
            if message.get("method").is_some() && message.get("id").is_some() {
                self.answer(&message);
                continue;
            }

            if accept(&message) {
                return message;
            }
        }
    }

    /// Answer a server→client request the way a client would.
    fn answer(&mut self, request: &Value) {
        let id = request["id"].clone();
        let method = request["method"].as_str().unwrap_or_default();
        let result = match method {
            // One `null` per requested item: "the user has configured nothing", which is what an unconfigured
            // client says and what the server's own defaults are for.
            "workspace/configuration" => json!([Value::Null]),
            _ => Value::Null,
        };

        self.send(json!({ "jsonrpc": "2.0", "id": id, "result": result }));
    }

    fn wait_for_exit(&mut self) -> bool {
        let deadline = Instant::now() + Duration::from_secs(10);

        while Instant::now() < deadline {
            match self.child.try_wait() {
                Ok(Some(_)) => return true,
                Ok(None) => std::thread::sleep(Duration::from_millis(20)),
                Err(_) => return false,
            }
        }

        false
    }
}

impl Drop for Server {
    fn drop(&mut self) {
        // Printed on the way out, which includes the way out a failing assertion takes: the server's log is the
        // first thing anyone debugging this test wants, and a panicking test would otherwise lose it.
        let log = self.log.lock().expect("the log is not poisoned");
        if !log.trim().is_empty() {
            eprintln!("--- the server logged:\n{log}");
        }
        drop(log);

        let _ = self.child.kill();
        let _ = self.child.wait();
    }
}

/// Read LSP frames off the server's stdout and hand each message to the test.
fn read_messages(stdout: impl Read, tx: std::sync::mpsc::Sender<Value>) {
    let mut reader = BufReader::new(stdout);

    loop {
        let mut length = None;
        loop {
            let mut header = String::new();
            match reader.read_line(&mut header) {
                Ok(0) => return,
                Ok(_) => {}
                Err(_) => return,
            }

            let header = header.trim_end();
            if header.is_empty() {
                break;
            }

            if let Some(value) = header.strip_prefix("Content-Length: ") {
                length = value.parse::<usize>().ok();
            }
        }

        let Some(length) = length else {
            return;
        };

        let mut body = vec![0u8; length];
        if reader.read_exact(&mut body).is_err() {
            return;
        }

        let Ok(message) = serde_json::from_slice::<Value>(&body) else {
            return;
        };

        if tx.send(message).is_err() {
            return;
        }
    }
}

/// The macro-declared type: the declaration is inside `DECLARE_HANDLE`'s replacement list, and `HWND h;` is a use
/// of the name it makes.
const HANDLE_H: &str = "#define DECLARE_HANDLE(name) struct name##__ { int unused; }; \
                        typedef struct name##__ *name\n";
const API_H: &str = "#include \"handle.h\"\nDECLARE_HANDLE(HWND);\n";
const API_CPP: &str = "#include \"api.h\"\nHWND h;\n";

/// **A declaration a macro makes is a declaration this server answers for.**
///
/// `DECLARE_HANDLE(HWND)` declares `HWND__` and `HWND` to a compiler and *nothing* to a reader of `api.cpp`: the
/// declaration is inside the replacement list, in a header the file includes. The index has it only because the
/// session reads the file a **second way** — cooked, through the translation unit that brings the macro in
/// (`Session::cook`, run by the indexing loop when its queue drains), with every range mapped back into the file.
///
/// Over the wire the difference is one jump that works, and the assertion is deliberately about the *range* rather
/// than only about the file: a definition of `HWND` that the raw reading had found would point at the text
/// `DECLARE_HANDLE(HWND)` writes — the argument of the invocation — while the cooked reading reports the
/// declaration at the **invocation** it came out of, which is the place a reader can act on.
#[test]
fn a_declaration_a_macro_makes_is_found_over_the_wire() {
    let project = Project::new("macro-declared");
    project.write("handle.h", HANDLE_H);
    project.write("api.h", API_H);
    project.write("main.cpp", API_CPP);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": API_CPP }
        }),
    );

    // `HWND h;` is the second line, and the name starts it.
    let location = server.ask_until(100, |id| {
        json!({
            "id": id,
            "method": "textDocument/definition",
            "params": {
                "textDocument": { "uri": main_uri },
                "position": { "line": 1, "character": 1 },
            },
        })
    });

    let found = &location["result"];
    let found_uri = found["uri"]
        .as_str()
        .unwrap_or_else(|| panic!("a definition was expected, got {location}"));
    assert!(
        found_uri.ends_with("api.h"),
        "the declaration the macro made belongs to the file that invoked it, which nobody opened: {location}"
    );
    assert_eq!(
        found["range"]["start"]["line"],
        json!(1),
        "and it is reported at the invocation: {location}"
    );

    server.request(999, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}

/// The file whose *text* has an error in a branch the preprocessor removes: `OFF` is 0, so the unclosed class never
/// reaches a compiler — while the bytes are right there in the buffer.
const BRANCH_CPP: &str = "#include \"cfg.h\"\n#if OFF\nstruct Unclosed { int x;\n#endif\nint ok;\n";
const CFG_H: &str = "#define OFF 0\n";

/// **A branch nobody takes is answered as clean.**
///
/// The two readings disagree about this file, and that disagreement is the reason the diagnostics channel reads the
/// cooked one: the raw reading reports the unclosed class — correctly, the *text* says so — and a compiler never
/// sees that branch. A server that answered from the raw reading would put a red squiggle on code that is not
/// compiled, which is the false positive the whole second reading exists to remove.
///
/// **Pull makes this the first answer rather than a later one.** The handler reads and cooks the file before it
/// queries, so there is no window in which the raw answer could reach a client — which is what the push path had to
/// live with, and what made this test above say "the assertion is about the *last* thing the client is told".
#[test]
fn a_branch_nobody_takes_is_answered_as_clean() {
    let project = Project::new("cooked-diagnostics");
    project.write("cfg.h", CFG_H);
    project.write("main.cpp", BRANCH_CPP);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                // No `textDocument.diagnostic`: this client wants diagnostics **pushed**, which is the half that has
                // no request in it — and the half a re-publish after the drain has to work for.
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": BRANCH_CPP }
        }),
    );

    let clean = server.pull_diagnostics(90, &main_uri);
    assert!(
        clean.is_empty(),
        "the branch is not compiled, so there is nothing to report: {clean:?}"
    );

    // **The falsification lives one layer down**, where the same fixture is read both ways:
    // `cpp_code_analysis::session::tests::a_branch_nobody_takes_reports_nothing_once_the_file_is_cooked` asserts
    // that this file's *raw* reading reports exactly that error and its cooked reading reports nothing. Without it
    // this test would also pass on a file that simply has no error in it.

    server.request(999, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}

/// **An error typed into an open file is published, and the edit has not been cooked yet.**
///
/// Reported: `std::cout << middleName << std::endl` with no `;` sat there with no diagnostic, however long the user
/// waited — and this is the case the older diagnostics test does not reach, because it opens a file whose text is
/// already on disk.
///
/// What makes it different is that **an edit drops the cooked reading**, and a diagnostic is answered from that
/// reading. So the pass that runs after the typing stops found no reading at all, `diagnose_file` answered `None`,
/// and the service logged *"nothing to diagnose"* and published nothing. The reading comes back when the index pump
/// reaches the file, and the pump works through its queue rather than the editor.
///
/// Measured on the fixture, at the analysis layer:
///
/// ```text
/// before the edit:       Some(1)
/// right after the edit:  None       ← what was being published as nothing
/// after re-indexing:     Some(1)
/// ```
///
/// So this opens a file that is **clean**, edits it into having a missing `;`, and requires the client to be told
/// about it. A server that waits for a re-read fails here and passes the fixture whose text was already on disk.
#[test]
fn an_error_typed_into_an_open_file_is_answered() {
    let project = Project::new("diagnostics-after-an-edit");
    project.write("main.cpp", CLEAN_CPP);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": CLEAN_CPP }
        }),
    );

    // **The edit**, as a client sends it: the whole text, one version later. `EDITED_CPP` differs from `CLEAN_CPP` by
    // a missing `;` and nothing else, so an error reported here is about this edit.
    server.notify(
        "textDocument/didChange",
        json!({
            "textDocument": { "uri": main_uri, "version": 2 },
            "contentChanges": [{ "text": EDITED_CPP }],
        }),
    );

    let diagnostics = server.pull_diagnostics(300, &main_uri);
    assert!(
        diagnostics.iter().any(|diagnostic| diagnostic["message"]
            .as_str()
            .is_some_and(|message| message.contains(';'))),
        "the missing `;` is the only difference from the clean file: {diagnostics:?}"
    );

    server.request(999, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}

/// **A diagnostic about text that is no longer there must go away on the next pull.**
///
/// Reported from an editor, with a screenshot: the file had been typed into and corrected, and it was completely
/// correct — and the Problems panel still showed the two findings from the moment in between (`missing-return` on
/// `int main() {` and `expected ';' after expression` on the `return 0;` line). Editing again did not always clear
/// them. That is the worst failure this channel has, because a reader has no way to tell a stale squiggle from a
/// real one, and every later finding becomes untrustworthy.
///
/// The cause was not a `resultId` (this server sends `resultId: None` and always a **full** report). It was the
/// handler's own rule: `document_diagnostic::the_report` **repeated** the last report when the analysis had no answer
/// and **unioned** it with the current one when the checks were withheld. Both were written to stop diagnostics
/// flashing while the index filled, and both keep a finding about deleted text alive indefinitely.
///
/// The sequence is the reported one, in order: the file is clean, an edit breaks it, the edit is taken back.
#[test]
fn a_diagnostic_about_deleted_text_is_gone_by_the_next_pull() {
    let project = Project::new("diagnostics-clear-after-a-fix");
    project.write("main.cpp", CLEAN_CPP);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": CLEAN_CPP }
        }),
    );

    // 1. The clean file, pulled once so the server has a report to be stale about.
    server.pull_diagnostics(100, &main_uri);

    // 2. The edit that breaks it — one `;` short.
    server.notify(
        "textDocument/didChange",
        json!({
            "textDocument": { "uri": main_uri, "version": 2 },
            "contentChanges": [{ "text": EDITED_CPP }],
        }),
    );
    let broken = server.pull_diagnostics(200, &main_uri);
    assert!(
        broken
            .iter()
            .any(|diagnostic| diagnostic["message"].is_string()),
        "the missing `;` is found: {broken:?}"
    );

    // 3. The fix — the file the session started with, byte for byte.
    server.notify(
        "textDocument/didChange",
        json!({
            "textDocument": { "uri": main_uri, "version": 3 },
            "contentChanges": [{ "text": CLEAN_CPP }],
        }),
    );

    // **What a reader must see: no diagnostic about text that is gone.** A file this small has nothing else to
    // report — no includes, no checks that can fire — so the whole list has to be empty.
    let fixed = server.pull_diagnostics(300, &main_uri);
    assert!(
        fixed.is_empty(),
        "the file is byte-for-byte the one that was clean before the edit, so nothing may be reported: {fixed:?}"
    );

    server.request(999, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}

/// **A pull while the index is still busy must not answer with a finding about text that is gone.**
///
/// The same reported sequence as above, on a project whose index **does not settle** when the pull arrives: the
/// handler decides `settled` from `Session::pending_work() == 0`, and a project of eighty headers is still being
/// read. That state is not exotic — it is what a real project looks like for its first seconds and, on a big one,
/// for minutes — and in it the handler used to answer with the **union** of the current findings and the last
/// report it had sent. A finding about a `;` the reader deleted an edit ago was in the union, and nothing removed
/// it: the client had no reason to ask again, because it had just asked.
///
/// So this is the same bug as the test above, at the state that makes it *permanent* rather than momentary. The
/// two tests are kept apart because they can fail independently: one is the report's rule, the other is when the
/// rule is reached.
#[test]
fn a_finding_about_deleted_text_does_not_survive_a_busy_index() {
    let project = Project::new("diagnostics-while-busy");

    // **Eighty headers in a chain**, so the session has work left when the pull arrives — `PREPARE_INDEX_SLICE` is
    // 24 files, and the pull's own slice drains a quarter of it. Each header includes the next, so main.cpp's
    // closure is the whole chain.
    for index in 0..80 {
        let next = if index + 1 < 80 {
            format!("#include \"h{}.h\"\n", index + 1)
        } else {
            String::new()
        };
        project.write(
            &format!("h{index}.h"),
            &format!("#pragma once\n{next}struct S{index} {{ int f; }};\n"),
        );
    }
    let clean = "#include \"h0.h\"\nint main() { return 0; }\n";
    let broken = "#include \"h0.h\"\nint main() { return 0 }\n";
    project.write("main.cpp", clean);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": clean }
        }),
    );
    server.pull_diagnostics(100, &main_uri);

    server.notify(
        "textDocument/didChange",
        json!({
            "textDocument": { "uri": main_uri, "version": 2 },
            "contentChanges": [{ "text": broken }],
        }),
    );
    let found = server.pull_diagnostics(200, &main_uri);
    assert!(
        found
            .iter()
            .any(|diagnostic| diagnostic["message"].is_string()),
        "the missing `;` is a parse error: {found:?}"
    );

    // The fix, as the editor sends it — the file the session opened, byte for byte.
    server.notify(
        "textDocument/didChange",
        json!({
            "textDocument": { "uri": main_uri, "version": 3 },
            "contentChanges": [{ "text": clean }],
        }),
    );
    let fixed = server.pull_diagnostics(300, &main_uri);
    assert!(
        fixed.is_empty(),
        "the `;` is back and the file is the one that was clean before the edit, so nothing may be reported: \
         {fixed:?}"
    );

    server.request(999, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}

/// The clean file [`an_error_typed_into_an_open_file_is_answered`] opens, and the same file one `;` short.
const CLEAN_CPP: &str = "int g();\nstruct Name {\n    int middleName;\n    void print(int i) {\n        \
                         middleName = i;\n    }\n};\n";
const EDITED_CPP: &str = "int g();\nstruct Name {\n    int middleName;\n    void print(int i) {\n        \
                          middleName = i\n    }\n};\n";

/// **The reported file is answered — and the answer is an empty list, which is correct.**
///
/// Reported twice: first a `return 0` with no `;` produced no diagnostic, and after that was fixed the file *with*
/// its semicolons still produced none. The two have different causes, and the second is not a defect:
///
/// ```text
/// the file parses                 so `syntax-error` is absent — a fact, because the parser defect is fixed
/// the only check that fires      `IncludeNotFound`, which is about the machine's include paths
/// on a machine that has them     nothing at all
/// ```
///
/// Logged from a run of this fixture, with the probes that established it:
///
/// ```text
/// COOK PROBE: summary=true cooked=true pending=0
/// READ PROBE: held=true key=Some("…/main.cpp") checks=Some((0, 0, Cooked))
/// ```
///
/// `checks=0` with the reading **cooked** and the file **held** is the whole answer: the channel is working and the
/// file is clean. So this test asserts the thing that is actually true and was worth doubting — that the server
/// **publishes**, that the publish is stamped with the document's version, and that the answer for this text is the
/// empty list rather than no message at all. A server that never reached the client, and one that answered "clean",
/// are the two states the report could not tell apart, and only the first is a bug.
///
/// What the file *does* deserve — `full.size();` discarding its result three times — is a rule this layer does not
/// have. `cpp_code_analysis`'s `the_reported_file_reports_only_its_unresolved_includes` records that.
#[test]
fn the_reported_file_is_answered() {
    let project = Project::new("reported-file");
    project.write("main.cpp", REPORTED_CPP);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": REPORTED_CPP }
        }),
    );

    let diagnostics = server.pull_diagnostics(90, &main_uri);
    eprintln!(
        "the server answered with {} diagnostic(s): {diagnostics:?}",
        diagnostics.len()
    );
    assert!(
        diagnostics
            .iter()
            .all(|diagnostic| diagnostic["code"] != json!("syntax-error")),
        "the file parses, and `return` reporting a missing `;` is the defect this fixture was built from: \
         {diagnostics:?}"
    );

    server.request(999, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}

/// The reported file, verbatim: the includes it does not write are part of the report.
const REPORTED_CPP: &str = r#"#include <iostream>
#include <string>
#include <cstdio>
int main() {
    int a = 1, b = 2;
    int sum = a + b;
    std::cout << "The sum of " << a << " and " << b << " is: " << sum << std::endl;
    std::string full;
    std::cout << "Full name: " << full << std::endl;
    std::cout << "hello world " << std::endl;
    full.size();
    full.length();
    full.size();
    printf("Full name Length: %zu\n", full.size());
    // printf("Full name Length using length(): %zu\n", full.length());
    return 0;
}
"#;

/// The namespace is opened by a macro in a header the open file includes. **The raw reading handles this one** —
/// an indexer given the closure's macro bodies reads `BEGIN_NS` as `namespace one {`, which is what the shape rules
/// exist for — so this fixture is about the member question rather than about the second reading.
const NAMESPACE_H: &str = "#define BEGIN_NS namespace one {\n#define END_NS }\n";
const NAMESPACED_WIDGET_H: &str =
    "#include \"namespace.h\"\nBEGIN_NS struct Widget { int size; }; END_NS\n";

/// The fixture that **needs** the second reading: a macro that declares something. `api.h`'s own text has a call
/// where the struct and the typedef are, and no shape rule invents a declaration out of a call.
const HWND_CPP: &str = "#include \"api.h\"\nvoid f() {\n    HWND\n}\n";

/// The cursor is after a `.` — the question that needs a **type**, made interesting by the spelling: `w`'s type is
/// written `one::Widget`.
const MEMBER_CPP: &str = "#include \"widget.h\"\nvoid f() {\n    one::Widget w;\n    w.\n}\n";

/// **A name only the cooked reading declares is offered.**
///
/// `DECLARE_HANDLE(HWND)` declares `HWND__` and `HWND` to a compiler and *nothing* to a reader of `api.h`: the
/// declaration is the replacement list. So a completion in `main.cpp` that offers `HWND__` is one this server can
/// give only because the file it is declared in was read a **second** way — and the falsification (excluding the
/// cooked declarations from the index) turns this test red, which is what makes it evidence rather than a fixture
/// that happens to work.
///
/// The **edit** is asserted as well as the label: the cursor is inside a half-written name, so what comes back is
/// the range of that name to replace, not a point to insert at.
#[test]
fn a_name_only_the_cooked_reading_declares_is_offered_over_the_wire() {
    let project = Project::new("completion-macro-declared");
    project.write("handle.h", HANDLE_H);
    project.write("api.h", API_H);
    project.write("main.cpp", HWND_CPP);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    let capabilities = server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    assert!(
        capabilities["result"]["capabilities"]["completionProvider"].is_object(),
        "the client is told the server completes: {capabilities}"
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": HWND_CPP }
        }),
    );

    // Line 2 is `    HWND` — the cursor is at its end. Asked again until the list holds `HWND__`, because a
    // completion answered before the project has been read is an empty list that says `isIncomplete`.
    let answer = server.ask_until_it(
        100,
        |id| {
            json!({
                "id": id,
                "method": "textDocument/completion",
                "params": {
                    "textDocument": { "uri": main_uri },
                    "position": { "line": 2, "character": 8 },
                },
            })
        },
        |response| {
            response["result"]["items"]
                .as_array()
                .is_some_and(|items| items.iter().any(|item| item["label"] == json!("HWND__")))
        },
    );

    let items = answer["result"]["items"]
        .as_array()
        .unwrap_or_else(|| panic!("a completion list was expected, got {answer}"));
    assert!(
        items.iter().any(|item| item["label"] == json!("HWND")),
        "and the typedef the same macro made is offered beside it: {answer}"
    );

    let generated = items
        .iter()
        .find(|item| item["label"] == json!("HWND__"))
        .expect("the closure accepted this");
    assert_eq!(generated["kind"], json!(7), "a class: {generated}");
    assert_eq!(
        generated["textEdit"]["range"]["start"],
        json!({ "line": 2, "character": 4 }),
        "the edit replaces the half-written name from where it starts: {generated}"
    );
    assert_eq!(
        generated["textEdit"]["range"]["end"],
        json!({ "line": 2, "character": 8 }),
        "…to where the cursor is: {generated}"
    );
    assert_eq!(
        generated["textEdit"]["newText"],
        json!("HWND__"),
        "{generated}"
    );

    server.request(999, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}

/// The `std::string` fixture: a standard-library type from a header, and a `.` where the member list belongs.
///
/// Written the way a reader does — `#include <string>`, a declaration, then the operator — so that the test covers
/// the chain and not the completion layer alone: the header has to be **found** on the search path, its declarations
/// have to be **indexed**, and `std::string` has to resolve before there is a member list to collapse.
const STD_STRING_CPP: &str = "\
#include <string>
int main() {
    std::string full;
    full.
}
";

/// **The other query, over the wire: after a `.`, what the object's type has.**
///
/// `w.` asks for the members of `w`'s type, and the type is written `one::Widget` — a qualified spelling the lookup
/// has to follow before the class body can be read at all. The dependency on the second reading here is **not** the
/// point of the test (the raw reading resolves `one::Widget` too, since a namespace-opening macro is a shape the
/// rules already handle — see the fixture's note); what it covers is the dispatch itself: a cursor after a dot goes
/// to the member query, its answer arrives as members with the range a client replaces, and the file-scope names
/// are not offered beside them.
#[test]
fn a_members_members_are_offered_over_the_wire() {
    let project = Project::new("completion-member");
    project.write("namespace.h", NAMESPACE_H);
    project.write("widget.h", NAMESPACED_WIDGET_H);
    project.write("main.cpp", MEMBER_CPP);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": MEMBER_CPP }
        }),
    );

    // Line 3 is `    w.` — the cursor is just past the dot; asked again until the list holds `size`, for the reason
    // the qualified test gives.
    let answer = server.ask_until_it(
        100,
        |id| {
            json!({
                "id": id,
                "method": "textDocument/completion",
                "params": {
                    "textDocument": { "uri": main_uri },
                    "position": { "line": 3, "character": 6 },
                },
            })
        },
        |response| {
            response["result"]["items"]
                .as_array()
                .is_some_and(|items| items.iter().any(|item| item["label"] == json!("size")))
        },
    );

    let items = answer["result"]["items"]
        .as_array()
        .unwrap_or_else(|| panic!("a completion list was expected, got {answer}"));
    let size = items
        .iter()
        .find(|item| item["label"] == json!("size"))
        .unwrap_or_else(|| panic!("`Widget` has a `size` member: {answer}"));
    assert_eq!(
        size["kind"],
        json!(5),
        "a **field** rather than a variable, because it is reached through an object — the completion layer \
         distinguishes the two positions, and a client draws them with different icons: {size}"
    );
    // **The line's second column is not in the list**, and that is the design rather than an omission: a type or a
    // parameter list per item is the largest part of a completion answer, and a client draws a few dozen rows of it.
    // The protocol's answer is `completionItem/resolve`, sent for the one item a user is looking at — so this asks
    // for it, exactly as a client does, and checks that it comes back.
    assert_eq!(
        size["detail"],
        Value::Null,
        "the detail is left for `completionItem/resolve`: {size}"
    );
    let resolved = server.request(4, "completionItem/resolve", size.clone());
    assert_eq!(
        resolved["result"]["detail"],
        json!("int"),
        "and resolve supplies the type the declaration was written with: {resolved}"
    );
    assert_eq!(
        resolved["result"]["labelDetails"]["detail"],
        json!("  int"),
        "as the label's second half too, which is where 3.17 draws it: {resolved}"
    );
    assert_eq!(
        size["textEdit"]["range"]["start"],
        json!({ "line": 3, "character": 6 }),
        "the edit is an empty range just past the dot: {size}"
    );

    server.request(999, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}

/// **A `.` on a `std::string` offers the standard library's members, once each.**
///
/// The case a user reported as "补全依然存在明显错误": the popup after `full.` was a list of file-scope names —
/// `printf`, `full`, `myName`, `sum`, `main` — plus keywords, which is what a client is shown when the member
/// question has no answer. Two separate faults can produce that shape, and this test pins both:
///
/// * **the members are found at all**, through `#include <string>` and the type's declaration in a header the
///   session had to index — the whole chain has to work for `std::string` to resolve;
/// * **each spelling appears once.** MSVC's `basic_string` declares `replace` eleven times and `insert` nine, and
///   the list used to carry every one of them: 119 rows of which 64 shared a label with another row. A list is
///   something a reader picks from, so eleven rows reading `replace` are one choice offered eleven times — and a
///   client that lays out 119 rows with duplicated labels is what "the popup looks broken" means.
///
/// It is an end-to-end test rather than a unit one because the failure was a *chain*: the fix could be right in the
/// completion layer and the answer still wrong if the index never resolved `<string>`.
///
/// # `#[ignore]`, and why it is not a disabled test
///
/// It is **too slow for the debug profile**: the fixture's one `#include <string>` is a closure of thousands of
/// MSVC headers, which the index reads before it can answer, and a debug build does that in minutes rather than in
/// the sixteen seconds a release build takes. The harness's own deadline is therefore unreachable in a debug run
/// — and a test that fails for a *build profile* teaches nothing about the code, which is the one thing a test
/// must not do.
///
/// It runs in release, and that is how it was written and verified:
///
/// ```text
/// cargo test --release -p cpp_ls --test handshake -- --ignored a_standard_library
/// ```
///
/// What covers the same ground in a debug run: `cpp_code_analysis/tests/completion.rs`'s
/// `a_member_position_offers_the_members_with_their_distinctions` (the member list and its kinds, from a fixture
/// with no standard library in it) and the probe, which is the instrument this was measured with.
#[test]
#[ignore = "needs the release profile: the standard library closure takes minutes to index in debug"]
fn a_standard_library_member_list_has_each_spelling_once() {
    let project = Project::new("completion-std-string");
    project.write("main.cpp", STD_STRING_CPP);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": STD_STRING_CPP }
        }),
    );

    // **The position of the operator, computed from the fixture** rather than counted by hand.
    //
    // This test was written with the position hard-coded twice and wrong twice, and the failure is invisible: an
    // off-by-one lands on the newline (still a name position, so the answer looks like "the members were not
    // found") or on the closing brace (still an answer about a position nobody is looking at). A test whose
    // subject is *where* the cursor is cannot afford to state the where by hand.
    let (line, character) = position_of(STD_STRING_CPP, "full.");
    assert_eq!(
        (line, character),
        (3, 9),
        "the operator ends the fourth line and the cursor is just past it — written out here once, so that a \
         fixture edited above this line fails loudly instead of silently asking about the wrong place"
    );

    // Asked until the list holds `append`, because the standard library's closure is thousands of files and the
    // index is still reading when the first request arrives.
    let answer = server.ask_until_it_within(
        100,
        STD_LIBRARY_TIMEOUT,
        |id| {
            json!({
                "id": id,
                "method": "textDocument/completion",
                "params": {
                    "textDocument": { "uri": main_uri },
                    "position": { "line": line, "character": character },
                },
            })
        },
        |response| {
            response["result"]["items"]
                .as_array()
                .is_some_and(|items| items.iter().any(|item| item["label"] == json!("append")))
        },
    );

    let items = answer["result"]["items"]
        .as_array()
        .unwrap_or_else(|| panic!("a completion list was expected, got {answer}"));

    let labels: Vec<&str> = items
        .iter()
        .filter_map(|item| item["label"].as_str())
        .collect();

    assert!(
        labels.contains(&"append") && labels.contains(&"size") && labels.contains(&"substr"),
        "the members of the standard library's string: {labels:?}"
    );
    assert!(
        !labels.contains(&"printf") && !labels.contains(&"main"),
        "and not the names in scope, which cannot follow the operator: {labels:?}"
    );

    let mut unique = labels.clone();
    unique.sort_unstable();
    unique.dedup();
    assert_eq!(
        unique.len(),
        labels.len(),
        "every spelling appears once — {} of {} rows are repeats: {:?}",
        labels.len() - unique.len(),
        labels.len(),
        labels
            .iter()
            .filter(|label| labels.iter().filter(|other| other == label).count() > 1)
            .collect::<Vec<_>>()
    );

    // Each row carries an **edit that replaces what was typed**, so that the choice is inserted rather than
    // appended to the half-written name — the same contract the `Widget` case asserts, on a type that came from a
    // header rather than from the buffer.
    let append = items
        .iter()
        .find(|item| item["label"] == json!("append"))
        .expect("asserted above");
    assert_eq!(
        append["textEdit"]["range"]["start"],
        json!({ "line": line, "character": character }),
        "just past the dot: {append}"
    );
    assert_eq!(append["textEdit"]["newText"], json!("append"), "{append}");

    server.request(999, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}

/// The type a `.` is asked about is declared in a **header**, and the test's change rewrites that header: the only
/// way the new member can be in the answer is if the header's *summary* was rebuilt, which is what
/// [`cpp_code_analysis::Session::catch_up`] does before the query.
const FRESH_TYPE_H: &str = "struct Widget { int size; };\n";

/// The uses of it, and a `.` at the end of the last line.
const FRESH_TYPE_CPP: &str = "\
#include \"widget.h\"
int main() {
    Widget w;
    w.
}
";

#[test]
fn a_client_without_dynamic_watches_observes_an_external_header_edit() {
    let project = Project::new("native-watch-header");
    project.write("widget.h", FRESH_TYPE_H);
    project.write("main.cpp", FRESH_TYPE_CPP);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));
    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {},
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": FRESH_TYPE_CPP }
        }),
    );

    let (line, character) = position_of(FRESH_TYPE_CPP, "w.");
    let completion = |id| {
        json!({
            "id": id,
            "method": "textDocument/completion",
            "params": {
                "textDocument": { "uri": main_uri },
                "position": { "line": line, "character": character },
            },
        })
    };
    server.ask_until_it(100, completion, |response| {
        response["result"]["items"]
            .as_array()
            .is_some_and(|items| items.iter().any(|item| item["label"] == "size"))
    });

    project.write("widget.h", "struct Widget { int from_disk; };\n");
    let deadline = Instant::now() + TIMEOUT;
    let mut id = 200;
    loop {
        let request = completion(id);
        let response = server.request(id, "textDocument/completion", request["params"].clone());
        if response["result"]["items"]
            .as_array()
            .is_some_and(|items| items.iter().any(|item| item["label"] == "from_disk"))
        {
            break;
        }
        if let Some(error) = response.get("error") {
            assert_eq!(
                error["code"],
                json!(lsp_server::ErrorCode::ContentModified as i32)
            );
        }
        assert!(
            Instant::now() < deadline,
            "the external edit was not observed: {response}"
        );
        id += 1;
        std::thread::sleep(Duration::from_millis(50));
    }

    server.request(999, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}

#[test]
fn a_native_watcher_rescans_new_directories_after_a_burst() {
    let project = Project::new("native-watch-directory");
    project.write("initial.cpp", "int initial_symbol;\n");
    let mut server = Server::start(project.root());
    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": { "textDocument": { "diagnostic": {} } }
        }),
    );
    server.notify("initialized", json!({}));
    server.ask_until_it(
        10,
        |id| json!({ "id": id, "method": "workspace/symbol", "params": { "query": "initial_symbol" } }),
        |response| response["result"].as_array().is_some_and(|items| !items.is_empty()),
    );

    let directory = project.root().join("new_directory");
    std::fs::create_dir(&directory).unwrap();
    std::fs::write(directory.join("new.cpp"), "int created_in_new_directory;\n").unwrap();
    let deadline = Instant::now() + TIMEOUT;
    let mut id = 100;
    loop {
        let response = server.request(
            id,
            "workspace/symbol",
            json!({ "query": "created_in_new_directory" }),
        );
        if response["result"].as_array().is_some_and(|items| {
            items
                .iter()
                .any(|item| item["name"] == "created_in_new_directory")
        }) {
            break;
        }
        if let Some(error) = response.get("error") {
            assert_eq!(
                error["code"],
                json!(lsp_server::ErrorCode::ContentModified as i32)
            );
        }
        assert!(
            Instant::now() < deadline,
            "the new directory was not indexed: {response}"
        );
        id += 1;
        std::thread::sleep(Duration::from_millis(100));
    }
}

#[test]
fn links_and_type_definitions_are_ready_on_the_first_request_after_open() {
    let project = Project::new("first-links-and-types");
    project.write("widget.h", FRESH_TYPE_H);
    project.write("main.cpp", FRESH_TYPE_CPP);
    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));
    let header_uri = uri_of(&project.root().join("widget.h"));

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": { "textDocument": { "diagnostic": {} } }
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": FRESH_TYPE_CPP }
        }),
    );
    let links = server.request(
        2,
        "textDocument/documentLink",
        json!({ "textDocument": { "uri": main_uri } }),
    );
    assert!(
        links["result"].as_array().is_some_and(|links| {
            links.iter().any(|link| {
                link["target"]
                    .as_str()
                    .is_some_and(|target| target.eq_ignore_ascii_case(&header_uri))
            })
        }),
        "the first request must include the resolved header: {links}"
    );

    let (line, character) = position_of(FRESH_TYPE_CPP, "Widget w");
    let types = server.request(
        3,
        "textDocument/typeDefinition",
        json!({
            "textDocument": { "uri": main_uri },
            "position": { "line": line, "character": character - 1 },
        }),
    );
    assert!(
        types["result"].as_array().is_some_and(|items| {
            items.iter().any(|item| {
                item["uri"]
                    .as_str()
                    .is_some_and(|uri| uri.eq_ignore_ascii_case(&header_uri))
            })
        }),
        "the first type definition must resolve the included type: {types}"
    );
}

/// **An edit to an included header is visible to the completion that follows it.**
///
/// This is the shape a user reported and diagnosed as "文件的 didchange 尚未处理完毕": an edit reaches the analysis in
/// two steps that are not the same step. `didChange` replaces the **text** immediately — the scope tree is rebuilt
/// from it on every parse — and *drops the file's summary*, which is rebuilt later, when the index pump reaches that
/// file. A request answered inside that window sees the new text with the **old facts**.
///
/// What it covers is the *atomicity of the pair*: the change and the request arrive with nothing in between, and the
/// answer is about the changed text. What it does **not** discriminate is the fix itself — the class here is in the
/// buffer's own scope tree (a view parses the text it holds, includes and all), so the members are answerable from
/// the tree whether or not the summary was rebuilt. The falsification for
/// [`cpp_code_analysis::Session::catch_up`] is at the session level, where the staleness is visible and measured:
/// `cpp_code_analysis/tests/completion.rs::a_completion_after_an_edit_is_about_the_file_the_edit_wrote`, which
/// asserts that the stale reading is *wrong* and that `catch_up` is what makes it right.
///
/// # Why the change is to a header rather than to `main.cpp`
///
/// Because a change to the file being edited moves the cursor, and the request would then be about a position that
/// did not exist before. Rewriting `widget.h` leaves `w.` where it was.
#[test]
fn a_completion_sees_a_change_to_an_included_header() {
    let project = Project::new("completion-after-header-change");
    project.write("widget.h", FRESH_TYPE_H);
    project.write("main.cpp", FRESH_TYPE_CPP);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));
    let header_uri = uri_of(&project.root().join("widget.h"));

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": FRESH_TYPE_CPP }
        }),
    );
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": header_uri, "languageId": "cpp", "version": 1, "text": FRESH_TYPE_H }
        }),
    );

    // Wait until the list is the members of the type **as it is now**, so that the assertion below is about the
    // change and not about the index being cold.
    let (line, character) = position_of(FRESH_TYPE_CPP, "w.");
    server.ask_until_it(
        100,
        |id| {
            json!({
                "id": id,
                "method": "textDocument/completion",
                "params": {
                    "textDocument": { "uri": main_uri },
                    "position": { "line": line, "character": character },
                },
            })
        },
        |response| {
            response["result"]["items"]
                .as_array()
                .is_some_and(|items| items.iter().any(|item| item["label"] == json!("size")))
        },
    );

    // **The change**, and then the request with nothing in between.
    server.notify(
        "textDocument/didChange",
        json!({
            "textDocument": { "uri": header_uri, "version": 2 },
            "contentChanges": [{ "text": "struct Widget { int size; int added_by_the_edit; };\n" }],
        }),
    );

    // **Asked once, with nothing in between**: the request a client sends in the same breath as the keystroke, and
    // the one that used to be answered from the header's *old* summary — with no members at all, or with the names
    // in scope instead.
    let answer = server.request(
        200,
        "textDocument/completion",
        json!({
            "textDocument": { "uri": main_uri },
            "position": { "line": line, "character": character },
        }),
    );

    let items = answer["result"]["items"]
        .as_array()
        .unwrap_or_else(|| panic!("a completion list was expected, got {answer}"));

    let labels: Vec<&str> = items
        .iter()
        .filter_map(|item| item["label"].as_str())
        .collect();

    assert!(
        labels.contains(&"added_by_the_edit"),
        "the member the edit added, which only a rebuilt summary can express — asked once, right after the change, \
         with no retry to hide a stale answer: {labels:?}"
    );
    assert!(
        !labels.contains(&"main"),
        "and not the names in scope, which is what a stale summary produces: {labels:?}"
    );

    server.request(999, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}

/// **A `.` at the end of a body, on a `std::string` variable, offers the members.**
///
/// The third report of the same symptom — "No suggestions" under `full2.` — and the one that shows how narrow the
/// failure is: the same file answered correctly when the line below the cursor was something else, and answered
/// nothing when the operator was the **last line of the body**, with `}` after it. That is the state a reader is in
/// constantly (type the line, press the key, and the closing brace is what follows), so it is the state this test
/// holds fixed.
///
/// The answers that are *not* acceptable here, and why each of them used to happen:
///
/// * an **empty list** — the member query could not work out the type of the object;
/// * the **names in scope** (`myName`, `full2`, `main`, the keywords) — which is what a declined member query falls
///   through to, and a list of things that cannot follow a `.`;
/// * a **different list at the two positions a caret after the operator can be reported at** — measured on a live
///   server: the request one column early was answered from the tree, found the name `full2`, and offered the names
///   in scope.
///
/// **Release only**, for the reason `a_standard_library_member_list_has_each_spelling_once` gives: the answer needs
/// `std::string`, and *this project has no sources of its own for the pump to seed from* — the client's buffer is
/// the only file — so the assertion can only be met once the pump has read the 156 files of MSVC's `<iostream>`/
/// `<string>` closure. Measured: **23.8 s in release**, past the debug profile's deadline. The debug-equivalent is
/// `cpp_code_analysis/tests/completion.rs`'s
/// `a_member_access_on_the_last_line_of_a_body_offers_its_members_at_either_caret`, which holds the same shape with
/// a header of the project's own.
///
/// ```text
/// cargo test --release -p cpp_ls --test handshake -- --ignored a_member_access_on_the_last_line
/// ```
#[test]
#[ignore = "needs the release profile: the answer comes from the standard library's include closure (156 files)"]
fn a_member_access_on_the_last_line_of_a_body_offers_the_members() {
    let project = Project::new("completion-last-line");
    project.write("main.cpp", LAST_LINE_CPP);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": LAST_LINE_CPP }
        }),
    );

    // **The two characters a caret after a typed `.` can be reported at.**
    //
    // A caret is drawn *between* two characters, and `position_of` returns the offset **past** `full2.` — which is
    // where the caret sits once the operator has been typed. The other position a reader can mean is one before it:
    // the newline's own column (`full2.|`). Both mean "after the operator" to a reader and both must answer the same
    // list, which is exactly the pair a live server disagreed about — a request one column early was answered from
    // the tree, found the name `full2` and offered the names in scope instead of the members.
    //
    // The characters **at or before** the operator's own column are deliberately not asked about here: there the
    // question is about the name `full2`, which is a different question with a different (and correct) answer.
    // Getting this arithmetic wrong is how three separate reports of "the completion is wrong here" turned out to be
    // about a cursor one column away from the operator — see `position_of` and the note on
    // `log_a_member_that_produced_no_members`.
    let (line, ends_at) = position_of(LAST_LINE_CPP, "full2.");

    for character in [ends_at, ends_at - 1] {
        let answer = server.ask_until_it_within(
            100,
            STD_LIBRARY_TIMEOUT,
            |id| {
                json!({
                    "id": id,
                    "method": "textDocument/completion",
                    "params": {
                        "textDocument": { "uri": main_uri },
                        "position": { "line": line, "character": character },
                    },
                })
            },
            |response| {
                response["result"]["items"]
                    .as_array()
                    .is_some_and(|items| items.iter().any(|item| item["label"] == json!("append")))
            },
        );

        let items = answer["result"]["items"]
            .as_array()
            .unwrap_or_else(|| panic!("a completion list was expected, got {answer}"));
        let labels: Vec<&str> = items
            .iter()
            .filter_map(|item| item["label"].as_str())
            .collect();

        assert!(
            labels.contains(&"append") && labels.contains(&"size"),
            "the members of the standard library's string, at line {line} character {character}: {labels:?}"
        );
        assert!(
            !labels.contains(&"full2") && !labels.contains(&"myName"),
            "and not the names in scope, at line {line} character {character}: {labels:?}"
        );
    }

    server.request(999, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}

/// The fixture for the last-line case: the operator is the **final line of the body**, with `}` after it.
///
/// Written to match the report it came from, including the parts that look incidental and are not: a member
/// function with a body (so the class has a non-trivial parse), a second variable of a user-defined type (so the
/// scope is not empty), and the standard library included (so the type's members come from a header).
const LAST_LINE_CPP: &str = "\
#include <iostream>
#include <string>
struct Name {
    std::string firstName;
    std::string lastName;
    std::string getFullName() const { return firstName + lastName; }
};
int main() {
    Name myName;
    std::string full2;
    full2.
}
";

/// **A completion asked for right after a change sees the change.**
///
/// A client sends `didChange` and then, without waiting for anything, asks for a completion at a position that only
/// exists in the **new** text — which is what typing is: the request follows the keystroke that caused it. The
/// server queues notifications so that its message loop never waits for a parse, and the queue must not be visible
/// to a request: while it was, the analysis still held older text, the cursor was past the end of that line, no
/// node was there, and the answer was `null` — a completion that simply does not appear.
///
/// The burst is what makes it a test rather than a coin toss: with one change the queue may well be applied before
/// the request is served (measured: the same assertion failed on 1 run in 4), so the fixture sends a **stream** of
/// changes the way a client that is typing, pasting or formatting does, and only the last of them has the `w.` the
/// request is about. Any staleness at all therefore fails: an older text has that line blank.
#[test]
fn a_completion_right_after_a_change_sees_the_change() {
    /// Long enough that applying one change is real work — the queue has to be behind for the race to exist.
    const LINES: usize = 1200;
    /// The burst. Each round is a different text, so each is a change a client could have sent.
    const ROUNDS: usize = 24;

    let text = |round: usize, dot: bool| {
        let mut text =
            String::from("struct Widget { int size; int weight; };\nvoid f() {\n    Widget w;\n");
        for index in 0..LINES {
            text.push_str(&format!("    w.size = {};\n", index + round));
        }
        text.push_str(if dot { "    w.\n}\n" } else { "    \n}\n" });
        text
    };

    let project = Project::new("completion-after-change");
    project.write("main.cpp", &text(0, false));

    let mut server = Server::start(project.root());
    let uri = uri_of(&project.root().join("main.cpp"));

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": uri, "languageId": "cpp", "version": 1, "text": text(0, false) }
        }),
    );

    // The burst, and then **immediately** the request: no sleep, no retry, no second request. A client that typed a
    // dot sends its edits and then asks, in this order.
    let sent = Instant::now();
    for round in 1..=ROUNDS {
        server.notify(
            "textDocument/didChange",
            json!({
                "textDocument": { "uri": uri, "version": round + 1 },
                "contentChanges": [{ "text": text(round, round == ROUNDS) }],
            }),
        );
    }
    let burst_written = Instant::now();

    let answer = server.request(
        100,
        "textDocument/completion",
        json!({
            "textDocument": { "uri": uri },
            "position": { "line": 3 + LINES, "character": 6 },
        }),
    );
    let served = Instant::now();

    // Reported rather than asserted: how long the burst costs the request that follows it is a measurement, and it
    // moves with the machine. What *is* asserted is the count of applications, in `context::update_queue`'s own
    // tests — a burst of changes for one document is one piece of work, so this request waited for one.
    println!(
        "a {ROUNDS}-change burst sent in {:?}, then a completion answered {:?} later",
        burst_written.elapsed(),
        served - sent
    );

    let items = answer["result"]["items"]
        .as_array()
        .unwrap_or_else(|| panic!("`w.` in the changed text must complete, got {answer}"));

    assert!(
        items.iter().any(|item| item["label"] == json!("weight")),
        "and the list is the *changed* class's members — `weight` is the member the change added: {answer}"
    );

    server.request(999, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}

#[test]
fn an_incremental_edit_is_visible_to_the_next_completion() {
    let project = Project::new("incremental-completion");
    let source = "struct Widget { int size; };\nvoid f() {\n    Widget w;\n    w.\n}\n";
    project.write("main.cpp", source);
    let mut server = Server::start(project.root());
    let uri = uri_of(&project.root().join("main.cpp"));
    let initialized = server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {},
        }),
    );
    assert_eq!(
        initialized["result"]["capabilities"]["textDocumentSync"]["change"],
        json!(2)
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": uri, "languageId": "cpp", "version": 1, "text": source }
        }),
    );
    let (line, character) = position_of(source, "w.");
    server.ask_until_it(
        100,
        |id| {
            json!({
                "id": id,
                "method": "textDocument/completion",
                "params": { "textDocument": { "uri": uri }, "position": { "line": line, "character": character } }
            })
        },
        |response| {
            response["result"]["items"]
                .as_array()
                .is_some_and(|items| items.iter().any(|item| item["label"] == json!("size")))
        },
    );

    let (edit_line, edit_character) = position_of(source, "int size;");
    server.notify(
        "textDocument/didChange",
        json!({
            "textDocument": { "uri": uri, "version": 2 },
            "contentChanges": [{
                "range": {
                    "start": { "line": edit_line, "character": edit_character },
                    "end": { "line": edit_line, "character": edit_character }
                },
                "text": " int added;"
            }]
        }),
    );
    let answer = server.request(
        200,
        "textDocument/completion",
        json!({ "textDocument": { "uri": uri }, "position": { "line": line, "character": character } }),
    );
    assert!(
        answer["result"]["items"]
            .as_array()
            .is_some_and(|items| items.iter().any(|item| item["label"] == json!("added"))),
        "the incremental edit must be visible immediately: {answer}"
    );
}

#[test]
fn a_client_without_pull_support_receives_versioned_diagnostics() {
    let project = Project::new("legacy-diagnostics");
    let broken = "struct Unclosed { int value;\n";
    let clean = "int main() { return 0; }\n";
    project.write("main.cpp", broken);
    let mut server = Server::start(project.root());
    let uri = uri_of(&project.root().join("main.cpp"));
    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "textDocument": { "publishDiagnostics": { "versionSupport": true } }
            }
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": uri, "languageId": "cpp", "version": 1, "text": broken }
        }),
    );
    let first = server.wait_for(|message| {
        message["method"] == "textDocument/publishDiagnostics"
            && message["params"]["uri"] == uri
            && message["params"]["version"] == 1
    });
    assert!(
        first["params"]["diagnostics"]
            .as_array()
            .is_some_and(|items| !items.is_empty()),
        "the invalid file must be diagnosed: {first}"
    );

    server.notify(
        "textDocument/didChange",
        json!({
            "textDocument": { "uri": uri, "version": 2 },
            "contentChanges": [{ "text": clean }]
        }),
    );
    let corrected = server.wait_for(|message| {
        message["method"] == "textDocument/publishDiagnostics"
            && message["params"]["uri"] == uri
            && message["params"]["version"] == 2
    });
    assert_eq!(corrected["params"]["diagnostics"], json!([]));

    for (version, text) in [(3, broken), (4, clean)] {
        server.notify(
            "textDocument/didChange",
            json!({
                "textDocument": { "uri": uri, "version": version },
                "contentChanges": [{ "text": text }]
            }),
        );
    }
    let latest = server.wait_for(|message| {
        if message["method"] == "textDocument/publishDiagnostics" && message["params"]["uri"] == uri
        {
            assert_ne!(
                message["params"]["version"], 3,
                "a superseded result was published"
            );
            return message["params"]["version"] == 4;
        }
        false
    });
    assert_eq!(latest["params"]["diagnostics"], json!([]));

    server.notify(
        "textDocument/didClose",
        json!({ "textDocument": { "uri": uri } }),
    );
    let closed = server.wait_for(|message| {
        message["method"] == "textDocument/publishDiagnostics"
            && message["params"]["uri"] == uri
            && message["params"]["version"].is_null()
    });
    assert_eq!(closed["params"]["diagnostics"], json!([]));
}

#[test]
fn an_unreadable_diagnostic_target_is_an_error_not_an_empty_report() {
    let project = Project::new("missing-diagnostic");
    let mut server = Server::start(project.root());
    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": { "textDocument": { "diagnostic": {} } }
        }),
    );
    server.notify("initialized", json!({}));
    let missing = uri_of(&project.root().join("missing.cpp"));
    let response = server.request(
        2,
        "textDocument/diagnostic",
        json!({ "textDocument": { "uri": missing } }),
    );
    assert_eq!(
        response["error"]["code"],
        json!(lsp_server::ErrorCode::RequestFailed as i32),
        "an unreadable file is not a clean file: {response}"
    );
}

#[test]
fn a_file_opened_without_a_workspace_gets_an_analysis_session() {
    let project = Project::new("single-file");
    let source = "struct Widget { int member; };\nvoid f() { Widget w; w.\n}\n";
    project.write("main.cpp", source);
    let mut server = Server::start(project.root());
    let uri = uri_of(&project.root().join("main.cpp"));
    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": null,
            "capabilities": { "textDocument": { "diagnostic": {} } }
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": uri, "languageId": "cpp", "version": 1, "text": source }
        }),
    );
    let (line, character) = position_of(source, "w.");
    let answer = server.request(
        2,
        "textDocument/completion",
        json!({ "textDocument": { "uri": uri }, "position": { "line": line, "character": character } }),
    );
    assert!(
        answer["result"]["items"]
            .as_array()
            .is_some_and(|items| items.iter().any(|item| item["label"] == "member")),
        "the single file must be analysed: {answer}"
    );
}

#[test]
fn a_module_is_read_in_the_background_for_completion() {
    let project = Project::new("background-module");
    let source = "import report;\nvoid f() { Report r; r.\n}\n";
    project.write("main.cpp", source);
    project.write(
        "report.cppm",
        "export module report;\nexport struct Report { int module_member; };\n",
    );
    let mut server = Server::start(project.root());
    let uri = uri_of(&project.root().join("main.cpp"));
    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": { "textDocument": { "diagnostic": {} } }
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": uri, "languageId": "cpp", "version": 1, "text": source }
        }),
    );
    let (line, character) = position_of(source, "r.");
    server.ask_until_it(
        100,
        |id| {
            json!({
                "id": id,
                "method": "textDocument/completion",
                "params": { "textDocument": { "uri": uri }, "position": { "line": line, "character": character } }
            })
        },
        |response| {
            response["result"]["items"]
                .as_array()
                .is_some_and(|items| items.iter().any(|item| item["label"] == "module_member"))
        },
    );
}

#[test]
fn a_configuration_reload_indexes_the_new_project_files() {
    let project = Project::new("reload-generation");
    project.write(".cppls.toml", "[workspace]\nsource_extensions = []\n");
    project.write("main.cpp", "int main() { return 0; }\n");
    project.write("extra.custom", "int ReloadedSymbol;\n");
    let mut server = Server::start(project.root());
    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": { "textDocument": { "diagnostic": {} } }
        }),
    );
    server.notify("initialized", json!({}));
    let before = server.request(2, "workspace/symbol", json!({ "query": "ReloadedSymbol" }));
    assert!(
        before["result"]
            .as_array()
            .is_none_or(|items| items.is_empty()),
        "the custom extension is not initially indexed: {before}"
    );

    project.write(
        ".cppls.toml",
        "[workspace]\nsource_extensions = [\"custom\"]\n",
    );
    server.notify(
        "workspace/didChangeWatchedFiles",
        json!({
            "changes": [{ "uri": uri_of(&project.root().join(".cppls.toml")), "type": 2 }]
        }),
    );
    std::thread::sleep(Duration::from_secs(3));
    server.ask_until_it(
        100,
        |id| json!({ "id": id, "method": "workspace/symbol", "params": { "query": "ReloadedSymbol" } }),
        |response| {
            response["result"]
                .as_array()
                .is_some_and(|items| items.iter().any(|item| item["name"] == "ReloadedSymbol"))
        },
    );
}

/// A macro defined in one header and used in two files — the shape a rename has to get right, and the shape a
/// *reference list* has to walk: the definition, and the uses that can see it.
const LIMITS_H: &str = "#define MAX_ITEMS 64\n";
const ITEMS_H: &str = "#include \"limits.h\"\nint items[MAX_ITEMS];\n";
const ITEMS_CPP: &str = "#include \"api.h\"\nvoid f() {\n    int more[MAX_ITEMS];\n}\n";

/// **References and rename: the macro is renamed everywhere, the ordinary name is refused.**
///
/// Two features in one test because they are one question asked twice — "where is this name written" — and because
/// the second half is the one that must **not** happen: a rename of an ordinary name would have to decide, for every
/// candidate file, whether the name at that offset resolves to the same declaration, which needs each candidate's
/// scopes and therefore a parse per candidate. So the handler refuses (`null`), and this test pins the refusal next
/// to the success, because "renamed half of the uses" is the one outcome an editor must never produce.
///
/// And a macro's rename *is* exact: its name is a textual thing, one table in the preprocessor, replaced wherever it
/// appears — so every edit below is a place the analysis read as that macro, in the files that can see its
/// definition.
#[test]
fn a_macro_is_renamed_everywhere_and_an_ordinary_name_is_refused() {
    let project = Project::new("rename");
    project.write("limits.h", LIMITS_H);
    project.write("api.h", ITEMS_H);
    project.write("main.cpp", ITEMS_CPP);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    let capabilities = server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    let capabilities = &capabilities["result"]["capabilities"];
    assert_eq!(
        capabilities["referencesProvider"],
        json!(true),
        "{capabilities}"
    );
    assert_eq!(
        capabilities["renameProvider"]["prepareProvider"],
        json!(true),
        "the rename box is offered only where a rename can happen: {capabilities}"
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": ITEMS_CPP }
        }),
    );

    // The use in `main.cpp` is on line 2 at columns 13..22 (`    int more[MAX_ITEMS];`).
    let at_the_use = json!({ "line": 2, "character": 16 });

    // --- references, with and without the definition ------------------------------------------------
    // `ask_until` is what a client does with the answer this server gives while the index still has work: `null`,
    // because a reference list assembled from a partially read index is a false claim rather than a smaller truth
    // (the protocol gives this response no `isIncomplete`, unlike a completion list). The loop below is therefore
    // part of the behaviour under test, not test scaffolding.
    let mut references = |include_declaration: bool| {
        server.ask_until(100, |id| {
            json!({
                "id": id,
                "method": "textDocument/references",
                "params": {
                    "textDocument": { "uri": main_uri },
                    "position": at_the_use,
                    "context": { "includeDeclaration": include_declaration },
                },
            })
        })
    };

    let with_the_definition = references(true);
    let locations = with_the_definition["result"]
        .as_array()
        .unwrap_or_else(|| panic!("a location list was expected, got {with_the_definition}"));
    assert_eq!(
        locations.len(),
        3,
        "the `#define` and both uses: {with_the_definition}"
    );
    let files: Vec<&str> = locations
        .iter()
        .filter_map(|location| location["uri"].as_str())
        .collect();
    assert!(
        files.iter().any(|file| file.ends_with("limits.h")),
        "including the file that defines it, which nobody opened: {with_the_definition}"
    );
    assert!(
        files.iter().any(|file| file.ends_with("api.h")),
        "and the header that uses it: {with_the_definition}"
    );

    let without = references(false);
    assert_eq!(
        without["result"].as_array().map(Vec::len),
        Some(2),
        "`includeDeclaration: false` leaves the `#define` out: {without}"
    );

    // --- the rename box, and the rename --------------------------------------------------------------
    let prepared = server.request(
        200,
        "textDocument/prepareRename",
        json!({ "textDocument": { "uri": main_uri }, "position": at_the_use }),
    );
    // **`RangeWithPlaceholder`**: the box starts around the name *and* with the name in it, so a reader renames
    // `MAX_ITEMS` rather than typing over an empty box. The server used to answer a bare range — and nothing at all for
    // a symbol.
    assert_eq!(
        prepared["result"]["range"]["start"],
        json!({ "line": 2, "character": 13 }),
        "the box starts around the name itself: {prepared}"
    );
    assert_eq!(
        prepared["result"]["range"]["end"],
        json!({ "line": 2, "character": 22 }),
        "{prepared}"
    );
    assert_eq!(
        prepared["result"]["placeholder"], "MAX_ITEMS",
        "and it starts with the name in it: {prepared}"
    );

    let renamed = server.request(
        300,
        "textDocument/rename",
        json!({
            "textDocument": { "uri": main_uri },
            "position": at_the_use,
            "newName": "MAX_ENTRIES",
        }),
    );
    let changes = renamed["result"]["changes"]
        .as_object()
        .unwrap_or_else(|| panic!("a workspace edit was expected, got {renamed}"));
    assert_eq!(changes.len(), 3, "three files are edited: {renamed}");

    let edits: Vec<&Value> = changes
        .values()
        .flat_map(|edits| edits.as_array().into_iter().flatten())
        .collect();
    assert_eq!(edits.len(), 3, "and one edit in each: {renamed}");
    assert!(
        edits
            .iter()
            .all(|edit| edit["newText"] == json!("MAX_ENTRIES")),
        "every edit writes the new name: {renamed}"
    );
    let definition_edit = changes
        .iter()
        .find(|(uri, _)| uri.ends_with("limits.h"))
        .map(|(_, edits)| &edits[0])
        .unwrap_or_else(|| panic!("the `#define` itself is edited: {renamed}"));
    assert_eq!(
        definition_edit["range"],
        json!({
            "start": { "line": 0, "character": 8 },
            "end": { "line": 0, "character": 17 },
        }),
        "and the definition's edit covers its name: {definition_edit}"
    );

    // --- the other half of the feature: a **local** is renamed inside its own file ---------------------
    // `more` is declared and never used in this fixture, which is the case that used to be refused: `local_references_of`
    // records a *use* against its declaration, so an unused local has no entry — and renaming the declaration alone is
    // the whole edit. It must not leave this file: a local is not visible through an include, so a cross-file list
    // would rewrite other files' `more`s.
    let on_a_local = json!({ "line": 2, "character": 9 });

    let prepared = server.request(
        400,
        "textDocument/prepareRename",
        json!({ "textDocument": { "uri": main_uri }, "position": on_a_local }),
    );
    assert_eq!(
        prepared["result"]["placeholder"], "more",
        "a local has a rename box too: {prepared}"
    );

    let renamed = server.request(
        500,
        "textDocument/rename",
        json!({
            "textDocument": { "uri": main_uri },
            "position": on_a_local,
            "newName": "renamed",
        }),
    );
    let changes = renamed["result"]["changes"]
        .as_object()
        .unwrap_or_else(|| panic!("the local is renamed: {renamed}"));
    println!("local rename: {renamed}");
    assert_eq!(
        changes.len(),
        1,
        "one file — the one the local is in: {renamed}"
    );
    assert_eq!(
        changes
            .values()
            .next()
            .and_then(|edits| edits.as_array())
            .map(Vec::len),
        Some(1),
        "one edit: the declaration, the only occurrence in this fixture: {renamed}"
    );
    // A rename to something that is not a name is refused too — two identifiers, a literal, nothing at all.
    for not_a_name in ["two words", "\"quoted\"", ""] {
        let refused = server.request(
            600,
            "textDocument/rename",
            json!({
                "textDocument": { "uri": main_uri },
                "position": at_the_use,
                "newName": not_a_name,
            }),
        );
        assert!(
            refused["result"].is_null(),
            "{not_a_name:?} is not a name: {refused}"
        );
    }

    server.request(999, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}

/// The selection fixture: one expression nested in a statement, a body and a function.
const SELECTION_CPP: &str = "int f() {\n    return w.size;\n}\n";

/// **Expanding a selection walks a chain**, and the chain is the answer's *shape* rather than a list.
///
/// A client walks it outward: the word under the cursor, then each construct containing it, out to the file — and
/// every step has to be strictly larger, or the keystroke does nothing. Over the wire that is a nested object, each
/// range pointing at its parent, which is the part a client cannot reconstruct and therefore the part worth pinning.
#[test]
fn a_selection_expands_one_rung_at_a_time() {
    let project = Project::new("selection-range");
    project.write("main.cpp", SELECTION_CPP);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    let capabilities = server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    assert_eq!(
        capabilities["result"]["capabilities"]["selectionRangeProvider"],
        json!(true),
        "the client is told the server can expand a selection: {capabilities}"
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": SELECTION_CPP }
        }),
    );

    // Line 1 is `    return w.size;` — the cursor is inside `size`, at the `i`.
    let answer = server.ask_until(100, |id| {
        json!({
            "id": id,
            "method": "textDocument/selectionRange",
            "params": {
                "textDocument": { "uri": main_uri },
                "positions": [{ "line": 1, "character": 13 }],
            },
        })
    });

    let answers = answer["result"]
        .as_array()
        .unwrap_or_else(|| panic!("one answer per position was expected, got {answer}"));
    assert_eq!(answers.len(), 1, "one position, one chain: {answer}");

    // Walk the parent chain the way a client does, and record each rung's text by line and column.
    let mut rungs = Vec::new();
    let mut current = Some(&answers[0]);
    while let Some(range) = current {
        rungs.push((
            range["range"]["start"]["line"].as_u64().unwrap_or_default(),
            range["range"]["start"]["character"]
                .as_u64()
                .unwrap_or_default(),
            range["range"]["end"]["line"].as_u64().unwrap_or_default(),
            range["range"]["end"]["character"]
                .as_u64()
                .unwrap_or_default(),
        ));
        current = range.get("parent").filter(|parent| !parent.is_null());
    }

    // **The statement's rung ends at its `;`, on its own line.** It used to run to `(2, 0)` because the trailing
    // newline was glued inside the statement's node; the node now ends where its last token does, and the range a
    // client gets is the statement a reader would select — `return w.size;` and not the line break after it.
    //
    // **The body's rung begins one character early, at `(0, 7)` rather than `(0, 8)`**, and that is the trivia pass
    // rather than a slip: a block reaches back over the layout in front of it, because the layout between two
    // statements belongs to the block that holds both of them. Here the layout in front of `{` is the space in
    // `int f() {`, so the body's range covers it. The rule is the one the reference implementation states, and the
    // cost is a selection that starts one character left of the brace on the one line where a function's `{` is
    // written after a space.
    assert_eq!(
        rungs,
        vec![
            (1, 13, 1, 17), // `size`
            (1, 11, 1, 17), // `w.size`
            (1, 4, 1, 18),  // `return w.size;`
            (0, 7, 3, 0),   // the function body, including the space before its `{`
            (0, 0, 3, 0),   // the function definition
        ],
        "the chain, innermost first: {answer}"
    );

    server.request(999, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}

/// The workspace-symbol fixture: a class in a namespace, in a header — and the client opens only the `.cpp`.
const SEARCH_H: &str =
    "namespace ns {\nstruct Widget { int size; };\n}\nstruct WidgetRegistry { int count; };\n";
const SEARCH_CPP: &str = "#include \"search.h\"\nvoid f() { ns::Widget w; }\n";

/// **A symbol in a file nobody opened is found by a project search.**
///
/// Every other feature here is asked about a cursor in a file the client is showing; this one is asked about the
/// project, and the answer has to include declarations from files the user has never looked at — which is what the
/// index is for. The query is matched the way the index documents it (`Widget::si` finds the member, `ns::widget`
/// does not drag it in), and the one thing this test pins beyond that is the qualification travelling with the
/// symbol, because a client shows it beside the name.
#[test]
fn a_workspace_search_finds_a_symbol_in_a_file_nobody_opened() {
    let project = Project::new("workspace-symbol");
    project.write("search.h", SEARCH_H);
    project.write("main.cpp", SEARCH_CPP);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    let capabilities = server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    assert_eq!(
        capabilities["result"]["capabilities"]["workspaceSymbolProvider"],
        json!(true),
        "the client is told the server searches: {capabilities}"
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": SEARCH_CPP }
        }),
    );

    // Asked again until it answers, because a search that arrives while the index still has work is refused
    // (`null`) rather than answered partially — see the handler's module note.
    let answer = server.ask_until_it(
        100,
        |id| json!({ "id": id, "method": "workspace/symbol", "params": { "query": "widget" } }),
        |response| {
            response["result"]
                .as_array()
                .is_some_and(|symbols| !symbols.is_empty())
        },
    );

    let found = answer["result"]
        .as_array()
        .unwrap_or_else(|| panic!("a symbol list was expected, got {answer}"));
    let names: Vec<&str> = found
        .iter()
        .filter_map(|symbol| symbol["name"].as_str())
        .collect();
    assert_eq!(
        names,
        vec!["Widget", "WidgetRegistry"],
        "the name first, then the one that contains it: {answer}"
    );

    let widget = &found[0];
    assert!(
        widget["location"]["uri"]
            .as_str()
            .is_some_and(|uri| uri.ends_with("search.h")),
        "the class is declared in a file the client never opened: {widget}"
    );
    assert_eq!(
        widget["containerName"],
        json!("ns"),
        "and the namespace it is in travels with it: {widget}"
    );
    assert_eq!(widget["kind"], json!(5), "a class: {widget}");

    // The **qualified** query finds the same class, and the member only when it is asked for by its owner.
    let qualified = server.ask_until(
        200,
        |id| json!({ "id": id, "method": "workspace/symbol", "params": { "query": "Widget::si" } }),
    );
    let names: Vec<&str> = qualified["result"]
        .as_array()
        .into_iter()
        .flatten()
        .filter_map(|symbol| symbol["name"].as_str())
        .collect();
    assert_eq!(
        names,
        vec!["size"],
        "`Widget::si` asks for the member: {qualified}"
    );

    let class_only = server.ask_until(
        300,
        |id| json!({ "id": id, "method": "workspace/symbol", "params": { "query": "ns::widget" } }),
    );
    let names: Vec<&str> = class_only["result"]
        .as_array()
        .into_iter()
        .flatten()
        .filter_map(|symbol| symbol["name"].as_str())
        .collect();
    assert_eq!(
        names,
        vec!["Widget"],
        "and a class query does not drag its members in: {class_only}"
    );

    server.request(999, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}

/// The folding fixture: an include run, a comment block, a class, and a conditional — one of each kind the protocol
/// names, in an order where the lines are easy to count.
const FOLDS_CPP: &str = "#include <string>\n\
                         #include <vector>\n\
                         \n\
                         // a note\n\
                         // and another\n\
                         \n\
                         struct Widget {\n\
                             int size;\n\
                         };\n\
                         \n\
                         #if defined(_WIN32)\n\
                         int win;\n\
                         #endif\n";

/// **Folding is about the file, and the lines are the client's.**
///
/// Four regions, one of each kind the protocol names, and each one's line range is asserted exactly — because the
/// two ways this can be wrong are both off-by-one: an end taken past the region hides the line after it, and a
/// region whose ends land on one line hides nothing at all. The analysis answers in offsets and refuses the second
/// kind; the conversion to lines happens here, which is why this test goes over the wire rather than against the
/// analysis's own tests.
#[test]
fn the_folds_of_a_file_are_the_regions_a_reader_hides() {
    let project = Project::new("folding");
    project.write("main.cpp", FOLDS_CPP);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    let capabilities = server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    assert_eq!(
        capabilities["result"]["capabilities"]["foldingRangeProvider"],
        json!(true),
        "the client is told the server folds: {capabilities}"
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": FOLDS_CPP }
        }),
    );

    let answer = server.ask_until(100, |id| {
        json!({
            "id": id,
            "method": "textDocument/foldingRange",
            "params": { "textDocument": { "uri": main_uri } },
        })
    });

    let ranges = answer["result"]
        .as_array()
        .unwrap_or_else(|| panic!("a folding range list was expected, got {answer}"));
    let seen: Vec<(u64, u64, Option<&str>)> = ranges
        .iter()
        .map(|range| {
            (
                range["startLine"].as_u64().unwrap_or_default(),
                range["endLine"].as_u64().unwrap_or_default(),
                range["kind"].as_str(),
            )
        })
        .collect();

    assert_eq!(
        seen,
        vec![
            (0, 1, Some("imports")),
            (3, 4, Some("comment")),
            (6, 8, None),
            (10, 12, Some("region")),
        ],
        "the include run, the comment block, the class (no kind: the protocol calls that code), the conditional"
    );

    server.request(999, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}
const OUTLINE_CPP: &str = "#include \"cfg.h\"\n\
                           #include \"handle.h\"\n\
                           #if OFF\n\
                           struct Dead { int x; };\n\
                           #endif\n\
                           struct Live { int y; };\n\
                           DECLARE_HANDLE(HWND);\n";

/// **The outline shows the file, not the compiler** — both halves of that, in one fixture.
///
/// `#if OFF` is false once the header says so, so a compiler never sees `Dead` — and a reader editing that branch
/// very much does, which is why an outline is built from the file's **own** declarations rather than from the
/// cooked reading every other feature uses. The other direction is `DECLARE_HANDLE(HWND)`: the file writes a call,
/// so `HWND__` and `HWND` are in the index and in completions and are *not* here — an outline listing a name the
/// file never writes would be claiming something about the file that is not true.
#[test]
fn the_outline_shows_the_file_and_not_the_compiler() {
    let project = Project::new("outline");
    project.write("cfg.h", CFG_H);
    project.write("handle.h", HANDLE_H);
    project.write("main.cpp", OUTLINE_CPP);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    let capabilities = server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    assert_eq!(
        capabilities["result"]["capabilities"]["documentSymbolProvider"],
        json!(true),
        "the client is told the server outlines: {capabilities}"
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": OUTLINE_CPP }
        }),
    );

    let answer = server.ask_until(100, |id| {
        json!({
            "id": id,
            "method": "textDocument/documentSymbol",
            "params": { "textDocument": { "uri": main_uri } },
        })
    });

    let symbols = answer["result"]
        .as_array()
        .unwrap_or_else(|| panic!("a nested outline was expected, got {answer}"));

    // Every name in the tree, however deep, for the assertions about what is *not* there.
    fn all_names(symbols: &[Value], into: &mut Vec<String>) {
        for symbol in symbols {
            into.push(symbol["name"].as_str().unwrap_or_default().to_string());
            if let Some(children) = symbol["children"].as_array() {
                all_names(children, into);
            }
        }
    }

    let mut names = Vec::new();
    all_names(symbols, &mut names);
    assert_eq!(
        names,
        vec!["Dead", "x", "Live", "y"],
        "the branch nobody takes is in the outline, the file's own class, and nothing else: {answer}"
    );

    assert_eq!(symbols[0]["kind"], json!(5), "a class: {}", symbols[0]);
    assert_eq!(
        symbols[0]["children"][0]["kind"],
        json!(13),
        "a variable: {}",
        symbols[0]
    );

    // The pair of ranges: the name is what a client selects, and it is inside the declaration it folds.
    assert_eq!(
        symbols[0]["selectionRange"],
        json!({ "start": { "line": 3, "character": 7 }, "end": { "line": 3, "character": 11 } }),
        "`Dead` is selected by its own name: {}",
        symbols[0]
    );
    assert_eq!(
        symbols[0]["range"]["start"]["line"],
        json!(3),
        "and the declaration starts on the same line: {}",
        symbols[0]
    );

    server.request(999, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}

/// The semantic-token fixture: a macro, a namespace, a class with a method, and a parameter.
const COLOURS_CPP: &str = "\
#define LIMIT 8
namespace shapes {
struct Widget {
    int size;
    int scaled(int factor) const;
};
}
";

/// **Semantic colours: each name is drawn as what declares it**, over the wire.
///
/// The answer is the protocol's delta walk — five numbers per token, the first two relative to the token before —
/// so the test decodes it back into absolute positions the way a client does, and asserts that a specific name is
/// drawn as a *specific legend entry*. That last part is the one a unit test cannot check: the numbers only mean
/// something against the legend the server advertised in `initialize`, and a legend that disagreed with the
/// encoding would colour every name as whatever sits at that index.
#[test]
fn semantic_colours_are_the_kinds_the_declarations_have() {
    let project = Project::new("semantic-tokens");
    project.write("main.cpp", COLOURS_CPP);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    let capabilities = server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
                "textDocument": {
                    "semanticTokens": {
                        "requests": { "full": true },
                        "tokenTypes": ["namespace", "type", "typeParameter", "enumMember", "function",
                                       "method", "variable", "parameter", "macro"],
                        "tokenModifiers": ["declaration"],
                        "formats": ["relative"],
                    },
                },
            },
        }),
    );
    let legend = capabilities["result"]["capabilities"]["semanticTokensProvider"]["legend"].clone();
    let index_of = |name: &str| -> u64 {
        legend["tokenTypes"]
            .as_array()
            .expect("a legend")
            .iter()
            .position(|kind| kind == name)
            .unwrap_or_else(|| panic!("the legend has no `{name}`: {legend}")) as u64
    };
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": COLOURS_CPP }
        }),
    );

    let answer = server.ask_until(100, |id| {
        json!({
            "id": id,
            "method": "textDocument/semanticTokens/full",
            "params": { "textDocument": { "uri": main_uri } },
        })
    });

    let data = answer["result"]["data"]
        .as_array()
        .unwrap_or_else(|| panic!("a token array was expected, got {answer}"));
    let numbers: Vec<u64> = data
        .iter()
        .map(|value| value.as_u64().expect("the encoding is numbers"))
        .collect();
    assert_eq!(numbers.len() % 5, 0, "five numbers per token: {numbers:?}");

    // The client's own reconstruction: absolute line and character, then the length and the kind.
    let mut line = 0u64;
    let mut character = 0u64;
    let mut tokens: Vec<(u64, u64, u64, u64, u64)> = Vec::new();
    for token in numbers.chunks(5) {
        if token[0] == 0 {
            character += token[1];
        } else {
            line += token[0];
            character = token[1];
        }
        tokens.push((line, character, token[2], token[3], token[4]));
    }

    let at = |needle: &str| -> (u64, u64) {
        let line = COLOURS_CPP
            .lines()
            .position(|text| text.contains(needle))
            .expect("the fixture writes it") as u64;
        let character = COLOURS_CPP
            .lines()
            .nth(line as usize)
            .and_then(|text| text.find(needle))
            .expect("the fixture writes it") as u64;
        (line, character)
    };

    let coloured = |needle: &str| -> Option<(u64, u64, u64)> {
        let (line, character) = at(needle);
        tokens
            .iter()
            .find(|token| token.0 == line && token.1 == character)
            .map(|token| (token.2, token.3, token.4))
    };

    assert_eq!(
        coloured("LIMIT").map(|(_, kind, _)| kind),
        Some(index_of("macro")),
        "a macro this file defines: {tokens:?}"
    );
    assert_eq!(
        coloured("shapes").map(|(_, kind, _)| kind),
        Some(index_of("namespace")),
        "{tokens:?}"
    );
    assert_eq!(
        coloured("Widget").map(|(_, kind, _)| kind),
        Some(index_of("type")),
        "a class is a type here: {tokens:?}"
    );
    assert_eq!(
        coloured("size").map(|(_, kind, _)| kind),
        Some(index_of("variable")),
        "a field is a variable: {tokens:?}"
    );
    assert_eq!(
        coloured("scaled").map(|(_, kind, _)| kind),
        Some(index_of("method")),
        "a function in a class is a method: {tokens:?}"
    );
    assert_eq!(
        coloured("factor").map(|(_, kind, _)| kind),
        Some(index_of("parameter")),
        "and a parameter is not a variable: {tokens:?}"
    );

    // The length is the name's own, and the modifier says it is where the name is declared.
    let (length, _, modifiers) = coloured("LIMIT").expect("the macro is coloured");
    assert_eq!(length, "LIMIT".len() as u64);
    assert_eq!(modifiers, 1, "the declaration modifier: {tokens:?}");

    server.request(999, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}

/// The signature fixture: a documented declaration, and a call being typed into.
const SIGNATURE_CPP: &str = "\
/// Scales a count.
/// @param count the count
int scale(int count, double factor);

int f() {
    return scale(1, );
}
";

/// **The signature popup, while the second argument is being typed.**
///
/// The cursor sits right after the comma — the state a signature exists for — and what has to come back is the
/// declaration's own text, the two parameter spans *inside that label*, the second one active, and the
/// documentation the file wrote above the declaration. A client bolds the active parameter by slicing the label
/// with the span, which is what this test does with it.
#[test]
fn a_signature_is_shown_while_the_arguments_are_typed() {
    let project = Project::new("signature-help");
    project.write("main.cpp", SIGNATURE_CPP);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": SIGNATURE_CPP }
        }),
    );

    let call_line = SIGNATURE_CPP
        .lines()
        .position(|line| line.contains("scale(1, )"))
        .expect("the fixture writes the call") as u64;
    let after_the_comma = SIGNATURE_CPP
        .lines()
        .nth(call_line as usize)
        .and_then(|line| line.find("scale(1, "))
        .expect("the fixture writes the call")
        + "scale(1, ".len();

    let answer = server.ask_until(100, |id| {
        json!({
            "id": id,
            "method": "textDocument/signatureHelp",
            "params": {
                "textDocument": { "uri": main_uri },
                "position": { "line": call_line, "character": after_the_comma },
            },
        })
    });

    let signature = &answer["result"]["signatures"][0];
    assert_eq!(
        signature["label"], "scale(int count, double factor)",
        "the declaration's own text: {answer}"
    );
    assert_eq!(answer["result"]["activeSignature"], json!(0));
    assert_eq!(
        answer["result"]["activeParameter"],
        json!(1),
        "the cursor is past the first comma, so the second parameter is active: {answer}"
    );

    // The parameter spans are offsets into the label — the client's own use of them, done here.
    let label = signature["label"].as_str().expect("a label");
    let spans: Vec<&str> = signature["parameters"]
        .as_array()
        .expect("the parameters are sent")
        .iter()
        .map(|parameter| {
            let offsets = parameter["label"].as_array().expect("offsets");
            let start = offsets[0].as_u64().expect("a start") as usize;
            let end = offsets[1].as_u64().expect("an end") as usize;
            &label[start..end]
        })
        .collect();
    assert_eq!(spans, vec!["int count", "double factor"]);

    // **The function's own text above the signature, and the `@param` line under the parameter it names.**
    //
    // Reported from an editor: "the function's popup should be synthesized from the doc and not include the
    // `@param` lines, and the parameters themselves should get their own". The whole comment shown twice said the
    // same sentence twice, the second time in the wrong place.
    let documentation = signature["documentation"]["value"]
        .as_str()
        .unwrap_or_else(|| panic!("the documentation above the declaration: {answer}"));
    assert!(documentation.contains("Scales a count."), "{documentation}");
    assert!(
        !documentation.contains("@param"),
        "the parameter's own sentence is not repeated above the signature: {documentation}"
    );

    let parameter_documentation = signature["parameters"][0]["documentation"]["value"]
        .as_str()
        .unwrap_or_else(|| {
            panic!("`@param count the count` belongs to the first parameter: {answer}")
        });
    assert_eq!(parameter_documentation, "the count");
    assert_eq!(
        signature["parameters"][1]["documentation"],
        Value::Null,
        "a parameter with no `@param` line has no documentation rather than somebody else's: {answer}"
    );

    server.request(999, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}
/// The completion-resolve fixture: a documented member, offered through a member access.
const RESOLVE_CPP: &str = "\
struct Widget {
    /// The widget's size in cells.
    int size;
};
int f() {
    Widget w;
    w.
}
";

/// **`completionItem/resolve` fetches the documentation for the one item a client is showing.**
///
/// The list itself carries no comments — that is the point of the round trip, and why the list stays cheap for a
/// hundred names — so this test asks the two questions a client asks, in order: complete, then resolve the item the
/// user highlighted. What comes back is the declaration's own comment, rendered by the same function the hover and
/// the signature help use.
#[test]
fn a_completion_item_resolves_to_its_declarations_documentation() {
    let project = Project::new("completion-resolve");
    project.write("main.cpp", RESOLVE_CPP);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": RESOLVE_CPP }
        }),
    );

    let line = RESOLVE_CPP
        .lines()
        .position(|text| text.trim() == "w.")
        .expect("the fixture writes the access") as u64;
    let character = RESOLVE_CPP
        .lines()
        .nth(line as usize)
        .and_then(|text| text.find("w."))
        .expect("the fixture writes the access")
        + 2;

    let listed = server.ask_until_it(
        100,
        |id| {
            json!({
                "id": id,
                "method": "textDocument/completion",
                "params": {
                    "textDocument": { "uri": main_uri },
                    "position": { "line": line, "character": character },
                },
            })
        },
        |answer| {
            answer["result"]["items"]
                .as_array()
                .is_some_and(|items| items.iter().any(|item| item["label"] == json!("size")))
        },
    );

    let item = listed["result"]["items"]
        .as_array()
        .expect("an item list")
        .iter()
        .find(|item| item["label"] == json!("size"))
        .expect("the member is offered")
        .clone();

    // The item carries **where the declaration is** — the file and the name's offset — which is what a resolve is
    // asked with. A client echoes `data` back untouched; this test does the same.
    assert!(
        item["data"]["file"].is_string() && item["data"]["offset"].is_number(),
        "the item carries its declaration's identity: {item}"
    );
    assert!(
        item["documentation"].is_null(),
        "the list itself carries no comments: {item}"
    );

    let resolved = server.ask_until_it(
        200,
        |id| {
            json!({
                "id": id,
                "method": "completionItem/resolve",
                "params": item.clone(),
            })
        },
        |answer| !answer["result"]["documentation"].is_null(),
    );

    let documentation = resolved["result"]["documentation"]["value"]
        .as_str()
        .unwrap_or_else(|| panic!("markdown documentation was expected, got {resolved}"));
    assert!(
        documentation.contains("The widget's size in cells."),
        "the member's own comment: {documentation}"
    );
    assert_eq!(
        resolved["result"]["label"], "size",
        "and the item is the one that was asked about: {resolved}"
    );

    server.request(999, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}

///
/// Two reports, one card each:
///
/// * a class template's card used to show only the **declaration's** parameter names (`map<_Kty, _Ty, _Pr, _Alloc>`),
///   because it was rebuilt from the fact — while the reader is looking at `std::map<const char*, int, std::less<>>`
///   and asking what *that* is;
/// * `static const struct { … } priority[]` was answered `void[]`, because the anonymous class body contributed no
///   name and the specifier reader fell back to `void`. The honest answer is that this layer cannot spell the type,
///   and the card then shows the declaration's own text — which is the only place the reader can see it.
#[test]
fn a_hover_names_the_instantiation_and_never_invents_a_void() {
    let project = Project::new("hover-instantiation");
    project.write("map.h", INSTANTIATION_HEADER);
    project.write("main.cpp", INSTANTIATION_CPP);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));
    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": INSTANTIATION_CPP }
        }),
    );

    let instantiation = hover_over(
        &mut server,
        100,
        &main_uri,
        INSTANTIATION_CPP,
        "map<const char*, int, Less>",
    );
    let text = instantiation["result"]["contents"]["value"]
        .as_str()
        .unwrap_or_else(|| panic!("a markdown answer was expected, got {instantiation}"));
    assert!(
        text.contains("std::map<const char*, int, Less>"),
        "the use's own spelling, not the declaration's parameter names: {text}"
    );
    assert!(
        !text.contains("map<_Kty, _Ty"),
        "and not the shape the header declares: {text}"
    );

    let anonymous = hover_over(&mut server, 200, &main_uri, INSTANTIATION_CPP, "priority");
    let text = anonymous["result"]["contents"]["value"]
        .as_str()
        .unwrap_or_else(|| panic!("a markdown answer was expected, got {anonymous}"));
    assert!(
        !text.contains("void"),
        "an anonymous struct's variable is not `void`: {text}"
    );
    // **The card is generated, not the declaration's text.** It used to be the file's own spelling of the anonymous
    // struct — the only way to show `unsigned char` for a type with no name — and that is exactly the copy-paste the
    // card must not do: the type has no name to spell, so the card shows the name and says nothing it did not read.
    assert!(
        !text.contains("unsigned char"),
        "the card does not echo the struct's body: {text}"
    );
    assert!(
        text.contains("priority"),
        "and it is still about the name the cursor is on: {text}"
    );

    server.request(999, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}

/// The fixture for the two cards above: a class template declared in a **header** (the shape a real project has —
/// `map` is in `<map>`, not in the file being edited) used with arguments, and an anonymous class type.
const INSTANTIATION_HEADER: &str = "\
#pragma once
namespace std {
template <class _Kty, class _Ty, class _Less>
class map {
public:
    void insert(const _Kty& key, const _Ty& value);
};
}
";

const INSTANTIATION_CPP: &str = "\
#include \"map.h\"

std::map<const char*, int, Less> table;

static const struct
{
    unsigned char left;
    unsigned char right;
} priority[] = { { 1, 2 } };
";

/// The hover fixture: a documented function, one with a plain comment above it, and a `this` in a member function.
const HOVER_CPP: &str = "\
/// Adds two counts.
/// @param a the first
/// @param b the second
int add(int a, int b);

// A note to the reader, which is not documentation.
int undocumented(int c);

struct Widget {
    int size;
    int scaled(int factor) const { return size * factor; }
    int go() const { return this->scaled(2); }
};
";

/// **Hover shows what the file wrote about a declaration — and only what it wrote as documentation.**
///
/// Three positions in one fixture, because the interesting part is the *boundary*: the documented declaration
/// carries its comment (its `@param`s rendered as a list, not as markers in a paragraph — see
/// `render_documentation`), the one under a plain `//` comment
/// carries none — a `// TODO` dressed as an interface description is the failure the parser's own classification
/// exists to prevent — and `this`, which names no declaration at all, is answered by the expression question
/// instead: the class it points at.
#[test]
fn hover_shows_the_documentation_and_refuses_a_plain_comment() {
    let project = Project::new("hover");
    project.write("main.cpp", HOVER_CPP);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": HOVER_CPP }
        }),
    );

    let documented = hover_over(&mut server, 100, &main_uri, HOVER_CPP, "add(int a, int b);");
    let text = documented["result"]["contents"]["value"]
        .as_str()
        .unwrap_or_else(|| panic!("a markdown answer was expected, got {documented}"));
    assert!(
        text.contains("Adds two counts."),
        "the comment above the declaration is the documentation: {text}"
    );
    assert!(
        text.contains("**`a`** — the first") && text.contains("**`b`** — the second"),
        "each parameter is a list item, named and described: {text}"
    );
    assert!(
        !text.contains("@param"),
        "and the markers are no longer in the text: {text}"
    );
    assert!(
        text.contains("add(int a, int b)"),
        "with the declaration itself: {text}"
    );

    let plain = hover_over(
        &mut server,
        200,
        &main_uri,
        HOVER_CPP,
        "undocumented(int c);",
    );
    let text = plain["result"]["contents"]["value"]
        .as_str()
        .unwrap_or_else(|| panic!("a markdown answer was expected, got {plain}"));
    assert!(
        !text.contains("A note to the reader"),
        "a plain `//` comment is not documentation: {text}"
    );
    assert!(
        text.contains("undocumented(int c)"),
        "the declaration is still what the hover is about: {text}"
    );

    let this = hover_over(&mut server, 300, &main_uri, HOVER_CPP, "this->scaled(2)");
    let text = this["result"]["contents"]["value"]
        .as_str()
        .unwrap_or_else(|| panic!("a markdown answer was expected for `this`, got {this}"));
    assert!(
        text.contains("enclosing class `Widget`"),
        "`this` names no declaration, so the expression question answers: {text}"
    );

    server.request(999, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}

/// **A hover on the last member of a chain reads the chain, not its head.**
///
/// `win->w_buffer->fnum`: the object of the access is `win->w_buffer`, and the *first* byte of that text is the `w`
/// of `win` — a node whose type is `win_T*`. The hover asked `members_of("win_T*")` for `fnum`, which is not a member
/// of `win_T` at all, and said so:
///
/// ```text
/// `win_T*` has no member `fnum`
///
/// `win->w_buffer` is a `win_T*`.
/// ```
///
/// Measured on neovim's `src/nvim/arglist.c` (`win->w_buffer->b_fnum`; `struct file_buffer` declares the field the
/// macro `#define b_fnum handle` renames). The last byte of the object is past the base name, so the node it sits in
/// is the chain itself and its type is `buf_T*` — which is the object's real type and what the answer has to use.
#[test]
fn a_hover_on_the_last_member_of_a_chain_reads_the_chain() {
    const FIXTURE: &str = "\
typedef struct { int fnum; } buf_T;
typedef struct { buf_T *w_buffer; int other; } win_T;
int f(win_T *win) { return win->w_buffer->fnum; }
";
    let project = Project::new("hover-chain");
    project.write("main.c", FIXTURE);

    let mut server = Server::start(project.root());
    let uri = uri_of(&project.root().join("main.c"));

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": uri, "languageId": "c", "version": 1, "text": FIXTURE }
        }),
    );

    // **Inside the member's name**, not on the `->` in front of it: a hover on the operator is a question about the
    // operator.
    let line = line_of(FIXTURE, "->w_buffer->fnum");
    let character = FIXTURE
        .lines()
        .nth(line as usize)
        .and_then(|text| text.find("fnum"))
        .expect("the fixture writes it")
        + 2;
    let answer = server.ask_until(100, |id| {
        json!({
            "id": id,
            "method": "textDocument/hover",
            "params": {
                "textDocument": { "uri": uri },
                "position": { "line": line, "character": character },
            },
        })
    });
    let text = answer["result"]["contents"]["value"]
        .as_str()
        .unwrap_or_else(|| panic!("a markdown answer was expected, got {answer}"));
    assert!(
        !text.contains("has no member"),
        "`fnum` is a member of the chain's type, so nothing may say otherwise: {text}"
    );
    assert!(
        text.contains("int"),
        "and the popup says what the member is: {text}"
    );

    server.request(999, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}

/// **A hover after an arrow reads the pointee's members**, the same reader the completion uses.
///
/// `h->load()` on a `Handle<Config>` is `Config::load`: the handle declares `T* operator->()`. The hover used to ask
/// `members_of` about the *written* type, so it looked `load` up in `Handle` — measured through the server on a real
/// project, "`std::shared_ptr<std::string>` has no member `c_str`" while the completion at the same cursor offered 187
/// members of `std::string`. `h.get()` must still answer with the handle's own member, which is why the pointee is
/// asked first and the handle second.
#[test]
fn a_hover_after_an_arrow_reads_the_pointees_members() {
    const FIXTURE: &str = "\
struct Config { void load(); };
template <class T>
struct Handle {
    T* operator->();
    T* get() const;
    void reset();
};
void f() {
    Handle<Config> h;
    h->load();
    h.get();
}
";
    let project = Project::new("hover_arrow");
    project.write("main.cpp", FIXTURE);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));
    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": FIXTURE }
        }),
    );

    let pointee = hover_at(&mut server, 100, &main_uri, FIXTURE, "h->load", 3);
    let text = pointee["result"]["contents"]["value"]
        .as_str()
        .unwrap_or_else(|| panic!("a markdown answer was expected, got {pointee}"));
    assert!(
        text.contains("Config") && text.contains("load"),
        "`h->load` is `Config::load`, through the handle's `operator->`: {text}"
    );

    let handle = hover_at(&mut server, 200, &main_uri, FIXTURE, "h.get", 2);
    let text = handle["result"]["contents"]["value"]
        .as_str()
        .unwrap_or_else(|| panic!("a markdown answer was expected, got {handle}"));
    assert!(
        text.contains("get") && text.contains("Handle"),
        "`h.get` is the handle's own member, asked second: {text}"
    );

    server.request(300, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}

/// **Hover on a UE member shows the reflection annotation it was written under.**
///
/// `UPROPERTY(EditAnywhere, Category = "Game")` is an empty macro: the tree has nothing of it, and the card a reader got
/// for a reflected member said only `bool bIsReady` — while the annotation is the whole reason the engine's build tool
/// does anything with the declaration. The fact carries it (read from the file's text), and the card shows it as the file
/// wrote it.
#[test]
fn hover_shows_the_unreal_reflection_annotation() {
    let project = Project::new("unreal-hover");
    project.write(".cppls.toml", "[unreal]\nenable = true\n");
    // **The macros come from a header, the way an engine's do** — the same shape the simulated engine has, and the one
    // this feature was measured on: the annotation is left standing in the file's own text, which is what the summary
    // reads, while the reading a compiler parses has it expanded away.
    project.write(
        "engine.h",
        "#pragma once\n\n#define UCLASS(...)\n#define UPROPERTY(...)\n#define GENERATED_BODY()\n",
    );
    const ACTOR_H: &str = "\
#include \"engine.h\"

UCLASS(Blueprintable)
class AMyActor
{
    GENERATED_BODY()

    UPROPERTY(EditAnywhere, Category = \"Game\")
    bool bIsReady = false;
};
";
    project.write("actor.h", ACTOR_H);

    let mut server = Server::start(project.root());
    let uri = uri_of(&project.root().join("actor.h"));
    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {},
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({ "textDocument": { "uri": uri, "languageId": "cpp", "version": 1, "text": ACTOR_H } }),
    );

    let hover = hover_at(&mut server, 100, &uri, ACTOR_H, "AMyActor", 1);
    let text = hover["result"]["contents"]["value"]
        .as_str()
        .unwrap_or_else(|| panic!("a markdown answer was expected, got {hover}"));
    assert!(
        text.contains("UCLASS(Blueprintable)"),
        "the annotation, as the file wrote it: {text}"
    );
    assert!(
        text.contains("AMyActor"),
        "and the declaration is still what the card is about: {text}"
    );

    server.request(200, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}
/// A hover whose position is the first byte of `needle` in the fixture — for a member name, which
/// [`hover_over`] cannot address (it hovers at the start of the line).
/// A hover whose position is `into` bytes into the **last** occurrence of `needle` — for a member name, which
/// [`hover_over`] cannot address (it hovers at the start of the line), searched from the end so a declaration
/// carrying the same text does not win.
fn hover_at(
    server: &mut Server,
    first_id: i64,
    uri: &str,
    fixture: &str,
    needle: &str,
    into: usize,
) -> Value {
    let at = fixture.rfind(needle).expect("the fixture writes it") + into;
    let before = &fixture[..at];
    let line: u64 = before
        .matches('\n')
        .count()
        .try_into()
        .expect("a fixture this size fits in a u32");
    let character: u64 = before
        .rsplit('\n')
        .next()
        .unwrap_or_default()
        .chars()
        .count()
        .try_into()
        .expect("a line this size fits in a u32");
    server.ask_until(first_id, |id| {
        json!({
            "id": id,
            "method": "textDocument/hover",
            "params": {
                "textDocument": { "uri": uri },
                "position": { "line": line, "character": character },
            },
        })
    })
}

/// A hover whose position is the first character of the line containing `needle`.
fn hover_over(server: &mut Server, first_id: i64, uri: &str, fixture: &str, needle: &str) -> Value {
    let line = line_of(fixture, needle);
    let character = fixture
        .lines()
        .nth(line as usize)
        .and_then(|text| text.find(needle))
        .expect("the fixture writes it");

    server.ask_until(first_id, |id| {
        json!({
            "id": id,
            "method": "textDocument/hover",
            "params": {
                "textDocument": { "uri": uri },
                "position": { "line": line, "character": character },
            },
        })
    })
}

/// The line of a fixture that contains `needle`, counted from zero.
fn line_of(text: &str, needle: &str) -> u64 {
    text.lines()
        .position(|line| line.contains(needle))
        .unwrap_or_else(|| panic!("{needle:?} is not in the fixture"))
        .try_into()
        .expect("a fixture this size fits in a u32")
}

/// **The inlay fixture whose callee is in a header** — the shape a reported file has, and the one that makes the
/// refusal visible.
///
/// The fixture below declares `scale` in the same file it is called from, which hides the bug the refusal caused:
/// an edit drops that file's summary, so the analysis itself answers nothing until the drain, and a test cannot tell
/// "refused" from "honestly empty". A callee in a header is untouched by an edit to the file that calls it, so the
/// answer is available the whole time — and anything that suppresses it is then the only thing being measured.
const INLAY_HEADER: &str = "\
#pragma once
double scale(int count, double factor);
";

const INLAY_ACROSS_FILES: &str = "\
#include \"widget.h\"

double f(int count) {
    return scale(count, 1);
}
";

/// The inlay fixture: a call whose argument already spells the parameter, one that does not, and a member call.
const INLAY_CPP: &str = "\
double scale(int count, double factor);

struct Widget {
    int size_of(int scale) const;
};

double f(Widget& w, int count) {
    return scale(count, 1) + w.size_of(2);
}
";

/// **A parameter name is drawn at the argument — and not where the argument already says it.**
///
/// **The hints a person is actually looking at**: asked one turn after an edit, with the queue still busy.
///
/// This is the case that made the feature look broken, and the report was exact: *"as soon as I have edited the code
/// the inlay hints stop appearing"*. The handler answered `null` — not an empty list, a refusal — while
/// `Session::pending() > 0`, on the reasoning that a callee in a file nobody has read yet resolves to nothing. The
/// reasoning is right about the cause and wrong about the remedy: `parameter_hints` **skips** an unresolved callee,
/// so a filling index yields fewer hints and never a wrong one.
///
/// What that cost, measured on a 31-line file with four `#include`s: an edit leaves the queue busy for **~48 ms**,
/// question about the same file returns **4 hints on the file's own tokens with the index complete** — so the
/// reading was never the problem and the refusal was the whole of it.
/// two apart deliberately; it was removed with the rest of the scaffolding once the cause was found.
/// question about the same file returns **4 hints on the file's own tokens with the index complete** — so the
/// reading was never the problem and the refusal was the whole of it.
///
/// The ask here waits for **the first answer that is not a refusal**, and then edits and asks **once**, with no
/// retry: a retry would let the queue drain and measure the wrong thing.
///
/// # What this test does not prove, recorded because it was tried
///
/// It **passes with the refusal put back**. The notification and the request are two messages and the server drains
/// in between — the window is ~48 ms, and this test does not control the race. The instrument that does show the
/// in between — the window is ~48 ms, and this test does not control the race. The instrument that did show it
/// was a probe that held the two apart deliberately, and it was removed with the rest of the scaffolding.
/// reports the depth and the count together.
///
/// And even there one number is ambiguous, which is worth knowing before trusting it: for a fixture whose callees
/// are declared **in the edited file**, the analysis itself answers nothing until the drain, because the edit
/// dropped that file's summary — so "the refusal" and "the honest empty answer" read the same. The reported file is
/// the other shape: its calls are into headers (`std::format`, `printf`), whose declarations the edit did not
/// touch, so the analysis had the answer all along and only the refusal was hiding it.
#[test]
fn the_hints_survive_the_edit_that_asks_for_them() {
    let project = Project::new("inlay-hints-after-an-edit");
    project.write("widget.h", INLAY_HEADER);
    project.write("main.cpp", INLAY_ACROSS_FILES);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));
    let whole = json!({
        "start": { "line": 0, "character": 0 },
        "end": { "line": INLAY_ACROSS_FILES.lines().count(), "character": 0 },
    });

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": { "textDocument": { "inlayHint": {} } },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": {
                "uri": main_uri,
                "languageId": "cpp",
                "version": 1,
                "text": INLAY_ACROSS_FILES,
            }
        }),
    );

    // Settled first, so that what is measured below is the **edit** and not the initial index.
    let settled = server.ask_until_it(
        100,
        |id| {
            json!({
                "id": id,
                "method": "textDocument/inlayHint",
                "params": { "textDocument": { "uri": main_uri }, "range": whole },
            })
        },
        |answer| {
            answer["result"]
                .as_array()
                .is_some_and(|hints| !hints.is_empty())
        },
    );
    assert!(
        settled["result"]
            .as_array()
            .is_some_and(|hints| hints.len() == 1),
        "one argument that does not spell its parameter: {settled}"
    );

    // **One keystroke**, in a function body: no directive moves, so this is the cheapest edit there is — and it is
    // the one whose hint request used to be refused. The callee is in `widget.h`, which the edit does not touch, so
    // the analysis can answer immediately and nothing but a refusal can be suppressing it.
    let edited = INLAY_ACROSS_FILES.replace("return scale(count, 1);", "return scale(count, 1) ;");
    server.notify(
        "textDocument/didChange",
        json!({
            "textDocument": { "uri": main_uri, "version": 2 },
            "contentChanges": [{ "text": edited }],
        }),
    );

    let after = server.request(
        200,
        "textDocument/inlayHint",
        json!({ "textDocument": { "uri": main_uri }, "range": whole }),
    );
    let hints = after["result"]
        .as_array()
        .unwrap_or_else(|| panic!("**the hints were refused outright after an edit**: {after}"));
    assert_eq!(
        hints.len(),
        1,
        "an edit that moves no directive changes nothing a hint depends on, and the callee is in a header: {after}"
    );
}

/// Three arguments, two hints: `scale(count, …)` needs no `count:` in front of `count`, `1` is the second
/// parameter however it is spelled, and the member call's argument is named by the *member's* declaration rather
/// than by anything in the calling file.
///
/// The `ask_until` below is about the **index**, not about a refusal: this request is made before the workspace has
/// been read at all, when the callee genuinely has no declaration to take parameter names from, and the answer is an
/// empty list. It is the loop that gets it past that moment — see
/// [`the_hints_survive_the_edit_that_asks_for_them`] for the case that used to be answered with `null` instead.
#[test]
fn parameter_names_are_drawn_at_the_arguments() {
    let project = Project::new("inlay-hints");
    project.write("main.cpp", INLAY_CPP);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    let capabilities = server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    assert_eq!(
        capabilities["result"]["capabilities"]["inlayHintProvider"]["resolveProvider"],
        json!(false),
        "the client is told the server hints, and that there is nothing to resolve: {capabilities}"
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": INLAY_CPP }
        }),
    );

    let call_line = line_of(INLAY_CPP, "return scale(count, 1)");
    let answer = server.ask_until(100, |id| {
        json!({
            "id": id,
            "method": "textDocument/inlayHint",
            "params": {
                "textDocument": { "uri": main_uri },
                "range": {
                    "start": { "line": 0, "character": 0 },
                    "end": { "line": INLAY_CPP.lines().count(), "character": 0 },
                },
            },
        })
    });

    let hints = answer["result"]
        .as_array()
        .unwrap_or_else(|| panic!("an inlay hint list was expected, got {answer}"));
    let seen: Vec<(u64, String)> = hints
        .iter()
        .map(|hint| {
            (
                hint["position"]["line"].as_u64().expect("a line"),
                hint["label"].as_str().expect("a label").to_string(),
            )
        })
        .collect();

    assert_eq!(
        seen,
        vec![
            (call_line, "factor:".to_string()),
            (call_line, "scale:".to_string()),
        ],
        "`count` spells its parameter and gets no hint; the other two do: {answer}"
    );

    // The position is on the argument itself and the padding is after the label, so a client draws `factor: 1`
    // rather than `factor :1`.
    let factor = &hints[0];
    let argument = INLAY_CPP
        .lines()
        .nth(call_line as usize)
        .and_then(|line| line.find("scale(count, 1)"))
        .expect("the fixture writes the call")
        + "scale(count, ".len();
    assert_eq!(
        factor["position"]["character"],
        json!(argument),
        "the hint sits on the argument: {factor}"
    );
    assert_eq!(factor["paddingRight"], json!(true), "{factor}");
    assert_eq!(factor["kind"], json!(2), "a parameter hint: {factor}");

    server.request(999, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}

/// An overloaded name answers with **every** location, which is the shape a client shows as a peek list.
///
/// One name covering several declarations is ordinary C++ — `find` in `std::basic_string` is seventeen of them in
/// MSVC's library — and `null` for all of them is a dead end for the reader. What must *not* happen is the other
/// mistake: a name with one declaration still answers `Scalar`, so nothing about the common case changes.
/// **The overload a call means is marked in the hover list.**
///
/// Hover on a name with several declarations answers with every signature, because that is what a reader on a callee is
/// asking. It used to say, in as many words, that *which* one the call means was not decided here — and now it is: the
/// resolver the checks and the signature popup share picks one, and the chosen line is the one with `→`.
/// **The chosen template overload is shown instantiated.**
///
/// `take(T* value)` is what the declaration says; `take(int* value)` is what this call means, and a reader who sees only
/// the first cannot tell that the analysis deduced anything. The substitution is whole-word, so `T` does not reach into
/// a longer name.
/// **The chosen template overload is shown instantiated** — `take(int* value)` rather than `take(T* value)`.
///
/// Two rules had to exist before this could pass: the template arguments are deduced from the call and substituted
/// (§12, §19), and two templates that deduce to the same types are settled by **partial ordering** — `T*` is more
/// specialized than `T` (§22). No `→` at all was the earlier measurement: without the names the candidates tie, and a
/// tie is `Ambiguous`.
#[test]
fn the_chosen_template_overload_is_shown_instantiated() {
    const TAKE_H: &str =
        "template <typename T> void take(T* value);\ntemplate <typename T> void take(T value);\n";
    const TAKE_CPP: &str =
        "#include \"take.h\"\nint g() { int n = 0; int* p = &n; take(p); return 0; }\n";

    let project = Project::new("hover-template-overloads");
    project.write("take.h", TAKE_H);
    project.write("main.cpp", TAKE_CPP);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": TAKE_CPP }
        }),
    );

    let hovered = hover_over(&mut server, 100, &main_uri, TAKE_CPP, "take(p)");
    let text = hovered["result"]["contents"]["value"]
        .as_str()
        .unwrap_or_else(|| panic!("a markdown answer was expected, got {hovered}"));

    assert!(
        text.contains("→ "),
        "an overload is marked as what the call means: {text}"
    );
    assert!(
        text.lines()
            .any(|line| line.trim_start().starts_with("→ ") && line.contains("int* value")),
        "and it is shown instantiated — `take(int* value)` rather than `take(T* value)`: {text}"
    );
}
/// **A hover on a call shows only the declarations that call can reach.**
///
/// Reported from an editor: hovering `append` in `result_str.append(x)` drew **nine** `basic_string::append`
/// declarations, several of which cannot accept one argument at all. The arity rule asked only "no more arguments than
/// parameters" — a longer list *may* have defaults — so every two- and three-parameter overload survived it. The
/// defaulted count is in the declaration's own `parameter_list` spelling, which the hover holds, so it is counted now.
///
/// The fixture separates the two results the resolution can give: `f(1)` has exact types for the one- and two-parameter
/// overloads, and "fewer parameters used is better" then selects `f(int)`, so **one** line is printed; `g(unknown)`
/// makes the argument's type unknown, so the two one-parameter overloads tie and **both** are printed — and the
/// two-parameter `g` is not, which is what the arity filter is for.
#[test]
fn a_hover_on_a_call_shows_only_the_declarations_it_can_reach() {
    const SHAPES_H: &str = "\
struct S {
    void f(int a);
    void f(int a, int b = 0);
    void f(int a, int b, int c);

    void g(int a);
    void g(long a);
    void g(int a, int b);
};
";
    const SHAPES_CPP: &str = "\
#include \"shapes.h\"
void h(S s) {
    s.f(1);
    s.g(unknown_name);
}
";

    let project = Project::new("hover-viable-overloads");
    project.write("shapes.h", SHAPES_H);
    project.write("main.cpp", SHAPES_CPP);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": SHAPES_CPP }
        }),
    );

    let hovered = hover_over(&mut server, 100, &main_uri, SHAPES_CPP, "f(1)");
    let text = hovered["result"]["contents"]["value"]
        .as_str()
        .unwrap_or_else(|| panic!("a markdown answer was expected, got {hovered}"));
    assert!(
        text.contains("void f(int a)") && text.contains("S::f"),
        "the call selects the one-parameter overload, and the card is that member's own: {text}"
    );
    assert!(
        !text.contains("int b"),
        "and the overloads that need more arguments are not shown: {text}"
    );

    let hovered = hover_over(&mut server, 200, &main_uri, SHAPES_CPP, "g(unknown_name)");
    let text = hovered["result"]["contents"]["value"]
        .as_str()
        .unwrap_or_else(|| panic!("a markdown answer was expected, got {hovered}"));
    assert!(
        text.contains("void g(int a)") && text.contains("void g(long a)"),
        "both one-parameter overloads accept an unknown argument: {text}"
    );
    assert!(
        !text.contains("int a, int b"),
        "the two-parameter overload cannot take one argument: {text}"
    );
}

/// **The overload a call means is marked in the list, and the mark is the argument's choice.**
///
/// **The overload a call means is the first location `textDocument/definition` answers.**
///
/// The protocol allows a list and a client shows it in order, so the first entry is what a reader who does not pick gets
/// — and for a call that should be the declaration its arguments select. The three declarations are one per line in the
/// header, so the line number of the first location says which one was chosen: `parse(1)` must lead with line 0,
/// `parse("x")` with line 1.
#[test]
fn the_definition_of_a_call_leads_with_the_overload_it_means() {
    const OVERLOADS_H: &str =
        "int parse(int value);\nint parse(const char* text);\nint parse(double value);\n";
    const OVERLOADS_CPP: &str = "#include \"overloads.h\"\nint f() { return parse(1); }\n";

    let project = Project::new("definition-overloads-order");
    project.write("overloads.h", OVERLOADS_H);
    project.write("main.cpp", OVERLOADS_CPP);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": OVERLOADS_CPP }
        }),
    );

    // The cursor goes to `parse` in the call, and the request is repeated until the header has been read — the index is
    // lazy on purpose.
    let line = OVERLOADS_CPP
        .lines()
        .position(|line| line.contains("parse(1)"))
        .unwrap_or_default();
    let character = OVERLOADS_CPP
        .lines()
        .nth(line)
        .and_then(|text| text.find("parse"))
        .unwrap_or_default();

    let mut first_line = None;
    for attempt in 0..40 {
        let answer = server.request(
            100 + attempt,
            "textDocument/definition",
            json!({
                "textDocument": { "uri": main_uri },
                "position": { "line": line, "character": character },
            }),
        );
        let locations = answer["result"].as_array().cloned().unwrap_or_default();
        if locations.len() > 1 {
            first_line = locations[0]["range"]["start"]["line"].as_u64();
            break;
        }
    }

    assert_eq!(
        first_line,
        Some(0),
        "an `int` argument leads with `int parse(int value);`, which is line 0 of the header"
    );
}
#[test]
fn the_overload_a_call_means_is_marked_in_the_hover_list() {
    const OVERLOADS_H: &str = "int parse(int value);\nint parse(const char* text);\n";
    const OVERLOADS_CPP: &str = "#include \"overloads.h\"\nint f() { return parse(1); }\n";

    let project = Project::new("hover-overloads");
    project.write("overloads.h", OVERLOADS_H);
    project.write("main.cpp", OVERLOADS_CPP);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": OVERLOADS_CPP }
        }),
    );

    let hovered = hover_over(&mut server, 100, &main_uri, OVERLOADS_CPP, "parse(1)");
    let text = hovered["result"]["contents"]["value"]
        .as_str()
        .unwrap_or_else(|| panic!("a markdown answer was expected, got {hovered}"));

    assert!(
        text.contains("→ "),
        "the overload this call means is marked: {text}"
    );
    let marked = text
        .lines()
        .find(|line| line.trim_start().starts_with("→ "))
        .unwrap_or_default()
        .to_string();
    assert!(
        marked.contains("int value"),
        "and it is the `int` one, because the argument is an `int`: {marked:?} of\n{text}"
    );
}
#[test]
fn an_overload_set_answers_with_every_location() {
    const OVERLOADS_H: &str =
        "int parse(int value);\nint parse(const char* text);\nint parse(double value);\n";
    const OVERLOADS_CPP: &str = "#include \"overloads.h\"\nint f() { return parse(1); }\n";

    let project = Project::new("definition-overloads");
    project.write("overloads.h", OVERLOADS_H);
    project.write("main.cpp", OVERLOADS_CPP);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));
    let header_uri = uri_of(&project.root().join("overloads.h"));

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": OVERLOADS_CPP }
        }),
    );

    // The cursor is inside `parse` on line 1 — `int f() { return parse(1); }` — and the request is repeated until
    // the header has been read, for the reason every query here is: the index is lazy on purpose.
    let answer = server.ask_until_it(
        100,
        |id| {
            json!({
                "id": id,
                "method": "textDocument/definition",
                "params": {
                    "textDocument": { "uri": main_uri },
                    "position": { "line": 1, "character": 20 },
                },
            })
        },
        |response| {
            response["result"]
                .as_array()
                .is_some_and(|locations| locations.len() == 3)
        },
    );

    let locations = answer["result"]
        .as_array()
        .unwrap_or_else(|| panic!("three declarations, three locations: {answer}"));

    assert_eq!(locations.len(), 3);
    for (index, location) in locations.iter().enumerate() {
        assert_eq!(
            location["uri"],
            json!(header_uri),
            "all three are in the header: {location}"
        );
        assert_eq!(
            location["range"]["start"]["line"],
            json!(index),
            "one per line, in the order the header writes them: {answer}"
        );
    }

    // A name with **one** declaration is still `Scalar`: the common case does not change shape, which is what lets
    // a client that predates lists keep working.
    let single = server.request(
        200,
        "textDocument/definition",
        json!({
            "textDocument": { "uri": main_uri },
            "position": { "line": 1, "character": 4 },
        }),
    );
    assert!(
        single["result"]["uri"].is_string(),
        "`f` is declared on this line, and one declaration is one location: {single}"
    );

    server.request(999, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}

/// The fixture for [`a_completion_inside_a_macros_argument_is_about_that_argument`]: a macro whose second argument is
/// where the cursor goes, and two types with one member each so that a wrong subject is visible in the list.
const MACRO_ARGUMENT_CPP: &str = "\
struct alpha { int one; };
struct beta { int gamma; };

#define PICK(first, second) pick_impl((first), (second))

beta bet;

int f() {
    return PICK(1, bet.);
}
";

/// **A cursor inside a macro's argument list is still a cursor in the code.**
///
/// A view is of the **rendering** — the file with its macros replaced — so a position a client sends has to be
/// translated into the reading before anything is resolved. A macro invocation is where that translation is hardest
/// and where getting it wrong is invisible: `PICK(1, bet.)` becomes something else entirely in the rendering, and a
/// mapping that dropped the cursor at the invocation's start rather than inside the argument would still produce a
/// completion list — of the wrong scope, at the wrong place, with no error anywhere to say so.
///
/// The criterion is that the **argument's own type** is what is offered. `bet` is a `beta` and the file also holds
/// an `alpha`, so a list holding `one` is a list answering about some other expression.
#[test]
fn a_completion_inside_a_macros_argument_is_about_that_argument() {
    let project = Project::new("completion-in-a-macro-argument");
    project.write("main.cpp", MACRO_ARGUMENT_CPP);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": { "textDocument": { "completion": {} } },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": MACRO_ARGUMENT_CPP }
        }),
    );

    // The cursor is right after `bet.` inside `PICK(1, bet.)` — a member access whose subject is a macro argument.
    // Line 8 is `    return PICK(1, bet.);` and column 23 is the byte after the dot: the first version of this test
    // asked at line 9, which is the closing brace, and the server answered a name completion for `}` — a correct
    // answer to a question about the wrong place, which is the failure mode this test exists to catch and which it
    // caught in itself first.
    let answer = server.ask_until(100, |id| {
        json!({
            "id": id,
            "method": "textDocument/completion",
            "params": {
                "textDocument": { "uri": main_uri },
                "position": { "line": 8, "character": 23 },
            },
        })
    });

    let items = answer["result"]["items"]
        .as_array()
        .or_else(|| answer["result"].as_array())
        .unwrap_or_else(|| panic!("a completion list was expected, got {answer}"));
    let labels: Vec<&str> = items
        .iter()
        .filter_map(|item| item["label"].as_str())
        .collect();

    assert!(
        labels.contains(&"gamma"),
        "the members of the argument's own type are offered: {labels:?}"
    );
    assert!(
        !labels.contains(&"one"),
        "and not the members of the other type in the same file: {labels:?}"
    );
}

/// The fixture for [`a_signature_survives_being_inside_a_macro_argument`]: a real declaration, a call to it, and the
/// whole call written as a macro's argument so that the reading the server parses has been rewritten around it.
const SIGNATURE_IN_A_MACRO_CPP: &str = "\
#define PICK(first, second) pick_impl((first), (second))

/// Scales a count.
int scale(int count, double factor);

int f() {
    return PICK(1, scale(2, ));
}
";

/// **The signature popup survives being inside a macro's argument.**
///
/// The same seam [`a_completion_inside_a_macros_argument_is_about_that_argument`] tests, asked by the other handler
/// that takes a cursor: signature help resolves the call around the offset out of the **rendering**, and the
/// rendering is where `PICK(1, scale(2, ))` has been rewritten into something with the call still in it but at a
/// different offset. A mapping that landed the cursor on the macro's own name, or on the first argument, would ask
/// about a different call — `pick_impl` here — and either answer nothing or answer with the wrong signature.
///
/// What has to come back is `scale`'s own label and its second parameter active, which is the state a reader sees
/// while typing the argument.
#[test]
fn a_signature_survives_being_inside_a_macro_argument() {
    let project = Project::new("signature-in-a-macro");
    project.write("main.cpp", SIGNATURE_IN_A_MACRO_CPP);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": { "textDocument": { "signatureHelp": {} } },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": SIGNATURE_IN_A_MACRO_CPP }
        }),
    );

    // `    return PICK(1, scale(2, ));` is line 6, and column 28 is right after the comma of `scale`'s arguments.
    let answer = server.ask_until_it(
        100,
        |id| {
            json!({
                "id": id,
                "method": "textDocument/signatureHelp",
                "params": {
                    "textDocument": { "uri": main_uri },
                    "position": { "line": 6, "character": 28 },
                },
            })
        },
        |answer| !answer["result"].is_null(),
    );

    let signatures = answer["result"]["signatures"]
        .as_array()
        .unwrap_or_else(|| panic!("a signature list was expected, got {answer}"));
    let labels: Vec<&str> = signatures
        .iter()
        .filter_map(|signature| signature["label"].as_str())
        .collect();
    assert!(
        labels.iter().any(|label| label.contains("scale")),
        "the signature of the call the cursor is in, not of the macro around it: {labels:?}"
    );
    assert!(
        !labels.iter().any(|label| label.contains("PICK")),
        "and not the macro's own name: {labels:?}"
    );
    assert_eq!(
        answer["result"]["activeParameter"],
        json!(1),
        "the second argument is the one being typed: {answer}"
    );
}

/// **What the popup says, for every shape a declaration comes in** — printed, not asserted.
///
/// A hover is the one answer a reader judges by how it *looks*, and no assertion states that well. This exists so
/// the shapes can be read side by side while the rendering is being changed: a template, a member function with a
/// body, a documented class, a variable the file gave no type to, and a member of a class template from another
/// file. Ignored by default — run it with `--ignored --nocapture`.
#[test]
#[ignore = "a reading aid: it prints popups rather than checking them"]
fn what_the_popups_look_like() {
    let project = Project::new("hover-shapes");
    project.write(
        "box.h",
        "#pragma once\n\
         /// A box that holds one `T`.\n\
         ///\n\
         /// The documentation is the file's own words.\n\
         template <class T>\n\
         class Box {\n\
         public:\n\
             /// What is in the box.\n\
             T get() const { return v; }\n\
             T v;\n\
         };\n",
    );
    project.write(
        "main.cpp",
        "#include \"box.h\"\n\
         \n\
         int main() {\n\
             auto n = 1;\n\
             Box<int> b;\n\
             b.v = n;\n\
             return 0;\n\
         }\n",
    );

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));
    let main_text = "#include \"box.h\"\n\nint main() {\n    auto n = 1;\n    Box<int> b;\n    b.v = n;\n    \
                     return 0;\n}\n";

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": { "textDocument": { "hover": {} } },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": main_text }
        }),
    );

    // (line, character, what is being hovered) — 0-based, as a client sends them.
    let asked: [(u64, u64, &str); 5] = [
        (
            3,
            9,
            "the local `n`, whose type is an `auto` the file wrote",
        ),
        (
            4,
            4,
            "`Box` in `Box<int> b;` — a class template from a header",
        ),
        (5, 6, "the member `v` of that class template"),
        (4, 13, "the variable `b`, whose type is that class template"),
        (1, 4, "`main` itself, a function this file defines"),
    ];

    for (line, character, what) in asked {
        let mut answer = server.ask_until_it(
            100,
            |id| {
                json!({
                    "id": id,
                    "method": "textDocument/hover",
                    "params": {
                        "textDocument": { "uri": main_uri },
                        "position": { "line": line, "character": character },
                    },
                })
            },
            |answer| !answer["result"].is_null(),
        );
        // Asked more than once so the server has had the turns it needs to read the file the way a client that
        // waited gets it — see the note in the coordinate test above.
        for _ in 0..4 {
            answer = server.ask_until_it(
                100,
                |id| {
                    json!({
                        "id": id,
                        "method": "textDocument/hover",
                        "params": {
                            "textDocument": { "uri": main_uri },
                            "position": { "line": line, "character": character },
                        },
                    })
                },
                |answer| !answer["result"].is_null(),
            );
        }
        let markdown = answer["result"]["contents"]["value"]
            .as_str()
            .unwrap_or("<no popup>")
            .to_string();
        println!("=== {line}:{character} — {what} ===\n{markdown}\n");
    }
}

/// **A declaration's own line, when the file it is in is the file being read.**
///
/// The tooltip's last line is `file:line:column`, and the line is the one part of this server that can be wrong
/// without anything looking broken: a fact about a declaration in **another** file carries that file's offsets,
/// while a fact about a declaration in **the file being viewed** comes from the view's own tree — whose offsets are
/// the **rendering's**, because the rendering is what the parser was handed, and whose line numbers are therefore
/// short by however many `#include` and `#define` lines the directives took out.
///
/// Measured on a real report: a class on line 6 of a file with five `#include`s above it was announced as
/// `main.cpp:1:7` — **the column right and the line five short**, which is exactly the number of lines between them.
/// The existing hover test cannot catch it: its declaration is in a header, so it takes the other branch.
///
/// The criterion is the line and the column together, because the column is what was right in the report — a test
/// that only checked "which file" would pass on the broken answer.
#[test]
fn a_declaration_in_the_viewed_file_is_reported_on_its_own_line() {
    let project = Project::new("hover-coordinates");
    // Five lines of directives above the class, so a rendering that drops them is five lines short — the number in
    // the report, and the number that makes the difference visible rather than rounded away.
    project.write(
        "main.cpp",
        "#include <vector>\n\
         #include <string>\n\
         #include <format>\n\
         #include <iostream>\n\
         \n\
         class Sux {\n\
         public:\n\
             void print() {}\n\
         };\n\
         \n\
         int main() {\n\
             Sux sux;\n\
             return 0;\n\
         }\n",
    );

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": { "textDocument": { "hover": {} } },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": {
                "uri": main_uri,
                "languageId": "cpp",
                "version": 1,
                "text": "#include <vector>\n#include <string>\n#include <format>\n#include <iostream>\n\n\
                         class Sux {\npublic:\n    void print() {}\n};\n\nint main() {\n    Sux sux;\n    \
                         return 0;\n}\n",
            }
        }),
    );

    // **Asked until the file has been read the way a client that waited gets it.**
    //
    // `Session::view` answers from the file's own tokens until a rendering exists and builds it for the next query —
    // a deliberate cost, because a rendering cannot be built behind an `&self`. In that first reading every offset is
    // the file's, so both readers below agree by accident and a test that asked once would pass on the broken answer.
    // Measured: with the fix disabled this test still passed, which is what sent it back here.
    let mut answer = server.ask_until_it(
        100,
        |id| {
            json!({
                "id": id,
                "method": "textDocument/hover",
                "params": {
                    "textDocument": { "uri": main_uri },
                    "position": { "line": 11, "character": 4 },
                },
            })
        },
        |answer| !answer["result"].is_null(),
    );
    for _ in 0..4 {
        answer = server.ask_until_it(
            100,
            |id| {
                json!({
                    "id": id,
                    "method": "textDocument/hover",
                    "params": {
                        "textDocument": { "uri": main_uri },
                        "position": { "line": 11, "character": 4 },
                    },
                })
            },
            |answer| !answer["result"].is_null(),
        );
    }

    let markdown = answer["result"]["contents"]["value"]
        .as_str()
        .unwrap_or_else(|| panic!("a hover was expected, got {answer}"));
    println!("--- the popup about `Sux` ---\n{markdown}\n---");
    assert!(
        markdown.contains("main.cpp:6:7"),
        "the class is written on line 6, column 7 — not on a line measured in the rendering: {markdown}"
    );
    // **And the popup's own text, read at the fact's offsets.** Those offsets are the rendering's, so reading the
    // file's bytes at them lands wherever the directives had taken lines out: measured on the same report, a popup
    // about `main` began with `tream>`, the tail of `#include <iostream>`, because the four `#include`s above `main`
    // had moved it 60 bytes. The line *number* was right by then — the two are separate readers and this is the one
    // that was still wrong.
    assert!(
        markdown.contains("class Sux"),
        "the declaration as it is written, not the bytes at that offset in another document: {markdown}"
    );
    assert!(
        !markdown.contains("tream>"),
        "and no fragment of an `#include` line: {markdown}"
    );
}

/// **The reported file itself, asked at every position a cursor sits in** — printed rather than asserted.
///
/// A report in three sentences: *"completion outside a namespace is gone too, and the inlay hints no longer appear
/// at all"*. The server's own log agrees that the member path declined for both positions it names — a plain name
/// and a qualifier are not member accesses, so that part is correct — and that the index held 157 files with **0
/// queued**. So whatever completion answered, it answered from a complete index, and a wrong answer here is the
/// handler's rather than the analysis's.
///
/// A list of a hundred names and an empty list need different fixes, and no assertion states which one came back.
#[test]
#[ignore = "a reading aid for a reported file"]
fn what_the_completion_answers_here() {
    // **The file is named by the reader, not by this test.** It used to be a path on one machine, which made the test
    // a no-op everywhere else *and* put somebody's home directory in the repository. `CPPLS_REPORTED_FILE` is the same
    // idea the other probes use: the file a report was about, and a skip when it is not given.
    let Ok(named) = std::env::var("CPPLS_REPORTED_FILE") else {
        println!("skipped: no CPPLS_REPORTED_FILE (the file a completion report was about)");
        return;
    };
    let Ok(source) = std::fs::read_to_string(&named) else {
        println!("skipped: {named} is not on this machine");
        return;
    };

    let project = Project::new("completion-report");
    project.write("main.cpp", &source);
    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": { "textDocument": { "completion": {} } },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": source }
        }),
    );

    // **Every position a cursor can be typed at**, which is the survey a "completion is gone" report needs: the
    // handler's own log had already said the member path declined for the two positions it named — correctly, since
    // a plain name and a qualifier are not member accesses — so what is missing is *which* positions come back
    // empty, and a list of them is the finding.
    let mut asked: Vec<(u64, u64)> = Vec::new();
    for (number, line) in source.lines().enumerate() {
        let line = line.trim_end();
        for (column, _) in line.char_indices() {
            let at = &line[..column];
            let ends = at.chars().last().is_some_and(|last| {
                last.is_alphanumeric() || last == '_' || last == ':' || last == '.'
            });
            if ends {
                asked.push((number as u64, column as u64));
            }
        }
    }
    for (number, character) in asked {
        let number = number as usize;
        let body = source.lines().nth(number).unwrap_or("").trim_end();

        let answer = server.request(
            100 + number as i64,
            "textDocument/completion",
            json!({
                "textDocument": { "uri": main_uri },
                "position": { "line": number, "character": character },
            }),
        );
        let items = match &answer["result"] {
            Value::Array(items) => items.len(),
            Value::Object(object) => object["items"].as_array().map(Vec::len).unwrap_or(0),
            _ => 0,
        };
        let first: Vec<&str> = match &answer["result"] {
            serde_json::Value::Array(items) => items
                .iter()
                .filter_map(|i| i["label"].as_str())
                .take(8)
                .collect(),
            serde_json::Value::Object(o) => o["items"]
                .as_array()
                .map(|a| {
                    a.iter()
                        .filter_map(|i| i["label"].as_str())
                        .take(8)
                        .collect()
                })
                .unwrap_or_default(),
            _ => Vec::new(),
        };
        println!(
            "{number:>3}: {:<40} -> {items} item(s): {first:?}",
            body.trim()
        );
    }
}
/// **A probe, not a test: what does the real project's server do to the CPU after it has settled?**
///
/// Reported from the outside before this existed: after the index burst and the workspace diagnostic pass, `cpp_ls`
/// held **exactly one core** — 2.00 s of CPU per 2.00 s of wall clock, flat, for as long as it was watched. A curve
/// that flat is not work being finished; it is something being scheduled again.
///
/// The reason it needs the harness rather than a hand-written script is the protocol's other direction: the server
/// **asks the client** for things (`window/workDoneProgress/create` while a pass reports progress), and a client that
/// never answers leaves it waiting instead of working — measured, two hand-written runs sat at 5 s of CPU for five
/// minutes because indexing never began. This pump answers, so the server reaches the state worth watching.
///
/// It is `#[ignore]`d because it drives the real project for four minutes and asserts nothing; run it by hand and
/// watch the process from outside:
///
/// ```text
/// cargo test --release -p cpp_ls --test handshake probe_the_cpu_shape -- --ignored --nocapture
/// ```
#[test]
#[ignore = "a probe, run by hand: four minutes on the real project, and it asserts nothing"]
fn probe_the_cpu_shape_of_the_real_project() {
    let root = std::path::Path::new(r"E:\EmmyLuaCodeStyle");

    let mut server = Server::start(root);
    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(root),
            "capabilities": {
                "textDocument": { "diagnostic": {}, "hover": {} },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    server.notify("initialized", json!({}));

    let started = Instant::now();
    let mut answered = 0;
    while started.elapsed() < Duration::from_secs(240) {
        while let Ok(message) = server.messages.try_recv() {
            let is_a_request = message.get("method").is_some() && message.get("id").is_some();
            if is_a_request {
                server.answer(&message);
                answered += 1;
            }
        }

        std::thread::sleep(Duration::from_millis(50));
    }

    println!("the client answered {answered} request(s) from the server while it worked");

    // **What the loop was saying while it spun.** The pump's own `debug!` lines are the only channel that names
    // which file would not leave the queue, and the harness keeps the server's stderr for exactly this kind of
    // question. Counted rather than printed whole: a loop that runs a hundred thousand times says the same thing.
    let log = server.log.lock().expect("the log is not poisoned").clone();
    let lines: Vec<&str> = log.lines().collect();
    println!("the server logged {} line(s); the last 30:", lines.len());
    for line in lines.iter().rev().take(30).rev() {
        println!("  {line}");
    }

    let mut repeated: std::collections::BTreeMap<String, usize> = std::collections::BTreeMap::new();
    for line in &lines {
        let shape = line
            .split_whitespace()
            .take(8)
            .collect::<Vec<_>>()
            .join(" ");
        *repeated.entry(shape).or_insert(0) += 1;
    }
    let mut worst: Vec<(String, usize)> = repeated.into_iter().collect();
    worst.sort_by_key(|entry| std::cmp::Reverse(entry.1));
    println!("the most repeated line shapes:");
    for (shape, count) in worst.iter().take(8) {
        println!("  {count:>7} x {shape}");
    }
}

/// **A hover on a member resolves through the object's type, and says so when it cannot.**
///
/// The shape from a real editor session: `auto z = std::vector<int>();` then `z.push_back(…)` and `z.append(…)`. The
/// first must name `push_back` on the vector; the second must say the member is absent rather than answer with the nine
/// `basic_string::append` overloads that the name query finds in a standard library the project has read.
///
/// This is a handshake test rather than a unit one because `hover` is written against `Session<DiskFiles>` — the
/// provider a server uses — so the honest way to exercise it is through a server.
#[test]
fn a_member_hover_is_resolved_through_the_objects_type() {
    let project = Project::new("member-hover");
    let source = "\
namespace std {
template <class T>
class vector {
public:
    void push_back(T value);
};
}
void f() {
    auto z = std::vector<int>();
    z.push_back(1);
    z.append(2);
}
";
    project.write("a.cpp", source);
    let mut server = Server::start(project.root());
    let a_uri = uri_of(&project.root().join("a.cpp"));
    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {},
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": a_uri, "languageId": "cpp", "version": 1, "text": source }
        }),
    );

    let line_of = |needle: &str| -> u32 {
        source
            .lines()
            .position(|line| line.contains(needle))
            .expect("the fixture has the line") as u32
    };
    // **Asked until it answers.** A hover before the project has been read is `null` — the analysis has no view yet —
    // and a well-behaved client asks again as it types; asserting the first answer would be asserting the machine's
    // speed rather than the server's behaviour.
    let mut hover_on = |id: i64, line: u32, character: u32| -> serde_json::Value {
        let uri = a_uri.clone();
        server.ask_until_it(
            id,
            move |_asked| {
                json!({
                    "method": "textDocument/hover",
                    "params": {
                        "textDocument": { "uri": uri },
                        "position": { "line": line, "character": character },
                    },
                })
            },
            |response| !response["result"].is_null(),
        )
    };

    // `z.push_back` — the member, on the type the `auto` initialiser gave it.
    let member = hover_on(2, line_of("z.push_back"), 6);
    let text = member["result"]["contents"]["value"]
        .as_str()
        .unwrap_or_else(|| panic!("a hover is expected: {member}"))
        .to_string();
    assert!(
        text.contains("push_back"),
        "the member is the answer: {text}"
    );

    // `z.append` — absent, said plainly, and **not** another class's member.
    let absent = hover_on(3, line_of("z.append"), 6);
    let text = absent["result"]["contents"]["value"]
        .as_str()
        .unwrap_or_else(|| panic!("a hover is expected: {absent}"))
        .to_string();
    assert!(
        text.contains("no member `append`") || text.contains("not known here"),
        "an absent member is answered honestly: {text}"
    );
    assert!(
        !text.contains("basic_string"),
        "and never with another class's members: {text}"
    );
}

/// **A macro**的 hover 显示的是它自己的 `#define` 行,而不是一段无关的代码。
///
/// 报告来自编辑器:悬停 `#define STD std::` 里的 `STD` 时,弹窗里是**一大段 `main` 的函数体**。
/// 原因是坐标用错了地方:事实(`DeclFact`/`MacroFact` 的 range)按**文件**坐标记录,而当时的实现拿它去切
/// **渲染**(指令和注释都已被删掉,长度短得多),于是偏移落到了程序中间,再往后切到 body 的末尾。
///
/// 断言两件事,因为两件都是这个 bug 的两面:弹窗**包含** `#define STD std::`,且**不含**任何 `int main`。
#[test]
fn a_macro_hover_shows_its_own_define_line() {
    let project = Project::new("macro-hover");
    let source = "#define FULL_NAME_FORMAT \"Full name: {}\"\n#define STD std::\n\nint main() {\n    STD c;\n    return 0;\n}\n";
    project.write("main.cpp", source);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": { "textDocument": { "hover": {} } },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": source }
        }),
    );

    // The **use** of `STD` on line 4 (0-based), which is where a reader hovers to ask what it stands for.
    let hovered = server.ask_until(100, |id| {
        json!({
            "id": id,
            "method": "textDocument/hover",
            "params": {
                "textDocument": { "uri": main_uri },
                "position": { "line": 4, "character": 5 },
            },
        })
    });

    let value = hovered["result"]["contents"]["value"]
        .as_str()
        .unwrap_or_else(|| panic!("the macro has a popup: {hovered}"));
    println!("hover: {value}");
    assert!(
        value.contains("#define STD std::"),
        "the popup is the macro's own definition line: {value}"
    );
    assert!(
        !value.contains("int main"),
        "and not a slice of the program starting somewhere else: {value}"
    );

    server.request(999, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}
/// **The call hierarchy over the wire**: prepare on a caller, then the two directions.
///
/// The three requests are a path through the dispatcher that no unit test covers — `prepareCallHierarchy` was asked on a
/// real project and the server **never answered**, so the plumbing is what this test is for.
#[test]
fn the_call_hierarchy_answers_over_the_wire() {
    let project = Project::new("call_hierarchy");
    project.write(
        "base.h",
        "int add(int a, int b);\nint subtract(int a, int b);\n",
    );
    let main = "#include \"base.h\"\n\
                int both(int a, int b) {\n    return add(a, b) + subtract(a, b);\n}\n";
    project.write("main.cpp", main);

    let mut server = Server::start(project.root());
    let main_uri = uri_of(&project.root().join("main.cpp"));

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": { "textDocument": { "callHierarchy": {} } },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": main_uri, "languageId": "cpp", "version": 1, "text": main },
        }),
    );

    // **Inside the name**: `position_of` answers the position *after* the needle, so the needle ends at the `(` and two
    // characters back is the `h` of `both`.
    let (line, character) = position_of(main, "both(");
    let prepared = server.request(
        2,
        "textDocument/prepareCallHierarchy",
        json!({
            "textDocument": { "uri": main_uri },
            "position": { "line": line, "character": character - 2 },
        }),
    );
    println!("prepare: {prepared}");
    let item = prepared["result"]
        .as_array()
        .and_then(|items| items.first())
        .cloned()
        .unwrap_or_else(|| panic!("the function is a call hierarchy item: {prepared}"));
    assert_eq!(item["name"], "both");

    let incoming = server.request(3, "callHierarchy/incomingCalls", json!({ "item": item }));
    println!("incoming: {incoming}");
    assert!(
        !incoming["result"].is_null(),
        "the request is answered: {incoming}"
    );

    let outgoing = server.request(4, "callHierarchy/outgoingCalls", json!({ "item": item }));
    println!("outgoing: {outgoing}");
    let names: Vec<&str> = outgoing["result"]
        .as_array()
        .map(|calls| {
            calls
                .iter()
                .filter_map(|call| call["to"]["name"].as_str())
                .collect()
        })
        .unwrap_or_default();
    assert!(names.contains(&"add"), "{names:?}");
    assert!(names.contains(&"subtract"), "{names:?}");
}
/// **A request whose params do not parse gets an answer.** The protocol's is `InvalidParams`; before this the request
/// produced **no response at all** — the dispatcher fell out of its arm, logged nothing, and a client waited for ever
/// (measured with a `prepareCallHierarchy` whose `position` was nested one level too deep: the probe hung, and every
/// request after it queued behind the same silence).
///
/// A malformed request is a client bug, but silence turns it into a server that looks hung.
#[test]
fn a_request_with_unreadable_params_is_answered_with_invalid_params() {
    let project = Project::new("invalid_params");
    project.write("main.cpp", "int main() { return 0; }\n");

    let mut server = Server::start(project.root());
    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {},
        }),
    );
    server.notify("initialized", json!({}));

    let uri = uri_of(&project.root().join("main.cpp"));
    // `position` is a *position*, not a `{ textDocument, position }` object — the shape a client gets wrong.
    let answer = server.request(
        2,
        "textDocument/prepareCallHierarchy",
        json!({
            "textDocument": { "uri": uri },
            "position": { "position": { "line": 0, "character": 4 } },
        }),
    );
    println!("answer: {answer}");
    assert_eq!(
        answer["error"]["code"].as_i64().map(|code| code as i32),
        Some(lsp_server::ErrorCode::InvalidParams as i32),
        "an unreadable request is InvalidParams, not silence: {answer}"
    );
}
/// **A CUDA project, over the wire**: the completion list carries CUDA's vocabulary and the popup explains it.
///
/// The two features are one question asked twice — *is this project CUDA?* — and the answer decides both, so both are
/// asserted here against a project that says so in its own file. The vocabulary is not the language server's to
/// invent: `__global__` is an identifier to the lexer (a legal variable name in C++) and a specifier to `nvcc`, which
/// makes the *family* the switch rather than the spelling.
#[test]
fn a_cuda_project_completes_its_vocabulary_and_explains_it() {
    let project = Project::new("cuda-vocabulary");
    // **The project's own word about itself.** `enable` is what a machine without `nvcc` needs; the toolkit is not
    // installed here either, which is the point: `threadIdx` is answered from the table rather than from a header.
    project.write(".cppls.toml", "[compile.cuda]\nenable = true\n");
    let source = "__global__ void add(float *out) {\n    unsigned i = threadIdx.x;\n    __dev\n}\n";
    project.write("kernels.cu", source);
    let uri = uri_of(&project.root().join("kernels.cu"));

    let mut server = Server::start(project.root());
    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": { "window": { "workDoneProgress": true } },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": uri, "languageId": "cuda-cpp", "version": 1, "text": source }
        }),
    );

    // **The popup on a built-in variable**: asked until the index has read the file, because a hover that arrives
    // first is legitimately null. The needle stops *inside* the word — `position_of` answers the offset past it, and
    // past `threadIdx` is the `.`, whose token is punctuation and whose popup is nothing.
    let (line, character) = position_of(source, "threadId");
    let hover = server.ask_until(100, |id| {
        json!({
            "id": id,
            "method": "textDocument/hover",
            "params": { "textDocument": { "uri": uri }, "position": { "line": line, "character": character } }
        })
    });
    let text = hover["result"]["contents"]["value"]
        .as_str()
        .unwrap_or_default();
    assert!(
        text.contains("threadIdx"),
        "the popup says what `threadIdx` is: {text:?}"
    );

    // **The completion list on a prefix**: `__dev` has one answer, and it is offered with its description.
    let (line, character) = position_of(source, "__dev");
    let completion = server.ask_until(200, |id| {
        json!({
            "id": id,
            "method": "textDocument/completion",
            "params": {
                "textDocument": { "uri": uri },
                "position": { "line": line, "character": character },
                "context": { "triggerKind": 1 }
            }
        })
    });
    let items = completion["result"]["items"]
        .as_array()
        .or_else(|| completion["result"].as_array())
        .expect("a completion list");
    let labels: Vec<&str> = items
        .iter()
        .filter_map(|item| item["label"].as_str())
        .collect();
    assert!(
        labels.contains(&"__device__"),
        "a CUDA project completes `__device__`: {labels:?}"
    );

    let shutdown = server.request(500, "shutdown", Value::Null);
    assert_eq!(shutdown["result"], Value::Null);
    server.notify("exit", Value::Null);
    assert!(server.wait_for_exit());
}

/// **The other half of the switch**: the same word in a project that is not CUDA is a name, and nothing is offered.
///
/// No `.cppls.toml` and no `nvcc` in a database means `config.cuda()` is false, and then `__global__` declares nothing
/// — which is what a project that has never seen `nvcc` should be told.
#[test]
fn a_cpp_project_is_not_offered_cuda_vocabulary() {
    let project = Project::new("cuda-vocabulary-off");
    let source = "__global__ void add(float *out) { }\n";
    project.write("kernels.cu", source);
    let uri = uri_of(&project.root().join("kernels.cu"));

    let mut server = Server::start(project.root());
    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": { "window": { "workDoneProgress": true } },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": uri, "languageId": "cpp", "version": 1, "text": source }
        }),
    );

    let (line, character) = position_of(source, "__glo");
    let completion = server.ask_until(100, |id| {
        json!({
            "id": id,
            "method": "textDocument/completion",
            "params": {
                "textDocument": { "uri": uri },
                "position": { "line": line, "character": character },
                "context": { "triggerKind": 1 }
            }
        })
    });
    let items = completion["result"]["items"]
        .as_array()
        .cloned()
        .or_else(|| completion["result"].as_array().cloned())
        .expect("a completion list");
    assert!(
        !items
            .iter()
            .any(|item| item["label"].as_str() == Some("__global__")),
        "a project that is not CUDA is not offered CUDA's vocabulary"
    );

    let shutdown = server.request(500, "shutdown", Value::Null);
    assert_eq!(shutdown["result"], Value::Null);
    server.notify("exit", Value::Null);
    assert!(server.wait_for_exit());
}

/// **A hover inside a format string explains the bytes under the cursor.**
///
/// The other thing a reader points at that no declaration describes: `%zu` is a `size_t` in decimal, `{:.3f}` is
/// fixed-point with three digits, and the only place a reader is already looking is the line of code. The words come
/// from `ormat::describe` — the module that decides which bytes are a *piece* — so the explanation cannot
/// disagree with the colouring.
///
/// Three assertions, in the order the feature is built:
///
/// ```text
///   inside a printf conversion       the type it converts, and the flags/width/precision beside it
///   inside a std::format field       the specification's own parts
///   inside a plain string            nothing — a string is not a format string unless a call says it is
/// ```
#[test]
fn a_hover_inside_a_format_string_explains_the_part_it_is_on() {
    const FIXTURE: &str = "\
#include <cstdio>
struct width { int value; };
void f(double d, int n) {
    std::printf(\"%-8.2f|%zu\", d, n);
    const char *plain = \"not a format string %d\";
    (void)plain;
}
";
    let project = Project::new("hover-format");
    project.write("main.cpp", FIXTURE);

    let mut server = Server::start(project.root());
    let uri = uri_of(&project.root().join("main.cpp"));

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": uri, "languageId": "cpp", "version": 1, "text": FIXTURE }
        }),
    );

    // **A position on a byte of a spelling**, found in the fixture rather than counted.
    let at = |needle: &str, within: usize| -> (u32, u32) {
        let line = line_of(FIXTURE, needle);
        let offset = FIXTURE
            .lines()
            .nth(line as usize)
            .and_then(|text| text.find(needle))
            .unwrap_or_else(|| panic!("the fixture writes {needle:?}"))
            + within;
        (line as u32, offset as u32)
    };
    let ask = |server: &mut Server, id: i64, (line, character): (u32, u32)| -> String {
        let answer = server.ask_until(id, |id| {
            json!({
                "id": id,
                "method": "textDocument/hover",
                "params": {
                    "textDocument": { "uri": uri },
                    "position": { "line": line, "character": character },
                },
            })
        });
        answer["result"]["contents"]["value"]
            .as_str()
            .unwrap_or_default()
            .to_string()
    };

    // Inside the `f` of `%.2f` — the conversion, and the sentence a reader wants.
    let text = ask(&mut server, 100, at("%-8.2f", 5));
    assert!(
        text.contains("fixed-point decimal"),
        "the conversion's meaning: {text:?}"
    );

    // Inside the width: the grammar's own words for the numbers in front of the letter.
    let text = ask(&mut server, 101, at("%-8.2f", 2));
    assert!(
        text.contains("width") && text.contains('8'),
        "the width: {text:?}"
    );
    assert!(
        text.contains("left-aligned"),
        "and the flag before it: {text:?}"
    );

    // A string that no call passes anywhere is not a format string, so there is no popup for its `%d`.
    let text = ask(&mut server, 102, at("not a format string", 17));
    assert!(
        !text.contains("conversion"),
        "a string nothing formats is left to the reader: {text:?}"
    );

    server.request(999, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}

/// **A completion inside a format string offers the grammar, and only the grammar.**
///
/// `printf("%5.` is followed by a conversion letter and by nothing else, so the language's own list — the names in
/// scope — is a list of things that cannot be written there. The request is asked at three positions that are one
/// character apart and the answers differ because the grammar does:
///
/// ```text
///   printf("%|")     every conversion, with what each one means
///   printf("%5.|")   the same, after the precision
///   printf("%d|")    nothing, and *nothing* is the answer — not the names in scope
/// ```
///
/// The third is the one that matters: a fall-through to the ordinary list there is the defect this branch exists to
/// prevent, and a client that received it would show `printf`, `n`, `main` inside a format string.
#[test]
fn a_completion_inside_a_format_string_is_the_grammar_s_own() {
    const FIXTURE: &str = "\
#include <cstdio>
struct width { int value; };
void f(double d, int n) {
    std::printf(\"%5.\", d);
}
";
    let project = Project::new("completion-format");
    project.write("main.cpp", FIXTURE);

    let mut server = Server::start(project.root());
    let uri = uri_of(&project.root().join("main.cpp"));

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
                "textDocument": { "completion": { "completionItem": { "snippetSupport": true } } },
            },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": uri, "languageId": "cpp", "version": 1, "text": FIXTURE }
        }),
    );

    // **The cursor goes just before the closing quote**, which is where a conversion belongs: `"%5.` has its width and
    // its precision and is waiting for the letter.
    let line = line_of(FIXTURE, "%5.");
    let character = FIXTURE
        .lines()
        .nth(line as usize)
        .and_then(|text| text.find("%5."))
        .expect("the fixture writes it")
        + 3;
    let ask = |server: &mut Server, id: i64| -> Vec<Value> {
        let answer = server.ask_until(id, |id| {
            json!({
                "id": id,
                "method": "textDocument/completion",
                "params": {
                    "textDocument": { "uri": uri },
                    "position": { "line": line, "character": character },
                },
            })
        });
        answer["result"]["items"]
            .as_array()
            .or_else(|| answer["result"].as_array())
            .cloned()
            .unwrap_or_else(|| panic!("a completion list was expected, got {answer}"))
    };

    let items = ask(&mut server, 100);
    assert!(!items.is_empty(), "a conversion list was expected");
    let labels: Vec<&str> = items
        .iter()
        .filter_map(|item| item["label"].as_str())
        .collect();
    for conversion in ["d", "f", "s", "x", "p"] {
        assert!(
            labels.contains(&conversion),
            "`{conversion}` is a conversion: {labels:?}"
        );
    }
    assert!(
        !labels.contains(&"printf"),
        "and the names in scope are not offered here: {labels:?}"
    );
    // The item says what the conversion does, which is the reason the list is worth showing at all.
    let fixed = items
        .iter()
        .find(|item| item["label"] == json!("f"))
        .expect("`f` is in the list");
    assert!(
        fixed["detail"]
            .as_str()
            .is_some_and(|detail| detail.contains("fixed-point")),
        "the one-line meaning: {fixed}"
    );

    server.request(999, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}

/// **A C project's macro questions, asked the way the editor asks them** — the four a reader reported.
///
/// ```c
/// #ifdef __STDC_VERSION__                          hover: nothing at all
/// #define CORPUS_STANDARD __STDC_VERSION__         hover on the name: nothing at all
/// #endif
/// #define SUM(count, ...) (impl)(count __VA_OPT__(, ) __VA_ARGS__)
/// int use(void) { return SUM(total, 1, 2, 3); }    go to definition: nothing at all
/// _Static_assert(sizeof(int) >= 2, "…");           hover: nothing at all
/// ```
///
/// Each row is a question the *editor* asked and got nothing for. The analysis behind them is not missing — a macro's
/// `#define` is in the summary, and `_Static_assert` is a spelling the vocabulary can describe — so every failure here
/// is a handler that did not ask, and that is what this test measures. It runs against a real server over stdio because
/// the reported symptom is "no hover in the editor", and a session-level test cannot see a handler that never runs.
#[test]
fn the_c_macro_questions_the_editor_asks_are_answered() {
    let project = Project::new("macro-questions");
    project.write("macros.c", MACROS_C);

    let mut server = Server::start(project.root());
    let uri = uri_of(&project.root().join("macros.c"));
    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": uri, "languageId": "c", "version": 1, "text": MACROS_C }
        }),
    );

    // **One shot per row**: the file is read by `prepare`, and a macro question is answered from that file's own
    // summary — a retry loop here would spin for the whole timeout on a row that is broken, and the first row's
    // failure is what this test exists to name.
    let hover_at = |server: &mut Server, id: i64, needle: &str| -> Value {
        let line = line_of(MACROS_C, needle);
        let character = MACROS_C
            .lines()
            .nth(line as usize)
            .and_then(|text| text.find(needle))
            .expect("the fixture writes it");
        server.request(
            id,
            "textDocument/hover",
            json!({
                "textDocument": { "uri": uri },
                "position": { "line": line, "character": character },
            }),
        )
    };

    // **A macro the compiler predefines**, in a directive's condition.
    let predefined = hover_at(&mut server, 100, "__STDC_VERSION__");
    let text = predefined["result"]["contents"]["value"]
        .as_str()
        .unwrap_or_else(|| panic!("`__STDC_VERSION__` has a hover: {predefined}"));
    assert!(
        text.contains("predefined") && text.contains("__STDC_VERSION__"),
        "the compiler defines it, and the card says so: {text}"
    );

    // **A macro at its own definition.**
    let definition = hover_at(&mut server, 200, "CORPUS_STANDARD");
    let text = definition["result"]["contents"]["value"]
        .as_str()
        .unwrap_or_else(|| panic!("`CORPUS_STANDARD` has a hover at its definition: {definition}"));
    assert!(
        text.contains("CORPUS_STANDARD"),
        "the card names the macro: {text}"
    );

    // **`_Static_assert`,** which is a contextual spelling rather than a keyword.
    let assertion = hover_at(&mut server, 300, "_Static_assert");
    let text = assertion["result"]["contents"]["value"]
        .as_str()
        .unwrap_or_else(|| panic!("`_Static_assert` has a hover: {assertion}"));
    assert!(
        text.contains("_Static_assert") && text.contains("compile time"),
        "the card explains the construct: {text}"
    );

    // **Go to definition on a macro use**, which is a *translation order* question rather than a name lookup.
    let line = line_of(MACROS_C, "SUM(selected, 1, 2, 3)");
    let character = MACROS_C
        .lines()
        .nth(line as usize)
        .and_then(|text| text.find("SUM"))
        .expect("the fixture writes the call");
    let jumped = server.ask_until(400, |id| {
        json!({
            "id": id,
            "method": "textDocument/definition",
            "params": {
                "textDocument": { "uri": uri },
                "position": { "line": line, "character": character },
            },
        })
    });
    let location = if jumped["result"].is_array() {
        jumped["result"][0].clone()
    } else {
        jumped["result"].clone()
    };
    assert_eq!(
        location["uri"].as_str().map(|found| found == uri),
        Some(true),
        "a macro's definition is the `#define` in this file: {jumped}"
    );
    assert_eq!(
        location["range"]["start"]["line"].as_u64(),
        Some(line_of(MACROS_C, "#define SUM(")),
        "and the line it names is the directive's: {jumped}"
    );

    server.request(999, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}

/// The fixture: a predefined macro in a directive, a macro defined and used, and a C11 keyword construct.
const MACROS_C: &str = "\
#ifdef __STDC_VERSION__
#define CORPUS_STANDARD __STDC_VERSION__
#else
#define CORPUS_STANDARD 0L
#endif

#define SUM(count, ...) (impl)(count __VA_OPT__(, ) __VA_ARGS__)

int impl(int count, ...);

int use(void) {
    int total = 0;
    int selected = 2;
    int n = SUM(selected, 1, 2, 3);
    _Static_assert(sizeof(int) >= 2, \"an int is at least two bytes\");
    return n + total;
}
";

/// **The three things a C reader asks of a line they are writing** — completion of a name the file itself defines,
/// completion inside a macro call, and the signature of a standard-library function.
///
/// ```c
/// #include <stdio.h>
/// #define LOCAL_MACRO(n) ((n) + 1)
/// static int local_helper(int n) { return n; }
/// int main(void) {
///     int value = local_helper(1);
///     fprintf(stdout, "%d\n", value);      signature help at the `(`
///     return LOCAL_MACRO(value);           completion after `LOCAL_`
/// }
/// ```
///
/// Reported together: *"当前文件定义的内容几乎都无法补全, 但是 hover 和跳转都照得到"* and *"fprintf 没有
/// signatureHelper"*. Hover and go-to-definition working while completion answers nothing is a **handler** question
/// rather than an analysis one — the three queries share the file's view and the offset — so both are asked here, over
/// stdio, at the positions the report names.
#[test]
fn a_c_reader_gets_completion_and_signature_help_for_what_the_file_defines() {
    let project = Project::new("c-completion");
    project.write("main.c", C_COMPLETION_C);

    let mut server = Server::start(project.root());
    let uri = uri_of(&project.root().join("main.c"));
    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": uri, "languageId": "c", "version": 1, "text": C_COMPLETION_C }
        }),
    );

    let at = |needle: &str, after: usize| -> (u64, u64) {
        let line = line_of(C_COMPLETION_C, needle);
        let character = C_COMPLETION_C
            .lines()
            .nth(line as usize)
            .and_then(|text| text.find(needle))
            .expect("the fixture writes it")
            + after;
        (line, character as u64)
    };

    // **A name this file defines**, typed as far as `local_he`.
    let (line, character) = at("local_helper(1)", 7);
    let asked = server.ask_until(100, |id| {
        json!({
            "id": id,
            "method": "textDocument/completion",
            "params": {
                "textDocument": { "uri": uri },
                "position": { "line": line, "character": character },
            },
        })
    });
    let items = completion_items(&asked);
    let labels: Vec<&str> = items
        .iter()
        .filter_map(|item| item["label"].as_str())
        .collect();
    assert!(
        labels.contains(&"local_helper"),
        "a function the file defines completes: {} item(s), first {:?}",
        labels.len(),
        labels.iter().take(10).collect::<Vec<_>>()
    );

    // **The same, for a macro** — the row the report names as missing.
    let (line, character) = at("LOCAL_MACRO(value)", 6);
    let asked = server.ask_until(200, |id| {
        json!({
            "id": id,
            "method": "textDocument/completion",
            "params": {
                "textDocument": { "uri": uri },
                "position": { "line": line, "character": character },
            },
        })
    });
    let items = completion_items(&asked);
    let labels: Vec<&str> = items
        .iter()
        .filter_map(|item| item["label"].as_str())
        .collect();
    assert!(
        labels.contains(&"LOCAL_MACRO"),
        "a macro the file defines completes: {} item(s), first {:?}",
        labels.len(),
        labels.iter().take(10).collect::<Vec<_>>()
    );

    // **The empty-prefix list must still reach the names of a header that is not the first one.** Five standard
    // headers declare far more than the 200-item budget, so a first-come cut keeps only `<stdio.h>`'s `a`-`b` names and
    // `fprintf` is absent — which is what a reader sees as "completion does not work in this function". Measured through
    // the real server on the corpus: `fprintf: false` with 200 items before the budget was spent fairly.
    let (line, character) = at("fprintf(stdout", 8);
    let asked = server.ask_until(250, |id| {
        json!({
            "id": id,
            "method": "textDocument/completion",
            "params": {
                "textDocument": { "uri": uri },
                "position": { "line": line, "character": character },
            },
        })
    });
    let items = completion_items(&asked);
    assert!(
        items
            .iter()
            .any(|item| item["label"].as_str() == Some("fprintf")),
        "with nothing typed, the budget still reaches `fprintf`: {} item(s)",
        items.len()
    );

    // **`fprintf(`'s signature**, which comes from a header the file includes rather than from the file.
    let (line, character) = at("fprintf(stdout", 8);
    let asked = server.ask_until(300, |id| {
        json!({
            "id": id,
            "method": "textDocument/signatureHelp",
            "params": {
                "textDocument": { "uri": uri },
                "position": { "line": line, "character": character },
            },
        })
    });
    let signatures = asked["result"]["signatures"]
        .as_array()
        .cloned()
        .unwrap_or_default();
    assert!(
        !signatures.is_empty(),
        "`fprintf` has a signature to show: {asked}"
    );
    let label = signatures[0]["label"].as_str().unwrap_or_default();
    // **The parameter's spelling is the implementation's.** The claim is that the label is `fprintf`'s own
    // declaration — the one with a format parameter and a variadic tail — and not the file's `local_helper` or a
    // neighbour in `<stdio.h>`. How that parameter is *spelled* is not this server's: glibc writes `format`, MSVC's
    // UCRT writes `_Format`, and musl writes `__format`. Matching the lowercased label asks the question the test
    // means and answers the same on all three.
    let folded = label.to_lowercase();
    assert!(
        folded.contains("fprintf") && folded.contains("format"),
        "and it is `fprintf`'s own: {label}"
    );

    server.request(999, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}

/// A completion answer, whether the server sent a list or a bare array.
fn completion_items(answer: &Value) -> Vec<Value> {
    if let Some(items) = answer["result"]["items"].as_array() {
        return items.clone();
    }
    answer["result"].as_array().cloned().unwrap_or_default()
}

/// The fixture: a header the file includes, a macro, a static function, and a call of each.
const C_COMPLETION_C: &str = "\
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>

#define LOCAL_MACRO(n) ((n) + 1)

static int local_helper(int n) { return n; }

int main(void) {
    int value = local_helper(1);
    fprintf(stdout, \"%d\\n\", value);
    return LOCAL_MACRO(value);
}
";

/// **The first completion after a file is opened**, asked the way an editor asks it: one shot, no retry, at the
/// keystroke that follows `didOpen`.
///
/// Reported: *"我输入 f 还是没有补全,但是输入到 fp 的时候就有补全了"* — typing `f` shows nothing and typing `fp` works.
/// The two requests differ only in the prefix, so the difference has to be either the answer for `f` or the state the
/// server was in when it arrived; a test that retried either would hide both. So this asks **once** per prefix, in the
/// order a reader types them, and requires the same name from both.
#[test]
fn the_first_completion_after_an_open_answers_the_same_as_the_second() {
    let project = Project::new("c-first-completion");
    project.write("main.c", C_COMPLETION_C);

    let mut server = Server::start(project.root());
    let uri = uri_of(&project.root().join("main.c"));
    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {
                "workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
                "window": { "workDoneProgress": true },
            },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": uri, "languageId": "c", "version": 1, "text": C_COMPLETION_C }
        }),
    );

    // **`f`, then `fp`** — the two prefixes in the report, one shot each, at the same line.
    let line = line_of(C_COMPLETION_C, "fprintf(stdout");
    let labels_at = |server: &mut Server, id: i64, width: u32| -> Vec<String> {
        let character = C_COMPLETION_C
            .lines()
            .nth(line as usize)
            .and_then(|text| text.find("fprintf"))
            .expect("the fixture writes it") as u32
            + width;
        let answer = server.request(
            id,
            "textDocument/completion",
            json!({
                "textDocument": { "uri": uri },
                "position": { "line": line, "character": character },
            }),
        );
        let items = if let Some(items) = answer["result"]["items"].as_array() {
            items.clone()
        } else {
            answer["result"].as_array().cloned().unwrap_or_default()
        };
        items
            .iter()
            .filter_map(|item| item["label"].as_str().map(str::to_string))
            .collect()
    };

    let one = labels_at(&mut server, 100, 1);
    let two = labels_at(&mut server, 200, 2);

    assert!(
        one.iter().any(|label| label == "fprintf"),
        "the answer to `f` holds `fprintf` — {} item(s), first {:?}",
        one.len(),
        one.iter().take(8).collect::<Vec<_>>()
    );
    assert!(
        two.iter().any(|label| label == "fprintf"),
        "and so does the answer to `fp` — {} item(s)",
        two.len()
    );

    server.request(999, "shutdown", Value::Null);
    server.notify("exit", Value::Null);
}

/// **A documentation comment's symbol reference works end to end** — Rust's ``[`Widget::grow`]``, over the wire.
///
/// The three layers are tested apart (`cpp_parser::doc_links`, the analysis's colouring, and the two handlers), and
/// this is the one that says the pair an editor actually exercises — a hover and a jump — answer for a position
/// **inside a comment**, which is where every other declaration query in the server answers about the token *after*
/// it. It is also the check that the two handlers agree: both resolve the target with `ProjectIndex::definition`, so
/// a card that has a declaration and a jump that has none would be a defect this catches.
#[test]
fn a_documentation_link_hovers_and_jumps_over_the_wire() {
    const SOURCE: &str = "\
struct Widget {
    /// See [`Widget::grow`] for the rule.
    void grow(int by);
};
";
    let project = Project::new("doc-link");
    project.write("a.cpp", SOURCE);

    let mut server = Server::start(project.root());
    let uri = uri_of(&project.root().join("a.cpp"));

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": {},
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": uri, "languageId": "cpp", "version": 1, "text": SOURCE }
        }),
    );

    // `/// See [` is columns 0–9, so the target starts at character 10 on line 1.
    let hover = server.ask_until(100, |id| {
        json!({
            "id": id,
            "method": "textDocument/hover",
            "params": { "textDocument": { "uri": uri }, "position": { "line": 1, "character": 14 } },
        })
    });
    let card = hover["result"]["contents"]["value"]
        .as_str()
        .or_else(|| hover["result"]["contents"].as_str())
        .unwrap_or_else(|| panic!("a card was expected for the link, got {hover}"));
    assert!(
        card.contains("void grow(int by)"),
        "the card is the declaration the link names: {card}"
    );

    let location = server.ask_until(100, |id| {
        json!({
            "id": id,
            "method": "textDocument/definition",
            "params": { "textDocument": { "uri": uri }, "position": { "line": 1, "character": 14 } },
        })
    });
    assert!(
        location["result"]["uri"]
            .as_str()
            .is_some_and(|found| found.ends_with("a.cpp")),
        "the jump names the file that declares it: {location}"
    );
    assert_eq!(
        location["result"]["range"]["start"]["line"],
        json!(2),
        "and the line of the declaration, which is below the comment: {location}"
    );
    assert_eq!(
        location["result"]["range"]["start"]["character"],
        json!(9),
        "and the column of the name: {location}"
    );

    // --- and the colour ---------------------------------------------------------------------------
    //
    // A comment is trivia, so the token pass cannot find a link in the tree: the name is read from the file's own
    // text and resolved by spelling, and it arrives in the same delta-encoded stream as every other name. A client
    // that declares no `tokenTypes` is sent the server's whole legend, which is what this request relies on.
    let tokens = server.ask_until(100, |id| {
        json!({
            "id": id,
            "method": "textDocument/semanticTokens/full",
            "params": { "textDocument": { "uri": uri } },
        })
    });
    let data = tokens["result"]["data"]
        .as_array()
        .unwrap_or_else(|| panic!("a token stream was expected, got {tokens}"));

    // Decode the delta walk: five numbers per token — `deltaLine`, `deltaStart`, `length`, `type`, `modifiers`.
    let mut line = 0i64;
    let mut character = 0i64;
    let mut length_at_the_link = 0i64;
    let mut at_the_link = None;
    for token in data.chunks(5) {
        let delta_line = token[0].as_i64().unwrap_or(0);
        let delta_start = token[1].as_i64().unwrap_or(0);
        line += delta_line;
        character = if delta_line == 0 {
            character + delta_start
        } else {
            delta_start
        };
        if line == 1 && character == 14 {
            length_at_the_link = token[2].as_i64().unwrap_or(0);
            at_the_link = token[3].as_i64();
        }
    }
    assert_eq!(
        length_at_the_link,
        "Widget::grow".len() as i64,
        "the token covers exactly the name between the backticks: {data:?}"
    );
    assert!(
        at_the_link.is_some(),
        "and it starts where the target does (line 1, character 14): {data:?}"
    );
}

/// **A documentation comment's prose offers no code**, and its ``[`…`]`` offers names — asked over the wire.
///
/// Reported from an editor: typing in a `///` comment produced the file's classes and functions as completions.
/// The answer has to be "nothing" in prose — a comment is not a place a C++ name goes — while a symbol reference is
/// exactly the place one does, which is why the two positions are asked separately here.
#[test]
fn a_documentation_comment_offers_code_only_inside_a_link() {
    const SOURCE: &str = "\
struct Widget { int grow; };
/// Hello w
/// See [`Wid
void f() {}
";
    let project = Project::new("doc-complete");
    project.write("a.cpp", SOURCE);

    let mut server = Server::start(project.root());
    let uri = uri_of(&project.root().join("a.cpp"));

    server.request(
        1,
        "initialize",
        json!({
            "processId": std::process::id(),
            "rootUri": uri_of(project.root()),
            "capabilities": { "textDocument": { "completion": { "completionItem": { "snippetSupport": false } } } },
        }),
    );
    server.notify("initialized", json!({}));
    server.notify(
        "textDocument/didOpen",
        json!({
            "textDocument": { "uri": uri, "languageId": "cpp", "version": 1, "text": SOURCE }
        }),
    );

    // --- prose: `/// Hello w` — the cursor is at the end of the line ------------------------------------------
    let prose = server.ask_until(100, |id| {
        json!({
            "id": id,
            "method": "textDocument/completion",
            "params": { "textDocument": { "uri": uri }, "position": { "line": 1, "character": 11 } },
        })
    });
    let empty: Vec<serde_json::Value> = Vec::new();
    let items = prose["result"]["items"].as_array().unwrap_or(&empty);
    assert!(
        items.is_empty(),
        "a comment's prose is not a place a code name goes, and this offered {} item(s): {:?}",
        items.len(),
        items
            .iter()
            .filter_map(|item| item["label"].as_str())
            .take(8)
            .collect::<Vec<_>>()
    );

    // --- inside the link: `/// See [`Wid` — a name belongs here --------------------------------
    let link = server.ask_until_it(
        100,
        |id| {
            json!({
                "id": id,
                "method": "textDocument/completion",
                "params": { "textDocument": { "uri": uri }, "position": { "line": 2, "character": 13 } },
            })
        },
        |response| {
            response["result"]["items"]
                .as_array()
                .is_some_and(|items| items.iter().any(|item| item["label"] == json!("Widget")))
        },
    );
    let items = link["result"]["items"]
        .as_array()
        .cloned()
        .unwrap_or_default();
    assert!(
        items.iter().any(|item| item["label"] == json!("Widget")),
        "a symbol reference completes the project's names: {link}"
    );
    // …and it completes **names**, not statements: a link takes a symbol, and a snippet is not one.
    for snippet in ["class", "dowhile", "forr", "function"] {
        assert!(
            !items.iter().any(|item| item["label"] == json!(snippet)),
            "`{snippet}` is a snippet, and a reference wants a name: {link}"
        );
    }
}