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
|
//! A real Language Server Protocol client: child processes spoken to over
//! JSON-RPC 2.0 with `Content-Length` framing. Nothing here knows any single
//! language — `specs` is a table of (binary, languageId, extensions, root
//! markers), and zls, rust-analyzer, clangd and gopls are rows in it: every
//! language pardes answers questions about.
//!
//! THE PROCESS LIFECYCLE IS THE DESIGN. `lsp.query` is a synchronous call on a
//! worker thread, and a language server costs tens of milliseconds to start
//! and MINUTES to index a large workspace. So a server is spawned lazily on
//! the first query that needs it, kept for the life of the editor, and each
//! spec gets at most one — `conns[i]` guards itself with an `Io.Mutex`
//! because a canceled query can still be inside `run` when the next arrives.
//! Every wait is an `Io` cancelation point: a shell cancels the worker of a
//! query it no longer wants, and the worker stops there.
//!
//! ONE READER THREAD PER SERVER, and it is not optional. The first design
//! pumped the socket only while a query waited, which works for a server that
//! only ever answers. A real server TALKS: rust-analyzer streams `$/progress`
//! for the whole minutes-long index of a big workspace, publishes diagnostics
//! it was never asked for, and asks its own `workspace/configuration`
//! questions mid-flight. The reader owns the read side of the socket, routes
//! responses to the one waiting query (a mailbox under the conn's mutex),
//! answers server-to-client requests so the server never blocks on us, feeds
//! the diagnostics store, and narrates state changes through `status sink` —
//! the shell posts them to `Pardes.setMessage`, so "rust-analyzer indexing 45%"
//! lands on the same transient message row a save narrates into. The reader is
//! also the ONLY closer of its socket fd: teardown calls `shutdown(2)` and the
//! reader closes on the EOF it then reads, so the fd number cannot be recycled
//! under a thread still polling it.
//!
//! Nothing here may wedge the editor:
//! - every write is bounded by a deadline, and every mailbox wait by a
//! deadline or, while the server narrates progress, by cancelation,
//! - a query the server does not answer in time returns no rows and sends
//! `$/cancelRequest`; the server is NOT killed for being busy (an indexing
//! server is busy for minutes and the status row says so) — but three
//! consecutive timeouts mean wedged, and wedged is killed and respawned,
//! - the transport is an AF_UNIX socketpair, so a dead server answers EPIPE
//! from `send(MSG_NOSIGNAL)` instead of killing pardes with SIGPIPE
//! (ignoring SIGPIPE process-wide would be inherited by every pty shell we
//! fork and would change what `yes | head` does in a pane),
//! - a binary missing from PATH costs one cached probe, disables the spec
//! for the session, and says so ONCE on the message row.
//!
//! Position encoding is negotiated to utf-8 and the SERVER'S ANSWER is
//! believed, not our request; the utf-16 conversion is implemented in both
//! directions for servers that refuse (`Req.offset` is a byte offset, and a
//! misconverted column is wrong on every line with non-ASCII in it).
const std = @import("std");
const builtin = @import("builtin");
const libc = std.c;
const lsp = @import("lsp.zig");
const Scip = @import("Scip.zig");
extern "c" fn execv(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int;
extern "c" fn usleep(usec: c_uint) c_int;
extern "c" fn atexit(f: *const fn () callconv(.c) void) c_int;
// test-only libc (the seam's own tests build a real directory tree)
extern "c" fn mkdtemp(template: [*:0]u8) ?[*:0]u8;
extern "c" fn system(cmd: [*:0]const u8) c_int;
/// darwin has no MSG_NOSIGNAL and gets SO_NOSIGPIPE on the socket instead,
/// set right after socketpair.
const msg_nosignal = if (builtin.os.tag.isDarwin()) 0 else libc.MSG.NOSIGNAL;
/// One language server this client knows how to run. Adding a language is
/// adding a row; nothing below the table branches on a language.
const Spec = struct {
/// what the message row and `SPC l i` call it
name: []const u8,
/// argv[0], searched on PATH unless it contains a slash
bin: []const u8,
args: []const []const u8 = &.{},
/// the protocol's `languageId` for didOpen
lang: []const u8,
/// extensions that route a file here (the seam asks `speaks`)
exts: []const []const u8,
/// project markers, walked UP from the file: the TOP-MOST directory
/// holding one is the root (helix's find_root rule), `.git` the fallback
markers: []const []const u8,
/// environment override: a binary path/name to use instead of `bin`, or
/// empty ("") to disable the spec entirely. How the snapshot harness pins
/// a deterministic mock server, and how a user points at a custom build.
env: [:0]const u8,
/// The command that writes the language's `index.scip` at the project
/// root (Scip.zig), which the Index word runs there; `PARDES_SCIP_*`
/// (the env's language) names another.
indexer: []const u8,
};
/// Each spec's indexer override, `PARDES_SCIP_RS` beside `PARDES_LSP_RS`.
const indexer_envs = blk: {
var names: [specs.len][:0]const u8 = undefined;
for (specs, &names) |spec, *name| name.* = "PARDES_SCIP_" ++ spec.env["PARDES_LSP_".len..];
break :blk names;
};
pub const specs = [_]Spec{
.{
.name = "zls",
.bin = "zls",
.lang = "zig",
.exts = &.{".zig"},
.markers = &.{ "build.zig", "build.zig.zon" },
.env = "PARDES_LSP_ZIG",
.indexer = "scip-zig",
},
.{
.name = "rust-analyzer",
.bin = "rust-analyzer",
.lang = "rust",
.exts = &.{".rs"},
.markers = &.{ "Cargo.toml", "rust-project.json" },
.env = "PARDES_LSP_RS",
.indexer = "rust-analyzer scip .",
},
.{
.name = "clangd",
.bin = "clangd",
.lang = "c",
.exts = &.{ ".c", ".h", ".cc", ".cpp", ".hpp", ".cxx", ".hxx" },
.markers = &.{ "compile_commands.json", "compile_flags.txt", ".clangd" },
.env = "PARDES_LSP_C",
.indexer = "scip-clang",
},
.{
.name = "gopls",
.bin = "gopls",
.lang = "go",
.exts = &.{".go"},
.markers = &.{ "go.mod", "go.work" },
.env = "PARDES_LSP_GO",
.indexer = "scip-go",
},
.{
.name = "typescript-language-server",
.bin = "typescript-language-server",
.args = &.{"--stdio"},
.lang = "typescript",
.exts = &.{ ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs" },
.markers = &.{ "tsconfig.json", "jsconfig.json", "package.json" },
.env = "PARDES_LSP_TS",
.indexer = "scip-typescript index",
},
.{
.name = "pyright",
.bin = "pyright-langserver",
.args = &.{"--stdio"},
.lang = "python",
.exts = &.{".py"},
.markers = &.{ "pyproject.toml", "setup.py", "requirements.txt" },
.env = "PARDES_LSP_PY",
.indexer = "scip-python index .",
},
};
/// Everything. Whether one SERVER can answer is a capability question
/// answered per connection; a kind its server never advertised simply returns
/// no rows, which the harness reports as CLAIMED-EMPTY per language — honest,
/// since the claim here is about the protocol, not about every server.
pub const supports: std.EnumSet(lsp.Kind) = .full;
/// Routing: an extension in the table whose spec is not disabled by its env
/// var. Deliberately does NOT probe for the binary — this runs on the Tab
/// keystroke. A missing binary is discovered at spawn, disables the spec, and
/// says so once on the message row; until then Tab in a `.rs` file diverts,
/// gets "no rows" instantly (the disabled flag short-circuits), and indents
/// late exactly like any other unanswerable completion.
pub fn speaks(path: []const u8) bool {
return specFor(path) != null;
}
fn specFor(path: []const u8) ?usize {
for (&specs, 0..) |*s, i| {
for (s.exts) |e| {
if (!std.mem.endsWith(u8, path, e)) continue;
if (libc.getenv(s.env)) |v| if (v[0] == 0) return null; // "" disables
return i;
}
}
return null;
}
// Deadlines. A shell cancels-and-joins the previous worker on a new query,
// and its waits are cancelation points: so a request needs no deadline to
// keep the editor responsive, and waits for its answer. Past req_ms the
// message row says the server is still at it; only a server silent and idle
// (no $/progress) for wedge_ms has failed to answer. Timeouts do NOT kill the
// server — an indexing rust-analyzer legitimately sits on a `gd` for minutes.
// The handshake runs protected from cancelation, so it keeps its deadline.
const init_ms = 8_000; // spawn + initialize handshake
const req_ms = 4_000; // a request past this is said to be still working
const wedge_ms = 300_000; // silent and idle this long: not answering (rust-analyzer takes ~1 min on `default`'s callers in agave)
const diag_ms = 1_200; // wait for a publishDiagnostics push after didChange
const reply_ms = 2_000; // our answers to server-to-client requests
const reply_queue_bytes = 64 << 10; // replies waiting for the socket (Conn.replies)
const parse_kept = 1 << 20; // what the reader's parse arena keeps between messages
const max_diag_files = 256; // files a server's pushed diagnostics are kept for
const max_diag_bytes = 32 << 20; // and their bytes
const wedged_strikes = 3; // consecutive timeouts before a restart
/// Rows one answer may hold, and its writer's bytes: carved from the query's
/// fixed region (memory.limits.arena.lsp_query) with the rest of its memory.
const max_rows = 100_000;
/// What a Callstack walk leaves of its query's region for rendering the
/// tree it found: past this it stops and says so.
const callstack_reserve = 32 << 20;
/// What rendering leaves of the answer's writer for its closing line.
const row_room = 4096;
const max_doc_bytes = 8 << 20;
const Err = error{ Dead, Timeout, Protocol, OutOfMemory, NoServer, Backoff, WriteFailed, Canceled };
/// Long-lived state outlives every query arena and cannot borrow the caller's
/// gpa (a different one shows up in the harness than in the shell), so
/// connections own their memory from the page allocator.
const sa = std.heap.page_allocator;
/// Which units `character` counts in — see the header note on believing the
/// server.
const Enc = Scip.Enc;
const Doc = struct {
uri: []u8,
version: u32,
/// content hash: a query whose buffer has not moved since the last one
/// sends no didChange at all, which is most of what makes warm queries fast
hash: u64,
/// a didChange the server has not answered with diagnostics yet
stale: bool = true,
};
/// The last publishDiagnostics per file, kept as raw params and re-parsed
/// against a query's arena. The accumulation IS workspace diagnostics for a
/// server with no pull support.
const DiagSet = struct { uri: []u8, body: []u8 };
/// The slice of server capabilities this client changes behaviour on. Silent
/// kinds (a server with no renameProvider) need no flag — the request errors
/// and errors render as no rows. These four either pick between two code
/// paths or gate a second round trip.
const Caps = struct {
enc: Enc = .utf16,
/// textDocument/diagnostic (LSP 3.17 pull) — preferred over the push store
pull: bool = false,
/// workspace/diagnostic
pull_workspace: bool = false,
call_hier: bool = false,
type_hier: bool = false,
/// workspace/didChangeWorkspaceFolders is worth sending
folders: bool = false,
};
const State = enum(u8) {
/// never spawned — the row every spec starts on
off,
/// spawned, initialize in flight
starting,
ready,
/// transport broke or the server was declared wedged; next query respawns
dead,
/// binary missing or two failed handshakes; stays down for the session
disabled,
};
const Conn = struct {
mu: std.Io.Mutex = .init,
cond: std.Io.Condition = .init,
/// Frames go out whole: a query's requests and the reader's replies
/// share the socket, and interleaved halves are a parse error that ends
/// the server.
write_mu: std.Io.Mutex = .init,
/// Replies the reader made while a query's write held the socket, sent
/// by that writer once its own message is out (releaseWrite): the reader
/// never waits to write, since a server blocked on its output reads
/// nothing more of ours.
/// Two halves: the reader appends to `replies[filling]`, and the writer
/// flips them and sends the other, with no copy and no wait.
replies: [2][reply_queue_bytes]u8 = undefined,
replies_len: [2]usize = .{ 0, 0 },
filling: u1 = 0,
replies_mu: std.Io.Mutex = .init,
state: State = .off,
/// bumped per spawn. A reader thread that sees a different gen than its
/// own is reading a corpse and exits; a waiter that sees one stops waiting.
gen: u32 = 0,
handshake_fails: u8 = 0,
/// monotonic ms before which a dead/failed server is not respawned —
/// exponential backoff against forking a doomed child per keystroke
retry_after_ms: i64 = 0,
/// monotonic ms when the last handshake completed — a crash shortly
/// after "ready" counts as a handshake failure for backoff purposes
ready_at_ms: i64 = 0,
timeouts: u8 = 0,
pid: libc.pid_t = -1,
sock: c_int = -1,
next_id: u32 = 1,
caps: Caps = .{},
/// the workspace root sent in initialize (sa-owned)
root: []u8 = &.{},
/// roots added since, via didChangeWorkspaceFolders (sa-owned entries)
extra_roots: std.ArrayList([]u8) = .empty,
docs: std.ArrayList(Doc) = .empty,
diags: std.ArrayList(DiagSet) = .empty,
/// The bytes `diags` holds, kept under max_diag_bytes.
diag_bytes: usize = 0,
/// the response mailbox: one request outstanding per connection
want_id: u32 = 0,
resp: ?[]u8 = null,
/// active $/progress begins, and the last begin's title for report rows
progress: i32 = 0,
title: [48]u8 = @splat(0),
title_len: u8 = 0,
/// The server says it is still loading its workspace (rust-analyzer's
/// serverStatus, not quiescent): an empty answer now is not one.
loading: bool = false,
/// its index in `conns`, for what it posts
si: usize = 0,
fn alive(c: *const Conn) bool {
return c.state == .starting or c.state == .ready;
}
};
var conns: [specs.len]Conn = @splat(.{});
// ------------------------------------------------------------- status sink
/// One registered listener for unsolicited state changes; both native shells
/// register at startup and DEREGISTER before tearing their loop down — the
/// registry lock is held across the callback, so a null-ing shell cannot race
/// a reader thread mid-post. The callback must copy `text` before returning.
var sink_mu: std.atomic.Mutex = .unlocked;
var sink_ctx: ?*anyopaque = null;
var sink_cb: ?*const fn (ctx: ?*anyopaque, text: []const u8) void = null;
/// throttle for chatty progress reports, per spec
var sink_last_ms: [specs.len]i64 = @splat(0);
var sink_last_text: [specs.len][96]u8 = @splat(@splat(0));
var sink_last_len: [specs.len]u8 = @splat(0);
pub fn setStatusSink(ctx: ?*anyopaque, cb: ?*const fn (ctx: ?*anyopaque, text: []const u8) void) void {
while (!sink_mu.tryLock()) std.atomic.spinLoopHint();
defer sink_mu.unlock();
sink_ctx = ctx;
sink_cb = cb;
}
const Chat = enum {
/// a progress report: at most one per 150ms per server, dropped when it
/// repeats the previous text — rust-analyzer emits thousands over a big
/// index and the message row repaints per post
chatty,
/// a state change: starting, ready, exited, errors. Always posted.
always,
};
fn post(si: usize, chat: Chat, comptime fmt: []const u8, args: anytype) void {
var buf: [192]u8 = undefined;
var w: std.Io.Writer = .fixed(&buf);
w.print(fmt, args) catch {}; // a long one is cut at the row's end
const text = w.buffered();
while (!sink_mu.tryLock()) std.atomic.spinLoopHint();
defer sink_mu.unlock();
const cb = sink_cb orelse return;
// Repeating the row that is already showing is never news, whatever the
// class — and it is what makes the FINAL state deterministic for the
// snapshot harness: however many intermediate reports the throttle let
// through, an `.always` end state lands exactly once.
const cut = @min(text.len, sink_last_text[si].len);
if (std.mem.eql(u8, text[0..cut], sink_last_text[si][0..sink_last_len[si]])) return;
if (chat == .chatty) {
const now = nowMs();
if (now - sink_last_ms[si] < 150) return;
sink_last_ms[si] = now;
}
sink_last_len[si] = @intCast(cut);
@memcpy(sink_last_text[si][0..cut], text[0..cut]);
cb(sink_ctx, text);
}
// ------------------------------------------------------------- introspection
const LogEntry = struct {
used: bool = false,
kind: lsp.Kind = .definition,
spec: u8 = 0,
us: u64 = 0,
rows: usize = 0,
err: [24]u8 = @splat(0),
err_len: u8 = 0,
file: [64]u8 = @splat(0),
file_len: u8 = 0,
};
const log_cap = 24;
var log_buf: [log_cap]LogEntry = @splat(.{});
var log_next: usize = 0;
var log_total: u64 = 0;
var log_mu: std.atomic.Mutex = .unlocked;
fn record(si: usize, req: lsp.Req, us: u64, rows: usize, err: []const u8) void {
while (!log_mu.tryLock()) std.atomic.spinLoopHint();
defer log_mu.unlock();
const e = &log_buf[log_next];
e.* = .{ .used = true, .kind = req.kind, .spec = @intCast(si), .us = us, .rows = rows };
const base = std.Io.Dir.path.basename(req.path);
e.file_len = @intCast(@min(base.len, e.file.len));
@memcpy(e.file[0..e.file_len], base[0..e.file_len]);
e.err_len = @intCast(@min(err.len, e.err.len));
@memcpy(e.err[0..e.err_len], err[0..e.err_len]);
log_next = (log_next + 1) % log_cap;
log_total += 1;
}
/// What answered a logged query: a server, or `scip`, the index.
fn sourceName(spec: u8) []const u8 {
return if (spec < specs.len) specs[spec].name else "scip";
}
fn hideTime() bool {
return @import("../Messages.zig").Message.noTime();
}
/// `SPC l w` narration, threaded through the real path, so it cannot
/// disagree with what `gd` actually did.
const Trace = struct {
on: bool = false,
buf: [16 * 1024]u8 = undefined,
len: usize = 0,
fn note(t: *Trace, comptime fmt: []const u8, args: anytype) void {
if (!t.on or t.len == t.buf.len) return;
var w: std.Io.Writer = .fixed(t.buf[t.len..]);
w.print(fmt ++ "\n", args) catch {};
t.len += w.buffered().len;
}
};
// ------------------------------------------------------------------- query
pub fn query(io: std.Io, arena: std.mem.Allocator, asked: lsp.Req, out: *std.Io.Writer) Err!void {
const req = lsp.explaining(asked);
if (req.kind == .status) return status(io, req.path, out);
if (req.kind == .index) return indexCommand(req, out);
var tr: Trace = .{ .on = req.kind == .explain };
// Raw: `alloc` fills a safe build's new memory, all 51 MB of it, per query.
const scratch_buf = (arena.rawAlloc(max_rows * 512, .of(u8), @returnAddress()) orelse return error.OutOfMemory)[0 .. max_rows * 512];
var scratch: std.Io.Writer = .fixed(scratch_buf);
// The index first: what it answers wants no server.
const t0 = nowUs();
if (fromIndex(io, arena, req, if (req.kind == .explain) req.explains else req.kind, &scratch, &tr) catch |e| blk: {
tr.note("index: {s}", .{@errorName(e)});
break :blk false;
}) {
const us = nowUs() -| t0;
const rows = std.mem.count(u8, scratch.buffered(), "\n");
record(specs.len, req, us, rows, "");
if (req.kind == .explain) return traceOut(&tr, req, out, rows, us);
return out.writeAll(scratch.buffered());
}
scratch.end = 0;
const si = specFor(req.path) orelse {
tr.note("STOP: no language server spec matches {s}", .{
if (req.path.len == 0) "a pane with no file" else req.path,
});
if (req.kind != .explain) return lsp.none(out, "no language server for {s}", .{if (req.path.len == 0) "a pane with no file" else std.Io.Dir.path.basename(req.path)});
return traceOut(&tr, req, out, 0, 0);
};
tr.note("file {s} -> {s} (languageId {s})", .{ std.Io.Dir.path.basename(req.path), specs[si].name, specs[si].lang });
const t1 = nowUs();
var err_name: []const u8 = "";
var failure: ?Err = null;
answer(io, arena, si, req, &scratch, &tr) catch |e| {
failure = e;
err_name = @errorName(e);
tr.note("ERROR: {s}", .{err_name});
};
const us = nowUs() -| t1;
const rows = std.mem.count(u8, scratch.buffered(), "\n");
record(si, req, us, rows, err_name);
if (req.kind == .explain) return traceOut(&tr, req, out, rows, us);
// No server to start for the language: said, not "did not answer".
if (failure) |err| if (err == error.NoServer) return lsp.none(out, "language server for {s} not found", .{std.Io.Dir.path.extension(req.path)});
// Installed, but it failed a moment ago: said so, and when it is tried
// again, not that it is not there.
if (failure) |err| if (err == error.Backoff) {
const c = &conns[si];
c.mu.lockUncancelable(io);
const left_ms = c.retry_after_ms -| nowMs();
c.mu.unlock(io);
return lsp.none(out, "{s} failed recently; retry in {d}s", .{ specs[si].name, @divFloor(left_ms + 999, 1000) });
};
if (failure) |err| return err;
try out.writeAll(scratch.buffered());
}
fn traceOut(tr: *const Trace, req: lsp.Req, out: *std.Io.Writer, rows: usize, us: u64) std.Io.Writer.Error!void {
if (req.kind != .explain) return;
try out.print("lsp explain — the {s} query at byte {d} of {s}\n\n", .{
@tagName(req.explains), req.offset, if (req.path.len == 0) "(no file)" else std.Io.Dir.path.basename(req.path),
});
try out.writeAll(tr.buf[0..tr.len]);
if (hideTime())
try out.print("\n{d} row(s)\n", .{rows})
else
try out.print("\n{d} row(s) in {d}us\n", .{ rows, us });
}
fn answer(io: std.Io, arena: std.mem.Allocator, si: usize, req: lsp.Req, out: *std.Io.Writer, tr: *Trace) Err!void {
const c = &conns[si];
try c.mu.lock(io);
defer c.mu.unlock(io);
const g = try ensure(c, io, si, arena, req, tr);
const before = out.end;
try attempt(c, io, si, arena, req, out, tr, g);
// A server still loading its workspace answers at once, with nothing
// (rust-analyzer before its index): that is no answer. Wait until it says
// it is loaded, the message row saying so, and ask again.
const answered = out.buffered()[before..];
if (c.loading and c.gen == g and (answered.len == 0 or std.mem.startsWith(u8, answered, "@none "))) {
tr.note("{s} is still loading: waiting for it, then asking again", .{specs[si].name});
post(si, .always, "{s} is still loading the workspace; the answer comes when it is done\u{2026}", .{specs[si].name});
while (c.loading and c.gen == g and c.alive()) _ = try timedWait(c, io, nowMs() + 500);
out.end = before;
try attempt(c, io, si, arena, req, out, tr, g);
}
}
/// One run of a query, and what its failure says of the server.
fn attempt(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io.Writer, tr: *Trace, g: u32) Err!void {
run(c, io, si, arena, req, out, tr) catch |e| {
switch (e) {
// transport-level: this server is gone; forget it, and the next
// query respawns. Gen-checked so a respawn that happened while we
// waited is not the one we kill.
error.Dead, error.Protocol => shutdownIf(c, io, g),
error.Timeout => {
// Slow is only wedged when the server is IDLE. One with
// active `$/progress` work (rust-analyzer running cargo
// check over a thousand crates) is demonstrably alive, is
// narrating its own excuse on the message row, and killing
// it would throw the index away right before it pays off.
if (c.progress > 0) {
c.timeouts = 0;
} else {
c.timeouts +|= 1;
if (c.timeouts >= wedged_strikes and c.gen == g) {
post(si, .always, "{s} not answering — restarting", .{specs[si].name});
shutdownIf(c, io, g);
}
}
},
// Canceled: the shell asked something newer, not a wedged server.
error.OutOfMemory, error.NoServer, error.Backoff, error.WriteFailed, error.Canceled => {},
}
return e;
};
c.timeouts = 0;
}
fn run(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io.Writer, tr: *Trace) Err!void {
// `explain` narrates the last query asked (a definition, `gd`, when
// none was) — dispatch below on the effective kind so the trace
// follows the code that query really runs.
const kind: lsp.Kind = if (req.kind == .explain) req.explains else req.kind;
// Both arg-taking kinds are useless without one, and an empty
// workspace/symbol query means "every symbol in the project".
if ((kind == .rename or kind == .workspace_symbols) and req.arg.len == 0) return;
var uri: std.ArrayList(u8) = .empty;
try uriOf(&uri, arena, req.path);
try syncDoc(c, io, si, arena, uri.items, req.source);
// Every other open file this server answers for, before a query whose
// answer reaches them: zls renames only in the documents it has.
if (lsp.reachesOtherFiles(kind)) for (req.others) |doc| if (specFor(doc.path) == si and !std.mem.eql(u8, doc.path, req.path)) {
var other: std.ArrayList(u8) = .empty;
try uriOf(&other, arena, doc.path);
try syncDoc(c, io, si, arena, other.items, doc.source);
tr.note("synced {s} first", .{std.Io.Dir.path.basename(doc.path)});
};
const pos = posOf(req.source, req.offset, c.caps.enc);
var cx: Cx = .{ .io = io, .arena = arena, .base = req.root, .cur_path = req.path, .cur_src = req.source, .out = out, .fixed_out = true, .relative_parents = req.kind == .callstack };
for (req.others) |doc| try cx.files.append(arena, .{ .path = doc.path, .text = doc.source });
tr.note("server {s} (pid {d}), root {s}, {s} columns", .{
@tagName(c.state), c.pid, c.root, @tagName(c.caps.enc),
});
const deadline = nowMs() + req_ms;
switch (kind) {
.definition, .declaration, .type_definition, .implementation, .references => {
const method = switch (kind) {
.definition => "textDocument/definition",
.declaration => "textDocument/declaration",
.type_definition => "textDocument/typeDefinition",
.implementation => "textDocument/implementation",
else => "textDocument/references",
};
var b = try atPos(arena, uri.items, pos);
if (kind == .references) try b.appendSlice(arena, ",\"context\":{\"includeDeclaration\":true}");
tr.note("-> {s} @ {d}:{d}", .{ method, pos.line + 1, pos.ch + 1 });
const result = (try call(c, io, arena, method, b.items, deadline)) orelse {
tr.note("<- empty (no result, an error response, or null)", .{});
return;
};
try locations(&cx, c.caps.enc, result);
tr.note("<- {d} row(s)", .{cx.rows});
},
.select_refs => {
const b = try atPos(arena, uri.items, pos);
const result = (try call(c, io, arena, "textDocument/documentHighlight", b.items, deadline)) orelse return;
for (items(result)) |h| try emitRange(&cx, c.caps.enc, uri.items, get(h, "range"), "");
},
.hover => {
const b = try atPos(arena, uri.items, pos);
const result = (try call(c, io, arena, "textDocument/hover", b.items, deadline)) orelse return;
const contents = get(result, "contents") orelse return;
const text = str(contents) orelse str(get(contents, "value")) orelse blk: {
for (items(contents)) |m| if (str(m) orelse str(get(m, "value"))) |t| break :blk t;
break :blk "";
};
if (text.len == 0) return;
try out.writeAll(std.mem.trim(u8, text, " \t\r\n"));
try out.writeByte('\n');
},
.document_symbols => {
const b = try docParams(arena, uri.items);
const result = (try call(c, io, arena, "textDocument/documentSymbol", b.items, deadline)) orelse return;
try walkSymbols(&cx, c.caps.enc, uri.items, result, 0);
},
.workspace_symbols => {
var b: std.ArrayList(u8) = .empty;
try b.appendSlice(arena, "\"query\":");
try jstr(&b, arena, req.arg);
const result = (try call(c, io, arena, "workspace/symbol", b.items, deadline)) orelse return;
for (items(result)) |sym| {
const loc = get(sym, "location") orelse continue;
try emitRange(&cx, c.caps.enc, str(get(loc, "uri")) orelse continue, get(loc, "range"), str(get(sym, "name")) orelse "");
}
},
.diagnostics => try diagnostics(c, io, arena, &cx, uri.items, deadline),
.workspace_diagnostics => try workspaceDiagnostics(c, io, arena, &cx, deadline),
.rename => {
var b = try atPos(arena, uri.items, pos);
try b.appendSlice(arena, ",\"newName\":");
try jstr(&b, arena, req.arg);
const result = (try call(c, io, arena, "textDocument/rename", b.items, deadline)) orelse return;
// Other open files that say the old name, should the server
// answer for this file alone (zls renaming at a declaration does,
// whatever it was told): applied here, they would no longer build.
var also: std.ArrayList([]const u8) = .empty;
const old = identAt(req.source, req.offset);
if (old.len > 0) for (req.others) |doc| if (specFor(doc.path) == si and !std.mem.eql(u8, doc.path, req.path) and holdsWord(doc.source, old))
try also.append(arena, doc.path);
try renameEdits(&cx, c.caps.enc, uri.items, result, req.source, old, also.items);
},
.format => {
var b = try docParams(arena, uri.items);
try b.appendSlice(arena, ",\"options\":{\"tabSize\":4,\"insertSpaces\":true}");
const result = (try call(c, io, arena, "textDocument/formatting", b.items, deadline)) orelse return;
try formatEdits(&cx, c.caps.enc, result, req.source);
},
.code_action => {
var b = try docParams(arena, uri.items);
try b.print(arena, ",\"range\":{{\"start\":{{\"line\":{d},\"character\":{d}}},\"end\":{{\"line\":{d},\"character\":{d}}}}},\"context\":{{\"diagnostics\":[]}}", .{ pos.line, pos.ch, pos.line, pos.ch });
const result = (try call(c, io, arena, "textDocument/codeAction", b.items, deadline)) orelse return;
for (items(result)) |ca| {
const title = str(get(ca, "title")) orelse continue;
try lsp.row(cx.out, lsp.rel(cx.base, cx.cur_path), pos.line, 0, flat(arena, title));
cx.rows += 1;
}
},
.completion => {
var b = try atPos(arena, uri.items, pos);
try b.appendSlice(arena, ",\"context\":{\"triggerKind\":1}");
const result = (try call(c, io, arena, "textDocument/completion", b.items, deadline)) orelse return;
const list = if (get(result, "items")) |it| items(it) else items(result);
const here = lsp.rel(cx.base, cx.cur_path);
var n: usize = 0;
for (list) |item| {
if (n >= 100) break;
const label = str(get(item, "label")) orelse continue;
const detail = str(get(item, "detail")) orelse "";
var text: std.ArrayList(u8) = .empty;
try text.appendSlice(arena, label);
if (detail.len > 0) {
try text.appendSlice(arena, " ");
try text.appendSlice(arena, flat(arena, detail));
}
// Every row carries the ASKING position: a completion item has
// no location of its own, so the honest place is where it would
// be inserted. n/N still step the list; Enter goes nowhere new.
try lsp.row(cx.out, here, pos.line, byteCol(req.source, pos.line, pos.ch, c.caps.enc), text.items);
n += 1;
}
},
.callstack => try callstack(c, io, si, arena, &cx, uri.items, pos, deadline, tr, req.callstack_depth, req.budget),
.incoming_calls => try hierarchy(c, io, si, arena, &cx, uri.items, pos, deadline, .incoming, tr),
.outgoing_calls => try hierarchy(c, io, si, arena, &cx, uri.items, pos, deadline, .outgoing, tr),
.supertypes => try hierarchy(c, io, si, arena, &cx, uri.items, pos, deadline, .supers, tr),
.subtypes => try hierarchy(c, io, si, arena, &cx, uri.items, pos, deadline, .subs, tr),
.status, .explain, .index => unreachable,
}
}
// -------------------------------------------------------- kind sub-handlers
/// Goto/references result shapes: bare Location, Location[], LocationLink[].
fn locations(cx: *Cx, enc: Enc, result: std.json.Value) Err!void {
if (result == .object) {
try emitRange(cx, enc, str(get(result, "uri")) orelse return, get(result, "range"), "");
return;
}
for (items(result)) |loc| {
if (get(loc, "targetUri")) |tu| {
const r = get(loc, "targetSelectionRange") orelse get(loc, "targetRange");
try emitRange(cx, enc, str(tu) orelse continue, r, "");
} else {
try emitRange(cx, enc, str(get(loc, "uri")) orelse continue, get(loc, "range"), "");
}
}
}
/// DocumentSymbol[] nests (`children`), SymbolInformation[] is flat.
fn walkSymbols(cx: *Cx, enc: Enc, uri: []const u8, node: std.json.Value, depth: u8) Err!void {
if (depth > 8) return;
for (items(node)) |sym| {
const name = str(get(sym, "name")) orelse continue;
if (get(get(sym, "location"), "range")) |r| {
try emitRange(cx, enc, str(get(get(sym, "location"), "uri")) orelse uri, r, name);
} else {
try emitRange(cx, enc, uri, get(sym, "selectionRange") orelse get(sym, "range"), name);
}
if (get(sym, "children")) |kids| try walkSymbols(cx, enc, uri, kids, depth + 1);
}
}
/// Pull when the server does (LSP 3.17), the push store otherwise. The store
/// path waits briefly for a publish that postdates the didChange we just
/// sent, so `]d` right after an edit sees the new truth, not the old one.
fn diagnostics(c: *Conn, io: std.Io, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, deadline: i64) Err!void {
if (c.caps.pull) {
const b = try docParams(arena, uri);
const result = (try call(c, io, arena, "textDocument/diagnostic", b.items, deadline)) orelse return;
for (items(get(result, "items"))) |dg| try emitDiag(cx, c.caps.enc, uri, dg, arena);
return;
}
var stale = true;
for (c.docs.items) |d| if (std.mem.eql(u8, d.uri, uri)) {
stale = d.stale;
break;
};
if (stale) try waitFresh(c, io, uri, nowMs() + diag_ms);
try renderStore(c, arena, cx, uri);
}
fn workspaceDiagnostics(c: *Conn, io: std.Io, arena: std.mem.Allocator, cx: *Cx, deadline: i64) Err!void {
if (c.caps.pull_workspace) {
const result = (try call(c, io, arena, "workspace/diagnostic", "\"previousResultIds\":[]", deadline)) orelse return;
for (items(get(result, "items"))) |per| {
const uri = str(get(per, "uri")) orelse continue;
for (items(get(per, "items"))) |dg| try emitDiag(cx, c.caps.enc, uri, dg, arena);
}
return;
}
try renderStore(c, arena, cx, null);
}
/// One diagnostic row: `severity: message`, at the diagnostic's own range.
fn emitDiag(cx: *Cx, enc: Enc, uri: []const u8, dg: std.json.Value, arena: std.mem.Allocator) Err!void {
const sev = num(get(dg, "severity")) orelse 1;
const label: []const u8 = switch (sev) {
1 => "error",
2 => "warning",
3 => "info",
else => "hint",
};
const msg = try std.fmt.allocPrint(arena, "{s}: {s}", .{ label, flat(arena, str(get(dg, "message")) orelse "") });
try emitRange(cx, enc, uri, get(dg, "range"), msg);
}
fn renderStore(c: *Conn, arena: std.mem.Allocator, cx: *Cx, only_uri: ?[]const u8) Err!void {
for (c.diags.items) |d| {
if (only_uri) |u| if (!std.mem.eql(u8, d.uri, u)) continue;
const v = std.json.parseFromSliceLeaky(std.json.Value, arena, d.body, .{}) catch continue;
for (items(get(get(v, "params"), "diagnostics"))) |dg| try emitDiag(cx, c.caps.enc, d.uri, dg, arena);
}
}
/// Block (mutex released) until the reader marks `uri` fresh or the deadline
/// passes. The reader broadcasts on every publishDiagnostics.
fn waitFresh(c: *Conn, io: std.Io, uri: []const u8, deadline: i64) error{Canceled}!void {
const g = c.gen;
while (c.gen == g and c.alive()) {
var fresh = false;
for (c.docs.items) |d| if (std.mem.eql(u8, d.uri, uri)) {
fresh = !d.stale;
break;
};
if (fresh) return;
if (!try timedWait(c, io, deadline)) return;
}
}
/// The identifier at byte `at` of `src`: the word a rename there names.
fn identAt(src: []const u8, at: usize) []const u8 {
const isId = struct {
fn f(ch: u8) bool {
return std.ascii.isAlphanumeric(ch) or ch == '_';
}
}.f;
var start = @min(at, src.len);
while (start > 0 and isId(src[start - 1])) start -= 1;
var end = @min(at, src.len);
while (end < src.len and isId(src[end])) end += 1;
return src[start..end];
}
/// Whether `text` holds `word` as a whole identifier.
fn holdsWord(text: []const u8, word: []const u8) bool {
var from: usize = 0;
while (std.mem.indexOfPos(u8, text, from, word)) |i| : (from = i + 1) {
const before = i == 0 or !(std.ascii.isAlphanumeric(text[i - 1]) or text[i - 1] == '_');
const end = i + word.len;
const after = end == text.len or !(std.ascii.isAlphanumeric(text[end]) or text[end] == '_');
if (before and after) return true;
}
return false;
}
/// A WorkspaceEdit that stays inside the asked-about file becomes `@put`
/// records the core applies as one undo transaction; anything wider (a real
/// multi-file rename, file creates/renames) becomes a PREVIEW — one location
/// row per would-be edit, in the same buffer `gr` fills, because silently
/// applying a fraction of a workspace rename would be worse than either.
fn renameEdits(cx: *Cx, enc: Enc, self_uri: []const u8, result: std.json.Value, src: []const u8, old: []const u8, also: []const []const u8) Err!void {
var edits: std.ArrayList(PutEdit) = .empty;
var foreign = false;
// (uri, edits) per file, from either shape of a WorkspaceEdit
var files: std.ArrayList(struct { []const u8, ?std.json.Value }) = .empty;
if (get(result, "documentChanges")) |dcs| {
for (items(dcs)) |dc| {
if (get(dc, "kind") != null) {
foreign = true; // create/rename/delete file operations
continue;
}
const u = str(get(get(dc, "textDocument"), "uri")) orelse continue;
try files.append(cx.arena, .{ u, get(dc, "edits") });
}
} else if (get(result, "changes")) |ch| if (ch == .object) {
var it = ch.object.iterator();
while (it.next()) |e| try files.append(cx.arena, .{ e.key_ptr.*, e.value_ptr.* });
};
for (files.items) |f| {
const in_self = std.mem.eql(u8, f[0], self_uri);
if (!in_self) foreign = true;
for (items(f[1])) |ed| {
if (in_self) {
// one malformed edit poisons the WHOLE mutating response:
// applying the valid remainder would be a partial edit set
const span = byteSpan(src, get(ed, "range"), enc) orelse return;
const text = str(get(ed, "newText")) orelse return;
try edits.append(cx.arena, .{ .start = span.start, .end = span.end, .text = text });
} else try emitRange(cx, enc, f[0], get(ed, "range"), flat(cx.arena, str(get(ed, "newText")) orelse ""));
}
}
// Answered for this file alone while other open files say the old
// name: previewed, never applied, each such file named in a row.
const partial = !foreign and also.len > 0;
if (foreign or partial) {
// the preview needs the self-file rows too — the point is the full map
// Rows as the other files' are, `file:L:C-E` with the range's end.
for (edits.items) |ed| {
const lc = lsp.lineCol(src, ed.start);
const end = lsp.lineCol(src, ed.end);
try lsp.spanRow(cx.out, lsp.rel(cx.base, cx.cur_path), lc.line, lc.col, end.line, end.col, flat(cx.arena, ed.text));
cx.rows += 1;
}
if (partial) for (also) |path| {
try cx.out.print("{s}: also says {s}, which the server did not rename\n", .{ lsp.rel(cx.base, path), old });
cx.rows += 1;
};
return;
}
sortEdits(edits.items);
for (edits.items) |ed| try lsp.put(cx.out, ed.start, ed.end, ed.text);
}
/// TextEdit[] from formatting is by definition about the current document:
/// straight to sorted `@put` records.
fn formatEdits(cx: *Cx, enc: Enc, result: std.json.Value, src: []const u8) Err!void {
var edits: std.ArrayList(PutEdit) = .empty;
for (items(result)) |ed| {
// fail the whole response on the first malformed TextEdit — a subset
// of a format is not a format
const span = byteSpan(src, get(ed, "range"), enc) orelse return;
const text = str(get(ed, "newText")) orelse return;
try edits.append(cx.arena, .{ .start = span.start, .end = span.end, .text = text });
}
sortEdits(edits.items);
for (edits.items) |ed| try lsp.put(cx.out, ed.start, ed.end, ed.text);
}
/// One would-be buffer mutation, on its way to an `@put` record.
const PutEdit = struct { start: usize, end: usize, text: []const u8 };
fn sortEdits(edits: []PutEdit) void {
std.mem.sort(PutEdit, edits, {}, struct {
fn lt(_: void, a: PutEdit, b: PutEdit) bool {
return a.start < b.start;
}
}.lt);
}
/// A bounded static hierarchy. Reuse the prepared item verbatim (including
/// server data), and retain every call-site range rather than just a declaration.
fn hierarchyResult(c: *Conn, io: std.Io, arena: std.mem.Allocator, item: std.json.Value, method: []const u8, deadline: i64) Err!?std.json.Value {
if (jsonDepth(item, 0) > 96) return null;
var body: std.ArrayList(u8) = .empty;
try body.appendSlice(arena, "\"item\":");
try body.appendSlice(arena, try std.json.Stringify.valueAlloc(arena, item, .{}));
return call(c, io, arena, method, body.items, deadline);
}
const CallTree = struct {
/// What a node keeps of its caller: its own copies, so the response it
/// came in is freed once its subtree is walked.
const Call = struct { uri: []const u8, name: []const u8, at: Range };
const Site = struct { range: Range, focus: bool };
const Node = struct {
call: Call,
ranges: std.ArrayList(Site) = .empty,
children: std.ArrayList(usize) = .empty,
cycle: bool = false,
};
nodes: std.ArrayList(Node) = .empty,
roots: std.ArrayList(usize) = .empty,
path: [lsp.callstack_max_depth]Hop = undefined,
depth_limit: usize = lsp.callstack_default_depth,
limited: bool = false,
out_of_time: bool = false,
out_of_memory: bool = false,
budget: ?*const std.heap.FixedBufferAllocator = null,
si: usize = 0,
collected: usize = 0,
started_ms: i64 = 0,
narrated: bool = false,
siblings: [lsp.callstack_max_depth]bool = @splat(false),
rendered: usize = 0,
/// The rows rendering the tree takes: the walk stops before `row_cap`,
/// as at the memory limit (`out_of_memory`).
rows: usize = 0,
row_cap: usize = max_rows - 16,
/// The bytes those rows take, over-estimated (the uri for the path it
/// becomes), kept under the answer writer's room.
bytes: usize = 0,
byte_cap: usize = std.math.maxInt(usize),
/// A row of a caller at `depth`: its tree columns, the uri the path is
/// made from, the name, and room for the address.
fn rowBytes(depth: usize, caller: Call) usize {
return 5 * (depth + 2) + caller.uri.len + caller.name.len + 40;
}
/// Incoming paths arrive nearest-first. Insert them outermost-first,
/// sharing common caller prefixes and retaining all their call sites.
fn addPath(tree: *CallTree, arena: std.mem.Allocator, path: []const Hop, cycle: bool) Err!void {
var parent: ?usize = null;
var at = path.len;
while (at > 0) {
at -= 1;
const hop = path[at];
const children = if (parent) |id| tree.nodes.items[id].children.items else tree.roots.items;
const found = for (children) |id| {
if (sameCall(tree.nodes.items[id].call, hop.call)) break id;
} else null;
const depth = path.len - 1 - at;
const id = found orelse blk: {
const id = tree.nodes.items.len;
try tree.nodes.append(arena, .{ .call = .{ .uri = try arena.dupe(u8, hop.call.uri), .name = try arena.dupe(u8, hop.call.name), .at = hop.call.at } });
tree.rows += 1;
tree.bytes += rowBytes(depth, tree.nodes.items[id].call);
if (parent) |pid| {
try tree.nodes.items[pid].children.append(arena, id);
} else try tree.roots.append(arena, id);
break :blk id;
};
const node = &tree.nodes.items[id];
node.cycle = node.cycle or (cycle and at == 0);
for (hop.sites.items) |parsed| {
for (node.ranges.items) |*other| {
if (std.meta.eql(parsed, other.range)) {
other.focus = other.focus or at == 0;
break;
}
} else {
try node.ranges.append(arena, .{ .range = parsed, .focus = at == 0 });
tree.rows += 1;
tree.bytes += rowBytes(depth + 1, .{ .uri = node.call.uri, .name = "", .at = parsed });
}
}
parent = id;
}
}
};
/// A caller one level up a Callstack: the function, the calls it makes
/// there, and what its own callers are asked by, the server's item or the
/// index's symbol (and document).
const Hop = struct { call: CallTree.Call, sites: std.ArrayList(Range) = .empty, item: ?std.json.Value = null, symbol: u32 = 0, doc: u32 = 0 };
/// Where a Callstack's callers come from: the index, else the server.
const Calls = union(enum) {
index: *Scip.Index,
server: struct { c: *Conn, io: std.Io, parse: ?*std.heap.FixedBufferAllocator },
};
fn sameCall(a: CallTree.Call, b: CallTree.Call) bool {
return std.mem.eql(u8, a.uri, b.uri) and std.meta.eql(a.at, b.at);
}
/// The server's incoming calls as hops, their strings the response's.
fn serverHops(a: std.mem.Allocator, incoming: ?std.json.Value) Err![]Hop {
var hops: std.ArrayList(Hop) = .empty;
for (items(incoming)) |entry| {
const from = get(entry, "from") orelse continue;
const uri = str(get(from, "uri")) orelse continue;
const at = rangeOf(get(from, "selectionRange") orelse get(from, "range")) orelse continue;
if (!std.mem.startsWith(u8, uri, "file:")) continue;
var hop: Hop = .{ .call = .{ .uri = uri, .name = str(get(from, "name")) orelse "(unnamed)", .at = at }, .item = from };
for (items(get(entry, "fromRanges"))) |r| if (rangeOf(r)) |site| try hop.sites.append(a, site);
try hops.append(a, hop);
}
return hops.items;
}
/// The index's callers of `symbol` as hops: the definition enclosing each
/// of its references, the references it holds its sites.
fn indexHops(a: std.mem.Allocator, ix: *Scip.Index, symbol: u32) Err![]Hop {
var hops: std.ArrayList(Hop) = .empty;
for (ix.of(symbol)) |o| {
if (ix.occurrences[o].roles & Scip.role_definition != 0) continue;
const def = ix.occurrences[ix.enclosingDefinition(o) orelse continue];
const hop = for (hops.items) |*h| {
if (h.symbol == def.symbol) break h;
} else blk: {
try hops.append(a, .{ .call = .{ .uri = try indexUri(a, ix, def.doc), .name = displayName(ix, def.symbol), .at = def.range }, .symbol = def.symbol, .doc = def.doc });
break :blk &hops.items[hops.items.len - 1];
};
try hop.sites.append(a, ix.occurrences[o].range);
}
return hops.items;
}
fn callPrefix(out: *std.Io.Writer, tree: *const CallTree, depth: usize) Err!void {
for (tree.siblings[0..depth]) |more| try out.writeAll(if (more) "│ " else " ");
}
fn callstack(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, pos: Pos, deadline: i64, tr: *Trace, max_depth: u8, budget: ?*const std.heap.FixedBufferAllocator) Err!void {
if (!c.caps.call_hier) return lsp.none(cx.out, "{s} does not answer call hierarchy (no callHierarchyProvider)", .{specs[si].name});
const b = try atPos(arena, uri, pos);
const prepared = (try call(c, io, arena, "textDocument/prepareCallHierarchy", b.items, deadline)) orelse return;
if (items(prepared).len == 0) return lsp.none(cx.out, "no function at this position", .{});
// The rows come from the tree alone: the core reads the sources.
cx.no_text = true;
// Each response is parsed into its own part of the region, freed once
// its subtree is walked; only the path being walked is live JSON.
// Raw, as query()'s scratch: `alloc` would fill all ~100 MB of it.
const parse_len = if (budget) |fixed| (fixed.buffer.len - fixed.end_index) / 2 else 0;
var parse_fba: std.heap.FixedBufferAllocator = .init(if (budget != null)
(arena.rawAlloc(parse_len, .of(u8), @returnAddress()) orelse return error.OutOfMemory)[0..parse_len]
else
&.{});
const parse = if (budget != null) parse_fba.allocator() else arena;
for (items(prepared)) |item| {
const focus: CallTree.Call = .{ .uri = str(get(item, "uri")) orelse continue, .name = "", .at = rangeOf(get(item, "selectionRange") orelse get(item, "range")) orelse continue };
const incoming = try hierarchyResult(c, io, parse, item, "callHierarchy/incomingCalls", deadline);
const src: Calls = .{ .server = .{ .c = c, .io = io, .parse = if (budget != null) &parse_fba else null } };
try callTree(src, si, cx, c.caps.enc, focus, try serverHops(parse, incoming), tr, max_depth, budget);
}
}
/// A Callstack from the first callers of the function asked at: walked to
/// the depth setting, rendered, and why it stopped said.
fn callTree(src: Calls, si: usize, cx: *Cx, enc: Enc, focus: CallTree.Call, first: []const Hop, tr: *Trace, max_depth: u8, budget: ?*const std.heap.FixedBufferAllocator) Err!void {
var tree: CallTree = .{
.depth_limit = std.math.clamp(max_depth, 1, lsp.callstack_max_depth),
.si = si,
.started_ms = nowMs(),
.budget = budget,
// The walk stops while the answer's writer has room for the rest.
.byte_cap = if (cx.fixed_out) (cx.out.buffer.len - cx.out.end) -| (1 << 20) else std.math.maxInt(usize),
};
const count = try collectCallers(src, cx.arena, focus, first, &tree, 0);
if (tree.narrated) post(si, .always, "Callstack: {d} callers", .{tree.collected});
if (count == 0) try cx.out.writeAll("No callers reported\n");
try renderCallers(cx, enc, &tree, tree.roots.items, 0);
if (tree.out_of_time) {
try cx.out.writeAll("… the language server ran out of time; continue from a function above with Callstack\n");
} else if (tree.out_of_memory) {
try cx.out.writeAll("… stopped at the query's memory limit; continue from a function above with Callstack\n");
} else if (tree.limited) try cx.out.writeAll("… continue from a function above with Callstack\n");
tr.note("callstack: {d} callers", .{tree.rendered});
}
/// No caller count and no overall deadline: the walk narrates itself on the
/// message row after a second, and it stops when a request goes unanswered
/// or the answer is full (what was collected is shown, its last row saying
/// so), or when the shell cancels it for a newer query.
fn collectCallers(src: Calls, arena: std.mem.Allocator, focus: CallTree.Call, hops: []const Hop, tree: *CallTree, depth: usize) Err!usize {
var count: usize = 0;
for (hops) |hop| {
if (tree.budget) |b| if (b.buffer.len - b.end_index < callstack_reserve) {
tree.out_of_memory = true;
};
if (tree.rows >= tree.row_cap or tree.bytes >= tree.byte_cap) tree.out_of_memory = true;
if (tree.out_of_time or tree.out_of_memory) break;
const cycle = sameCall(focus, hop.call) or for (tree.path[0..depth]) |ancestor| {
if (sameCall(ancestor.call, hop.call)) break true;
} else false;
tree.path[depth] = hop;
count += 1;
tree.collected += 1;
if (nowMs() - tree.started_ms >= 1000) {
tree.narrated = true;
post(tree.si, .chatty, "Callstack: {d} callers\u{2026}", .{tree.collected});
}
var children: usize = 0;
if (!cycle) {
if (depth + 1 == tree.depth_limit) {
tree.limited = true;
} else if (src == .index) {
children = try collectCallers(src, arena, focus, try indexHops(arena, src.index, hop.symbol), tree, depth + 1);
} else {
const parse = src.server.parse;
const mark = if (parse) |fixed| fixed.end_index else 0;
defer if (parse) |fixed| {
fixed.end_index = mark;
};
const a = if (parse) |fixed| fixed.allocator() else arena;
const ancestors = hierarchyResult(src.server.c, src.server.io, a, hop.item.?, "callHierarchy/incomingCalls", nowMs() + req_ms) catch |e| switch (e) {
error.Timeout => blk: {
tree.out_of_time = true;
break :blk null;
},
// A response bigger than the parse region: this caller
// stops here, the walk with it.
error.OutOfMemory => blk: {
tree.out_of_memory = true;
break :blk null;
},
else => return e,
};
if (!tree.out_of_time and !tree.out_of_memory) children = try collectCallers(src, arena, focus, try serverHops(a, ancestors), tree, depth + 1);
}
}
if (children == 0) try tree.addPath(arena, tree.path[0 .. depth + 1], cycle);
}
return count;
}
/// Test callers sink below the rest; each group keeps the usual order.
// ponytail: substring heuristic, "latest.zig" or "contest" count as tests too
fn testCaller(caller: CallTree.Call) bool {
return std.ascii.findIgnoreCase(caller.name, "test") != null or
std.ascii.findIgnoreCase(std.Io.Dir.path.basenamePosix(caller.uri), "test") != null;
}
fn callerLess(tree: *const CallTree, a: usize, b: usize) bool {
const left = tree.nodes.items[a].call;
const right = tree.nodes.items[b].call;
if (testCaller(left) != testCaller(right)) return testCaller(right);
const uri_order = std.mem.order(u8, left.uri, right.uri);
if (uri_order != .eq) return uri_order == .lt;
return rangeLess(left.at, right.at);
}
fn rangeLess(left: Range, right: Range) bool {
return left.sl < right.sl or (left.sl == right.sl and left.sc < right.sc);
}
fn renderCallers(cx: *Cx, enc: Enc, tree: *CallTree, children: []usize, depth: usize) Err!void {
std.mem.sort(usize, children, @as(*const CallTree, tree), callerLess);
for (children, 0..) |id, index| {
// emitRange's row ceiling and the writer's room, met here before a
// prefix is half written
if (cx.rows >= max_rows or (cx.fixed_out and cx.out.buffer.len - cx.out.end < row_room)) {
tree.limited = true;
return;
}
const node = &tree.nodes.items[id];
const more = index + 1 < children.len;
try callPrefix(cx.out, tree, depth);
const has_children = node.children.items.len > 0 or node.ranges.items.len > 0;
try cx.out.writeAll(if (more) "├" else "╰");
try cx.out.writeAll(if (has_children) "──┬ " else "─── ");
const name = flat(cx.arena, node.call.name);
const label = if (node.cycle) try std.fmt.allocPrint(cx.arena, "{s} ↻ recursion", .{name}) else name;
try emitAt(cx, enc, node.call.uri, node.call.at, label);
tree.rendered += 1;
tree.siblings[depth] = more;
std.mem.sort(CallTree.Site, node.ranges.items, {}, struct {
fn less(_: void, a: CallTree.Site, b: CallTree.Site) bool {
return rangeLess(a.range, b.range);
}
}.less);
for (node.ranges.items, 0..) |site, site_index| {
if (cx.rows >= max_rows or (cx.fixed_out and cx.out.buffer.len - cx.out.end < row_room)) {
tree.limited = true;
return;
}
if (site.focus) try cx.out.writeAll(lsp.callstack_match);
try callPrefix(cx.out, tree, depth + 1);
try cx.out.writeAll(if (node.children.items.len > 0 or site_index + 1 < node.ranges.items.len) "├─ " else "╰─ ");
try emitAt(cx, enc, node.call.uri, site.range, "");
}
try renderCallers(cx, enc, tree, node.children.items, depth + 1);
}
}
const Hier = enum { incoming, outgoing, supers, subs };
/// The two-step hierarchy kinds: prepare at the cursor, then follow every
/// item the server returned (usually one). Gated on the server capability so
/// an old server costs zero round trips.
fn hierarchy(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, pos: Pos, deadline: i64, h: Hier, tr: *Trace) Err!void {
const call_side = h == .incoming or h == .outgoing;
if (call_side and !c.caps.call_hier) {
tr.note("STOP: {s} does not advertise callHierarchyProvider", .{specs[si].name});
return lsp.none(cx.out, "{s} does not answer call hierarchy (no callHierarchyProvider)", .{specs[si].name});
}
if (!call_side and !c.caps.type_hier) {
tr.note("STOP: {s} does not advertise typeHierarchyProvider", .{specs[si].name});
return lsp.none(cx.out, "{s} does not answer type hierarchy (no typeHierarchyProvider)", .{specs[si].name});
}
const prepare: []const u8 = if (call_side) "textDocument/prepareCallHierarchy" else "textDocument/prepareTypeHierarchy";
const follow: []const u8 = switch (h) {
.incoming => "callHierarchy/incomingCalls",
.outgoing => "callHierarchy/outgoingCalls",
.supers => "typeHierarchy/supertypes",
.subs => "typeHierarchy/subtypes",
};
const b = try atPos(arena, uri, pos);
const prepared = (try call(c, io, arena, prepare, b.items, deadline)) orelse return;
for (items(prepared)) |item| {
const result = (try hierarchyResult(c, io, arena, item, follow, deadline)) orelse return;
for (items(result)) |entry| switch (h) {
.incoming => {
// one row per CALL SITE, under the caller's name — that is
// what n/N want to walk
const from = get(entry, "from") orelse continue;
const fu = str(get(from, "uri")) orelse continue;
const name = str(get(from, "name")) orelse "";
const ranges = items(get(entry, "fromRanges"));
if (ranges.len == 0) {
try emitRange(cx, c.caps.enc, fu, get(from, "selectionRange"), name);
} else for (ranges) |r| try emitRange(cx, c.caps.enc, fu, r, name);
},
.outgoing => {
const to = get(entry, "to") orelse continue;
try emitRange(cx, c.caps.enc, str(get(to, "uri")) orelse continue, get(to, "selectionRange") orelse get(to, "range"), hierText(cx.arena, to));
},
.supers, .subs => try emitRange(cx, c.caps.enc, str(get(entry, "uri")) orelse continue, get(entry, "selectionRange") orelse get(entry, "range"), hierText(cx.arena, entry)),
};
}
}
/// Depth of a parsed json value, saturating just past `at`'s caller's cap —
/// the guard that keeps server-controlled nesting away from Stringify's
/// fixed-depth assertion.
fn jsonDepth(v: std.json.Value, at: u32) u32 {
if (at > 96) return at;
return switch (v) {
.object => |o| blk: {
var deepest = at;
var it = o.iterator();
while (it.next()) |e| deepest = @max(deepest, jsonDepth(e.value_ptr.*, at + 1));
break :blk deepest;
},
.array => |a| blk: {
var deepest = at;
for (a.items) |e| deepest = @max(deepest, jsonDepth(e, at + 1));
break :blk deepest;
},
else => at,
};
}
fn hierText(arena: std.mem.Allocator, item: std.json.Value) []const u8 {
const name = str(get(item, "name")) orelse "";
const detail = str(get(item, "detail")) orelse return name;
return std.fmt.allocPrint(arena, "{s} {s}", .{ name, flat(arena, detail) }) catch name;
}
// ---------------------------------------------------------------- the index
/// The index's answer (Scip.zig), in the rows the server's would make: true
/// when it had one, false to ask the server: no index above the file, a
/// file it does not hold, unsaved changes it has not seen, nothing at the
/// cursor, a symbol it does not know, or a word only a server answers.
fn fromIndex(io: std.Io, arena: std.mem.Allocator, req: lsp.Req, kind: lsp.Kind, out: *std.Io.Writer, tr: *Trace) Err!bool {
switch (kind) {
.definition, .type_definition, .implementation, .references, .select_refs, .hover, .document_symbols, .workspace_symbols, .incoming_calls, .outgoing_calls, .callstack, .supertypes, .subtypes => {},
else => return false,
}
if (req.dirty) {
tr.note("unsaved changes the index has not seen: the server", .{});
return false;
}
const dir = std.Io.Dir.path.dirname(req.path) orelse return false;
const ix = (Scip.find(io, dir) catch |e| {
tr.note("index.scip above {s}: {s}", .{ dir, @errorName(e) });
return false;
}) orelse {
tr.note("no index.scip above {s}", .{dir});
return false;
};
const doc = ix.document(req.path) orelse {
tr.note("{s} holds no {s}", .{ ix.path(), std.Io.Dir.path.basename(req.path) });
return false;
};
const si = specFor(req.path) orelse 0;
if (ix.stale(io, req.path)) {
tr.note("stale: {s} is newer than the index", .{std.Io.Dir.path.basename(req.path)});
if (!ix.stale_said) post(si, .always, "{s} is older than {s}: Index makes it again", .{ ix.path(), std.Io.Dir.path.basename(req.path) });
ix.stale_said = true;
}
const enc = ix.documents[doc].enc;
var cx: Cx = .{ .io = io, .arena = arena, .base = req.root, .cur_path = req.path, .cur_src = req.source, .out = out, .fixed_out = true, .relative_parents = kind == .callstack };
for (req.others) |d| try cx.files.append(arena, .{ .path = d.path, .text = d.source });
if (kind == .document_symbols or kind == .workspace_symbols) {
for (ix.occurrences, 0..) |o, i| {
if (kind == .document_symbols and o.doc != doc) continue;
// A name, never a local or a whole file's module.
if (o.roles & Scip.role_definition == 0 or o.range.sl != o.range.el or std.mem.startsWith(u8, ix.symbols.items[o.symbol], "local ")) continue;
const name = displayName(ix, o.symbol);
if (kind == .workspace_symbols and std.ascii.findIgnoreCase(name, req.arg) == null) continue;
try emitOcc(&cx, ix, @intCast(i), name);
}
tr.note("<- {d} row(s) from the index", .{cx.rows});
return cx.rows > 0;
}
const pos = posOf(req.source, req.offset, enc);
const at = ix.at(doc, pos.line, pos.ch) orelse {
tr.note("no occurrence at {d}:{d} in {s}", .{ pos.line + 1, pos.ch + 1, ix.path() });
return false;
};
const sym = ix.occurrences[at].symbol;
tr.note("{s}: occurrence '{s}' at {d}:{d}", .{ ix.path(), ix.symbols.items[sym], pos.line + 1, pos.ch + 1 });
switch (kind) {
.definition => try emitDefinitions(&cx, ix, sym, false),
.type_definition => for (try related(arena, ix, sym, 4)) |to| try emitDefinitions(&cx, ix, to, false),
.supertypes => for (try related(arena, ix, sym, 3)) |to| try emitDefinitions(&cx, ix, to, true),
.implementation, .subtypes => for (ix.infos.items, 0..) |_, from| {
if (std.mem.indexOfScalar(u32, try related(arena, ix, @intCast(from), 3), sym) != null)
try emitDefinitions(&cx, ix, @intCast(from), kind == .subtypes);
},
.references, .select_refs => {
var also = try related(arena, ix, sym, 2);
also = try std.mem.concat(arena, u32, &.{ &.{sym}, also });
for (also) |of| for (ix.of(of)) |o| if (kind == .references or ix.occurrences[o].doc == doc) try emitOcc(&cx, ix, o, "");
},
.hover => {
const info = ix.infos.items[sym];
var said = false;
if (Scip.field(info, 7)) |sig| if (Scip.field(sig.bytes, 5)) |text| {
try out.writeAll(std.mem.trim(u8, text.bytes, " \t\r\n"));
said = true;
};
var r: Scip.Reader = .{ .bytes = info };
while (r.next() catch null) |f| if (f.num == 3) {
if (said) try out.writeAll("\n\n");
try out.writeAll(std.mem.trim(u8, f.bytes, " \t\r\n"));
said = true;
};
if (said) try out.writeByte('\n') else tr.note("no documentation for it in the index", .{});
return said;
},
.incoming_calls => for (try indexHops(arena, ix, sym)) |hop| for (hop.sites.items) |site|
try emitPath(&cx, ix.documents[hop.doc].enc, try indexPath(arena, ix, hop.doc), site, hop.call.name),
.outgoing_calls => for (ix.of(sym)) |d| {
// The calls inside its definition, each function once, at its
// own definition.
const def = ix.occurrences[d];
if (def.roles & Scip.role_definition == 0) continue;
var seen: std.ArrayList(u32) = .empty;
const in = ix.documents[def.doc];
for (ix.occurrences[in.first..][0..in.len]) |o| {
if (o.roles & Scip.role_definition != 0 or !Scip.holds(def.enclosing, o.range) or !Scip.callable(ix.infos.items[o.symbol])) continue;
if (std.mem.indexOfScalar(u32, seen.items, o.symbol) != null) continue;
try seen.append(arena, o.symbol);
try emitDefinitions(&cx, ix, o.symbol, true);
}
break;
},
.callstack => {
const def = for (ix.of(sym)) |o| {
if (ix.occurrences[o].roles & Scip.role_definition != 0) break ix.occurrences[o];
} else {
tr.note("no definition of it in the index", .{});
return false;
};
// The rows come from the tree alone: the core reads the sources.
cx.no_text = true;
const focus: CallTree.Call = .{ .uri = try indexUri(arena, ix, def.doc), .name = "", .at = def.range };
try callTree(.{ .index = ix }, si, &cx, enc, focus, try indexHops(arena, ix, sym), tr, req.callstack_depth, req.budget);
return true;
},
else => unreachable,
}
tr.note("<- {d} row(s) from the index", .{cx.rows});
return cx.rows > 0;
}
/// A symbol's definitions, as rows: named by the symbol, as a type
/// hierarchy's are, or by their source lines.
fn emitDefinitions(cx: *Cx, ix: *Scip.Index, symbol: u32, named: bool) Err!void {
for (ix.of(symbol)) |o| if (ix.occurrences[o].roles & Scip.role_definition != 0) {
const sig = if (Scip.field(ix.infos.items[symbol], 7)) |f| (Scip.field(f.bytes, 5) orelse Scip.Field{ .num = 0 }).bytes else "";
const note = if (!named) "" else if (sig.len == 0) displayName(ix, symbol) else try std.fmt.allocPrint(cx.arena, "{s} {s}", .{ displayName(ix, symbol), flat(cx.arena, sig) });
try emitOcc(cx, ix, o, note);
};
}
fn emitOcc(cx: *Cx, ix: *const Scip.Index, o: u32, note: []const u8) Err!void {
const occ = ix.occurrences[o];
try emitPath(cx, ix.documents[occ.doc].enc, try indexPath(cx.arena, ix, occ.doc), occ.range, note);
}
/// The symbols `symbol`'s relationships name with flag `flag` set
/// (scip.proto Relationship: 2 is_reference, 3 is_implementation, 4
/// is_type_definition), the ones the index knows.
fn related(a: std.mem.Allocator, ix: *const Scip.Index, symbol: u32, flag: u64) Err![]u32 {
var out: std.ArrayList(u32) = .empty;
var r: Scip.Reader = .{ .bytes = ix.infos.items[symbol] };
while (r.next() catch null) |f| if (f.num == 4) {
const to = Scip.field(f.bytes, 1) orelse continue;
if ((Scip.field(f.bytes, flag) orelse continue).int == 0) continue;
if (ix.ids.get(to.bytes)) |id| try out.append(a, id);
};
return out.items;
}
/// A symbol's name to show: its display name, else its string's last
/// descriptor (`... lib/add().` is `add`).
fn displayName(ix: *const Scip.Index, symbol: u32) []const u8 {
if (Scip.field(ix.infos.items[symbol], 6)) |f| return f.bytes;
const s = std.mem.trimEnd(u8, ix.symbols.items[symbol], "().#/:!");
return s[if (std.mem.lastIndexOfAny(u8, s, " /#.")) |cut| cut + 1 else 0..];
}
fn indexPath(a: std.mem.Allocator, ix: *const Scip.Index, doc: u32) Err![]const u8 {
return std.fmt.allocPrint(a, "{s}/{s}", .{ ix.root(), ix.documents[doc].path });
}
fn indexUri(a: std.mem.Allocator, ix: *const Scip.Index, doc: u32) Err![]const u8 {
var b: std.ArrayList(u8) = .empty;
try uriOf(&b, a, try indexPath(a, ix, doc));
return b.items;
}
/// The Index word's command line: the language's indexer, at the
/// project's root, where the index it writes answers for every file under
/// it (`PARDES_SCIP_RS` and the like name another indexer).
fn indexCommand(req: lsp.Req, out: *std.Io.Writer) !void {
const si = specFor(req.path) orelse return lsp.none(out, "no indexer for {s}", .{std.Io.Dir.path.basename(req.path)});
const cmd = if (libc.getenv(indexer_envs[si])) |v| std.mem.span(v) else specs[si].indexer;
try out.writeAll("@run cd '");
for (rootOf(std.Io.Dir.path.dirname(req.path) orelse "/", specs[si].markers)) |ch| try if (ch == '\'') out.writeAll("'\\''") else out.writeByte(ch);
try out.print("' && {s}\n", .{cmd});
}
// ------------------------------------------------------------ row rendering
/// Files read while answering ONE query, so a references list over a handful
/// of files reads each once, not once per row. The current buffer never needs
/// reading: `req.source` IS its text, unsaved edits included.
const Cx = struct {
io: std.Io,
arena: std.mem.Allocator,
base: []const u8,
cur_path: []const u8,
cur_src: []const u8,
out: *std.Io.Writer,
/// `out` is the query's fixed answer buffer, whose room is checked.
fixed_out: bool = false,
/// Rows without their source text (Callstack: the core reads it).
no_text: bool = false,
rows: usize = 0,
relative_parents: bool = false,
files: std.ArrayList(struct { path: []const u8, text: []const u8 }) = .empty,
fn text(cx: *Cx, path: []const u8) ?[]const u8 {
if (std.mem.eql(u8, path, cx.cur_path)) return cx.cur_src;
for (cx.files.items) |f| if (std.mem.eql(u8, f.path, path)) return f.text;
if (cx.files.items.len >= 32) return null;
const file = std.Io.Dir.cwd().openFile(cx.io, path, .{}) catch return null;
defer file.close(cx.io);
var chunk: [64 * 1024]u8 = undefined;
var file_reader = file.reader(cx.io, &chunk);
var buf: std.ArrayList(u8) = .empty;
// A file past max_doc_bytes is its first max_doc_bytes.
file_reader.interface.appendRemaining(cx.arena, &buf, .limited(max_doc_bytes)) catch |err| switch (err) {
error.StreamTooLong => {},
else => return null,
};
cx.files.append(cx.arena, .{ .path = path, .text = buf.items }) catch return null;
return buf.items;
}
};
/// One row from an LSP (uri, Range). The uri becomes a real path (percent-
/// decoded, `rel`'d against the asking window), utf-16 columns become byte
/// columns, and a single-line range becomes the `path:LINE:COL-ENDCOL` form a
/// look SELECTS. `note` overrides the source line as the row's text.
fn emitRange(cx: *Cx, enc: Enc, uri: []const u8, range: ?std.json.Value, note: []const u8) Err!void {
return emitAt(cx, enc, uri, rangeOf(range) orelse return, note);
}
fn emitAt(cx: *Cx, enc: Enc, uri: []const u8, r: Range, note: []const u8) Err!void {
return emitPath(cx, enc, pathOf(cx.arena, uri) orelse return, r, note);
}
fn emitPath(cx: *Cx, enc: Enc, path: []const u8, r: Range, note: []const u8) Err!void {
if (cx.rows >= max_rows) return;
if (path.len == 0 or path[0] != '/') return; // rows promise absolute-or-rel-from-base
// Without sources (Callstack) the asking file is still known: its rows'
// columns convert from utf-16 as ever.
const src = if (cx.no_text and !std.mem.eql(u8, path, cx.cur_path)) null else cx.text(path);
var bol: usize = 0;
var eol: usize = 0;
if (src) |t| {
var n: u32 = 0;
while (n < r.sl) : (n += 1) {
bol = (std.mem.indexOfScalarPos(u8, t, bol, '\n') orelse {
bol = t.len;
break;
}) + 1;
}
eol = std.mem.indexOfScalarPos(u8, t, @min(bol, t.len), '\n') orelse t.len;
}
const lntext: []const u8 = if (src) |t| t[@min(bol, t.len)..@min(eol, t.len)] else "";
const col = colBytes(lntext, r.sc, enc);
const shown = if (cx.relative_parents) blk: {
const relative = std.Io.Dir.path.relativePosix(cx.arena, "/", cx.base, path) catch break :blk path;
break :blk if (relative.len < path.len) relative else path;
} else lsp.rel(cx.base, path);
// A same-line exclusive end byte offset is also the displayed inclusive
// one-based column. Multi-line ranges display only their starting address.
const end_col = if (r.el == r.sl and r.ec > r.sc) colBytes(lntext, r.ec, enc) else col;
if (note.len == 0) {
try lsp.sourceSpanRow(cx.out, shown, r.sl, col, r.el, end_col, lntext);
} else {
try lsp.spanRow(cx.out, shown, r.sl, col, r.el, end_col, note);
}
cx.rows += 1;
}
/// utf-16 code units -> byte column within one line; identity for utf-8.
fn colBytes(lntext: []const u8, ch: u32, enc: Enc) usize {
if (enc == .utf8 or lntext.len == 0) return ch;
var units: u32 = 0;
var i: usize = 0;
while (i < lntext.len and units < ch) {
const l = std.unicode.utf8ByteSequenceLength(lntext[i]) catch 1;
units += if (l == 4 and enc == .utf16) 2 else 1;
i += l;
}
return i;
}
/// The current-buffer byte column for a (line, ch) position — used only for
/// rows that point at the asking position itself.
fn byteCol(src: []const u8, line: u32, ch: u32, enc: Enc) usize {
var bol: usize = 0;
var n: u32 = 0;
while (n < line) : (n += 1)
bol = (std.mem.indexOfScalarPos(u8, src, bol, '\n') orelse return ch) + 1;
const eol = std.mem.indexOfScalarPos(u8, src, bol, '\n') orelse src.len;
return colBytes(src[bol..eol], ch, enc);
}
/// Whole-document Range -> half-open byte span for a MUTATING record.
/// STRICT: null unless both endpoints denote positions that exist in the
/// document — for edits, a clamped range is a wrong edit, and wrong edits
/// fail closed (the render paths keep their forgiving conversions; a row a
/// column off is an inconvenience, a splice a column off is corruption).
fn byteSpan(src: []const u8, range: ?std.json.Value, enc: Enc) ?struct { start: usize, end: usize } {
const r = rangeOf(range) orelse return null;
const start = strictOffset(src, r.sl, r.sc, enc) orelse return null;
const end = strictOffset(src, r.el, r.ec, enc) orelse return null;
if (end < start) return null;
return .{ .start = start, .end = end };
}
/// (line, character) -> byte offset, or null when the line does not exist or
/// the character runs past its end. End-of-line (character == line length) is
/// a real position — that is where an insert-at-EOL lands.
fn strictOffset(src: []const u8, line: u32, ch: u32, enc: Enc) ?usize {
var bol: usize = 0;
var n: u32 = 0;
while (n < line) : (n += 1)
bol = (std.mem.indexOfScalarPos(u8, src, bol, '\n') orelse return null) + 1;
const eol = std.mem.indexOfScalarPos(u8, src, bol, '\n') orelse src.len;
if (enc == .utf8) {
if (ch > eol - bol) return null;
return bol + ch;
}
var units: u32 = 0;
var i: usize = bol;
while (i < eol and units < ch) {
const l = std.unicode.utf8ByteSequenceLength(src[i]) catch 1;
units += if (l == 4 and enc == .utf16) 2 else 1;
i += l;
}
if (units < ch) return null;
return i;
}
/// Prose squashed onto the one line a row is: newlines and tabs to spaces,
/// cut to a width a pane can show.
fn flat(arena: std.mem.Allocator, s: []const u8) []const u8 {
var buf: std.ArrayList(u8) = .empty;
var sp = false;
for (s) |ch| {
if (ch == '\n' or ch == '\r' or ch == '\t' or ch == 0) {
if (!sp and buf.items.len > 0) buf.append(arena, ' ') catch break;
sp = true;
} else {
buf.append(arena, ch) catch break;
sp = false;
}
if (buf.items.len >= 200) break;
}
return std.mem.trim(u8, buf.items, " ");
}
fn setCloexec(fd: c_int) void {
const FD_CLOEXEC: c_int = 1;
_ = libc.fcntl(fd, libc.F.SETFD, FD_CLOEXEC);
}
// Darwin needs fcntl after socketpair; another concurrent fork can inherit the pair in that window.
fn transportPair(sv: *[2]libc.fd_t) bool {
const sock_type = if (comptime builtin.os.tag.isDarwin())
libc.SOCK.STREAM
else
libc.SOCK.STREAM | libc.SOCK.CLOEXEC;
if (libc.socketpair(libc.AF.UNIX, sock_type, 0, sv) != 0) return false;
if (comptime builtin.os.tag.isDarwin()) {
setCloexec(sv[0]);
// The child dup2s this onto 0 and 1, and dup2 CLEARS close-on-exec on
// the copy, so the server still gets the socket; this marks only the
// number itself, which the child's 3..1024 sweep closes anyway.
setCloexec(sv[1]);
const one: c_int = 1;
_ = libc.setsockopt(sv[0], libc.SOL.SOCKET, libc.SO.NOSIGPIPE, @ptrCast(&one), @sizeOf(c_int));
}
return true;
}
// ----------------------------------------------------------- the connection
/// Spawn-or-return, and tell an existing server about a new project root.
/// Returns the generation the caller's whole query is bound to.
fn ensure(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, req: lsp.Req, tr: *Trace) Err!u32 {
c.si = si;
if (c.state == .disabled) {
tr.note("STOP: {s} is disabled for this session (no binary; set {s})", .{ specs[si].name, specs[si].env });
return error.NoServer;
}
if (c.alive()) {
const root = rootOf(req.root, specs[si].markers);
if (!std.mem.eql(u8, root, c.root)) {
var known = false;
for (c.extra_roots.items) |r| if (std.mem.eql(u8, r, root)) {
known = true;
break;
};
if (!known and c.caps.folders) {
var b: std.ArrayList(u8) = .empty;
try b.appendSlice(arena, "{\"jsonrpc\":\"2.0\",\"method\":\"workspace/didChangeWorkspaceFolders\",\"params\":{\"event\":{\"added\":[{\"name\":\"root\",\"uri\":\"");
try uriOf(&b, arena, root);
try b.appendSlice(arena, "\"}],\"removed\":[]}}}");
try send(c, io, b.items, nowMs() + wedge_ms);
const owned = try sa.dupe(u8, root);
c.extra_roots.append(sa, owned) catch sa.free(owned);
}
}
return c.gen;
}
// A recent failed spawn/handshake holds the fork back; the message row
// already said when the next try is due.
if (nowMs() < c.retry_after_ms) {
tr.note("STOP: {s} failed recently; retry due in {d}ms", .{ specs[si].name, c.retry_after_ms - nowMs() });
return error.Backoff;
}
// Look before forking; a missing binary must cost one probe and one
// message, not a doomed fork per keystroke.
var exe_buf: [4096:0]u8 = undefined;
const exe = binOf(&specs[si], &exe_buf) orelse {
c.state = .disabled;
post(si, .always, "{s} not found — install it or set {s}", .{ specs[si].name, specs[si].env });
tr.note("STOP: no {s} binary on PATH (override: {s})", .{ specs[si].bin, specs[si].env });
return error.NoServer;
};
const root = rootOf(req.root, specs[si].markers);
var root_buf: [4096:0]u8 = undefined;
const root_z = std.fmt.bufPrintSentinel(&root_buf, "{s}", .{root}, 0) catch return error.NoServer;
// Owned BEFORE anything spawns: the reader thread is the socket's only
// closer once it exists, so nothing fallible may sit between fork and
// reader-spawn — an abort there would strand the fd.
const owned_root = try sa.dupe(u8, root);
var sv: [2]libc.fd_t = undefined;
if (!transportPair(&sv)) {
sa.free(owned_root);
tr.note("STOP: socketpair for {s} failed", .{specs[si].name});
return error.NoServer;
}
if (!exit_hook.swap(true, .acq_rel)) _ = atexit(killAllAtExit);
// ponytail: hand-rolled, not std.process.spawn: 0.17's has no setsid
// (only setpgid), no signal mask/disposition reset and no fd sweep.
const pid = libc.fork();
if (pid < 0) {
_ = libc.close(sv[0]);
_ = libc.close(sv[1]);
sa.free(owned_root);
tr.note("STOP: fork for {s} failed", .{specs[si].name});
return error.NoServer;
}
if (pid == 0) {
// Between fork and exec, in a process with threads: only async-
// signal-safe calls, no allocation, no locks. (Same rule as tui.zig's
// forkShell.)
_ = libc.setsid(); // Ctrl-C in pardes's terminal is not the server's business
@import("../host_io.zig").resetChildSignals();
_ = libc.dup2(sv[1], 0);
_ = libc.dup2(sv[1], 1);
const devnull = libc.open("/dev/null", .{ .ACCMODE = .WRONLY });
if (devnull >= 0) _ = libc.dup2(devnull, 2);
var fd: c_int = 3;
while (fd < 1024) : (fd += 1) _ = libc.close(fd);
_ = libc.chdir(root_z.ptr);
var argv: [8:null]?[*:0]const u8 = @splat(null);
argv[0] = exe.ptr;
// args are comptime literals; the buffers live until execv
var argbufs: [6][64:0]u8 = undefined;
for (specs[si].args, 0..) |a, i| {
if (i >= argbufs.len) break;
const z = std.fmt.bufPrintSentinel(&argbufs[i], "{s}", .{a}, 0) catch break;
argv[1 + i] = z.ptr;
}
_ = execv(exe.ptr, &argv);
libc._exit(127);
}
_ = libc.close(sv[1]);
// the slate the old generation may have left (a self-died server skips
// shutdownIf) must not leak into the new one: a stale doc entry would
// suppress the didOpen the new server never got
c.gen +%= 1;
const g = c.gen;
c.pid = pid;
c.sock = sv[0];
c.state = .starting;
c.caps = .{};
c.next_id = 1;
c.want_id = 0;
if (c.resp) |r| sa.free(r);
c.resp = null;
c.progress = 0;
c.loading = false;
c.timeouts = 0;
forgetDocs(c);
if (c.root.len > 0) sa.free(c.root);
c.root = owned_root;
const th = std.Thread.spawn(.{}, reader, .{ io, si, g, sv[0] }) catch {
// no reader means nobody would ever close the fd our way; do it here,
// before anything else can see the conn
_ = libc.close(sv[0]);
_ = libc.kill(pid, .KILL);
_ = libc.waitpid(pid, null, 0);
c.state = .dead;
c.sock = -1;
return error.NoServer;
};
th.detach();
post(si, .always, "{s} starting — {s}", .{ specs[si].name, root });
tr.note("spawned {s} (pid {d}) at {s}", .{ specs[si].name, pid, root });
// A start runs to the end however soon the query that began it is
// canceled: killing a half-started server would only make the next
// query start it again. The cancel lands at the next wait instead.
const protection = io.swapCancelProtection(.blocked);
const started = handshake(c, io, arena, root);
_ = io.swapCancelProtection(protection);
started catch |e| {
shutdownIf(c, io, g);
// NOT a session disable. A handshake that misses the deadline is
// routinely environmental — a rustup shim deciding to download the
// project's pinned toolchain before launching the real server was
// the case that taught this — and it heals by itself. What must not
// happen is a fork per keystroke while it heals, so failures back
// off on backoffMs's schedule, reset by the next success.
c.handshake_fails +|= 1;
const wait = backoffMs(c.handshake_fails);
c.retry_after_ms = nowMs() + wait;
post(si, .always, "{s} not answering — retrying in {d}s", .{
specs[si].name, @divTrunc(wait, 1000),
});
return switch (e) {
error.OutOfMemory => error.OutOfMemory,
else => error.NoServer,
};
};
c.handshake_fails = 0;
c.retry_after_ms = 0;
c.ready_at_ms = nowMs();
c.state = .ready;
post(si, .always, "{s} ready — {s}", .{ specs[si].name, root });
return g;
}
fn handshake(c: *Conn, io: std.Io, arena: std.mem.Allocator, root: []const u8) Err!void {
var b: std.ArrayList(u8) = .empty;
try b.print(arena, "\"processId\":{d},\"clientInfo\":{{\"name\":\"pardes\"}},\"rootUri\":\"", .{@as(u32, @bitCast(libc.getpid()))});
try uriOf(&b, arena, root);
try b.appendSlice(arena, "\",\"workspaceFolders\":[{\"name\":\"root\",\"uri\":\"");
try uriOf(&b, arena, root);
try b.appendSlice(arena, "\"");
try b.appendSlice(arena,
\\}],"capabilities":{"general":{"positionEncodings":["utf-8","utf-16"]},
\\"window":{"workDoneProgress":true},
\\"workspace":{"configuration":true,"workspaceFolders":true,"symbol":{},
\\"diagnostics":{"refreshSupport":false}},
\\"textDocument":{"synchronization":{"dynamicRegistration":false,"willSave":false,"didSave":false},
\\"publishDiagnostics":{"relatedInformation":false},
\\"diagnostic":{"dynamicRegistration":false,"relatedDocumentSupport":false},
\\"hover":{"contentFormat":["plaintext","markdown"]},
\\"definition":{"linkSupport":true},"declaration":{"linkSupport":true},
\\"typeDefinition":{"linkSupport":true},"implementation":{"linkSupport":true},
\\"references":{},"documentHighlight":{},
\\"documentSymbol":{"hierarchicalDocumentSymbolSupport":true},
\\"formatting":{},"rename":{"prepareSupport":false},
\\"completion":{"completionItem":{"snippetSupport":false,"documentationFormat":["plaintext"]}},
\\"callHierarchy":{},"typeHierarchy":{},
\\"codeAction":{"codeActionLiteralSupport":{"codeActionKind":{"valueSet":[]}}}},
\\"experimental":{"serverStatusNotification":true}}
);
// strip the literal's newlines: legal JSON either way, but the frame
// length must match what is sent
var body: std.ArrayList(u8) = .empty;
for (b.items) |ch| if (ch != '\n') try body.append(arena, ch);
const deadline = nowMs() + init_ms;
const reply = (try call(c, io, arena, "initialize", body.items, deadline)) orelse return error.Protocol;
const caps = get(reply, "capabilities");
c.caps.enc = if (std.mem.eql(u8, str(get(caps, "positionEncoding")) orelse "utf-16", "utf-8")) .utf8 else .utf16;
if (get(caps, "diagnosticProvider")) |dp| {
c.caps.pull = provider(dp);
c.caps.pull_workspace = if (get(dp, "workspaceDiagnostics")) |w| w == .bool and w.bool else false;
}
c.caps.call_hier = provider(get(caps, "callHierarchyProvider"));
c.caps.type_hier = provider(get(caps, "typeHierarchyProvider"));
c.caps.folders = if (get(get(get(caps, "workspace"), "workspaceFolders"), "supported")) |s| s == .bool and s.bool else false;
try send(c, io, "{\"jsonrpc\":\"2.0\",\"method\":\"initialized\",\"params\":{}}", deadline);
}
/// A server capability that may be `true`, an options object, or absent.
fn provider(v: ?std.json.Value) bool {
const o = v orelse return false;
return switch (o) {
.bool => |b| b,
.object => true,
else => false,
};
}
/// didOpen the first time a file is seen, didChange when its bytes moved,
/// nothing when they did not — the common case between two presses of gd.
fn syncDoc(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, uri: []const u8, src: []const u8) Err!void {
const hash = std.hash.Wyhash.hash(0, src);
var doc: ?*Doc = null;
for (c.docs.items) |*d| if (std.mem.eql(u8, d.uri, uri)) {
doc = d;
break;
};
if (doc) |d| if (d.hash == hash) return;
var b: std.ArrayList(u8) = .empty;
if (doc) |d| {
d.version += 1;
d.hash = hash;
d.stale = true;
try b.print(arena, "{{\"jsonrpc\":\"2.0\",\"method\":\"textDocument/didChange\",\"params\":{{\"textDocument\":{{\"uri\":", .{});
try jstr(&b, arena, uri);
try b.print(arena, ",\"version\":{d}}},\"contentChanges\":[{{\"text\":", .{d.version});
try jstr(&b, arena, src);
try b.appendSlice(arena, "}]}}");
} else {
if (c.docs.items.len >= 256) return; // a session does not open this many
const owned = try sa.dupe(u8, uri);
c.docs.append(sa, .{ .uri = owned, .version = 1, .hash = hash }) catch {
sa.free(owned);
return error.OutOfMemory;
};
try b.appendSlice(arena, "{\"jsonrpc\":\"2.0\",\"method\":\"textDocument/didOpen\",\"params\":{\"textDocument\":{\"uri\":");
try jstr(&b, arena, uri);
try b.print(arena, ",\"languageId\":\"{s}\",\"version\":1,\"text\":", .{specs[si].lang});
try jstr(&b, arena, src);
try b.appendSlice(arena, "}}}");
}
// A server busy with what it was sent last reads no more meanwhile
// (clangd parses its compile database at a first open): this waits as
// an answer does, for a cancel or a server that has stopped.
try send(c, io, b.items, nowMs() + wedge_ms);
}
/// Send a request and wait on the mailbox. Returns the parsed `result`, or
/// null for an error response / null result — both are legal "no answer".
/// Runs with the conn mutex held; the mutex is released inside the wait.
fn call(c: *Conn, io: std.Io, arena: std.mem.Allocator, method: []const u8, params: []const u8, deadline: i64) Err!?std.json.Value {
const g = c.gen;
const id = c.next_id;
c.next_id +%= 1;
var b: std.ArrayList(u8) = .empty;
try b.print(arena, "{{\"jsonrpc\":\"2.0\",\"id\":{d},\"method\":\"{s}\",\"params\":{{", .{ id, method });
try b.appendSlice(arena, params);
try b.appendSlice(arena, "}}");
if (c.resp) |r| sa.free(r);
c.resp = null;
c.want_id = id;
defer c.want_id = 0;
try send(c, io, b.items, if (c.state == .ready) nowMs() + wedge_ms else deadline);
// The handshake (still `.starting`) has its deadline. A ready server is
// waited for until it answers or the shell cancels this query for a
// newer one, so the first query after a start is answered, not lost:
// past `deadline` the message row says it is still working, and only
// silent and idle for wedge_ms is it not answering.
var said = false;
var busy_at = nowMs();
while (c.resp == null and c.gen == g and c.alive()) {
const ready = c.state == .ready;
const waiting = timedWait(c, io, if (ready) nowMs() + 500 else deadline) catch |e| {
cancelRequest(c, io, arena, id);
return e;
};
if (!ready) {
if (waiting) continue;
break;
}
if (c.progress > 0) busy_at = nowMs();
if (!said and nowMs() >= deadline) {
said = true;
post(c.si, .always, "{s} is still working on it\u{2026}", .{specs[c.si].name});
}
if (nowMs() - busy_at >= wedge_ms) break;
}
if (said and c.resp != null) post(c.si, .always, "{s} answered", .{specs[c.si].name});
if (c.gen != g or !c.alive()) return error.Dead;
const raw = c.resp orelse {
cancelRequest(c, io, arena, id);
return error.Timeout;
};
c.resp = null;
defer sa.free(raw);
const v = std.json.parseFromSliceLeaky(std.json.Value, arena, raw, .{}) catch return error.Protocol;
const result = get(v, "result") orelse return null;
if (result == .null) return null;
return result;
}
/// Give the server leave to abandon the work we stopped waiting for.
fn cancelRequest(c: *Conn, io: std.Io, arena: std.mem.Allocator, id: u32) void {
var cb: std.ArrayList(u8) = .empty;
cb.print(arena, "{{\"jsonrpc\":\"2.0\",\"method\":\"$/cancelRequest\",\"params\":{{\"id\":{d}}}}}", .{id}) catch return;
send(c, io, cb.items, nowMs() + reply_ms) catch {};
}
/// One bounded cond wait, and a cancelation point: a worker the shell
/// cancels for a newer query stops here. False when the deadline has passed.
fn timedWait(c: *Conn, io: std.Io, deadline: i64) error{Canceled}!bool {
const left = deadline - nowMs();
if (left <= 0) return false;
const wait_ms = @min(left, 500); // tick so gen/state changes are noticed
c.cond.waitTimeout(io, &c.mu, .{ .duration = .{ .raw = .fromMilliseconds(wait_ms), .clock = .awake } }) catch |e| switch (e) {
error.Timeout => {},
error.Canceled => return error.Canceled,
};
return true;
}
/// Forget a server, but only the generation the caller actually used — a
/// respawn that happened during the caller's wait must not be killed for its
/// predecessor's crimes. Mutex held. The reader closes the fd; this only
/// shuts the transport down and reaps the child.
fn shutdownIf(c: *Conn, io: std.Io, g: u32) void {
if (c.gen != g or c.sock < 0) return;
_ = libc.shutdown(c.sock, 2); // SHUT_RDWR: the reader sees EOF and closes
reap(c.pid);
c.sock = -1;
c.pid = -1;
if (c.state != .disabled) c.state = .dead;
forgetDocs(c);
if (c.resp) |r| sa.free(r);
c.resp = null;
c.cond.broadcast(io);
}
/// TERM, a bounded grace, then KILL, to the server's whole process group
/// (it is its group's leader, setsid at spawn): what it started -- zls's
/// `zig build --build-runner` -- goes with it, never left an orphan. Never
/// blocks unboundedly: a reaped or foreign pid answers -1 immediately.
fn reap(pid: libc.pid_t) void {
if (pid <= 0) return;
_ = libc.kill(-pid, .TERM);
var tries: u8 = 0;
while (tries < 20) : (tries += 1) {
const w = libc.waitpid(pid, null, libc.W.NOHANG);
if (w == pid or w < 0) {
// Its children may still be finishing their TERM.
_ = libc.kill(-pid, .KILL);
return;
}
_ = usleep(10_000);
}
_ = libc.kill(-pid, .KILL);
_ = libc.waitpid(pid, null, 0);
}
/// At this process's exit, every server's group is killed: a server busy
/// in a build (zls at a cold start) would not notice its socket close, and
/// lived on with its children after the editor. Registered once, at the
/// first spawn; signals only, no locks (other threads may hold them).
fn killAllAtExit() callconv(.c) void {
for (&conns) |*c| if (c.pid > 0) {
_ = libc.kill(-c.pid, .KILL);
};
}
var exit_hook = std.atomic.Value(bool).init(false);
/// Free every per-document accumulation. Mutex held.
fn forgetDocs(c: *Conn) void {
for (c.extra_roots.items) |r| sa.free(r);
c.extra_roots.clearRetainingCapacity();
for (c.docs.items) |d| sa.free(d.uri);
c.docs.clearRetainingCapacity();
for (c.diags.items) |d| {
sa.free(d.uri);
sa.free(d.body);
}
c.diags.clearRetainingCapacity();
c.diag_bytes = 0;
}
// ------------------------------------------------------------ reader thread
/// Owns the read side of one socket for one generation, and is the only
/// closer of that fd. Routes responses to the mailbox, answers server
/// requests, feeds the diagnostics store, narrates progress.
fn reader(io: std.Io, si: usize, g: u32, sock: c_int) void {
const c = &conns[si];
var buf = sa.alloc(u8, 256 * 1024) catch {
readerExit(c, io, si, g, sock);
return;
};
defer sa.free(buf);
var len: usize = 0;
var parse_arena: std.heap.ArenaAllocator = .init(sa);
defer parse_arena.deinit();
outer: while (true) {
// drain every complete frame already buffered
drain: while (true) switch (frameNext(buf[0..len])) {
.frame => |m| {
dispatch(c, io, si, g, sock, buf[m.body_start..m.body_end], &parse_arena);
std.mem.copyForwards(u8, buf[0 .. len - m.consumed], buf[m.consumed..len]);
len -= m.consumed;
},
.incomplete => break :drain,
// a complete header that is not a frame we can speak: nothing
// after it can ever re-synchronize, so the connection is over —
// this must NOT read as "incomplete", which would buffer the
// poison forever while every request quietly times out
.poison => break :outer,
};
// grow when a frame is bigger than the space that is left
if (len == buf.len) {
if (buf.len >= 64 << 20) break :outer;
const bigger = sa.realloc(buf, buf.len * 2) catch break :outer;
buf = bigger;
}
var pfd = [_]libc.pollfd{.{ .fd = sock, .events = libc.POLL.IN, .revents = 0 }};
const pr = libc.poll(&pfd, 1, 1000);
if (pr < 0) {
if (libc.errno(pr) == .INTR) continue;
break :outer;
}
if (pr == 0) {
// tick: a respawn while the server was silent leaves this thread
// reading a corpse; notice and go
c.mu.lockUncancelable(io);
const stale = c.gen != g;
c.mu.unlock(io);
if (stale) break :outer;
continue;
}
const got = libc.recv(sock, buf.ptr + len, buf.len - len, 0);
if (got < 0) {
const e = libc.errno(got);
if (e == .INTR or e == .AGAIN) continue;
break :outer;
}
if (got == 0) break :outer; // the server exited or shutdownIf spoke
len += @intCast(got);
}
readerExit(c, io, si, g, sock);
}
fn readerExit(c: *Conn, io: std.Io, si: usize, g: u32, sock: c_int) void {
c.mu.lockUncancelable(io);
if (c.gen == g and c.alive()) {
// the server died on its own — shutdownIf never saw it, so the corpse
// is ours to reap and the conn's transport fields are ours to clear
c.state = .dead;
reap(c.pid);
c.pid = -1;
c.sock = -1;
// A server that keeps crashing right after its handshake would
// otherwise respawn on every keystroke — the handshake SUCCEEDING
// resets the backoff, so the crash has to count as the failure it
// is. A long-lived server that dies gets one free respawn.
if (nowMs() - c.ready_at_ms < 30_000) {
c.handshake_fails +|= 1;
const wait = backoffMs(c.handshake_fails);
c.retry_after_ms = nowMs() + wait;
post(si, .always, "{s} crashed — retrying in {d}s", .{ specs[si].name, @divTrunc(wait, 1000) });
} else {
post(si, .always, "{s} exited — restarts on the next query", .{specs[si].name});
}
c.cond.broadcast(io);
}
c.mu.unlock(io);
// A query writes with the mutex let go (send): the fd stays its until
// that write is done, and shutdown(2) has already made it fail fast.
c.write_mu.lockUncancelable(io);
_ = libc.close(sock);
c.write_mu.unlock(io);
}
/// 10s doubling to 2min: the fork-per-keystroke guard's schedule.
fn backoffMs(fails: u8) i64 {
const shift: u5 = @min(fails -| 1, 4);
return @as(i64, 10_000) << shift;
}
const Framed = struct { body_start: usize, body_end: usize, consumed: usize };
const FrameStep = union(enum) {
/// keep reading; the head of the buffer may still become a frame
incomplete,
/// a complete, valid frame
frame: Framed,
/// a complete header that cannot be a frame (no/invalid/oversized
/// Content-Length): the stream can never re-synchronize
poison,
};
/// One Content-Length-framed message at the head of `data`. Pure — this is
/// the whole wire format, and it is testable without a socket.
fn frameNext(data: []const u8) FrameStep {
const sep = std.mem.indexOf(u8, data, "\r\n\r\n") orelse return .incomplete;
var clen: ?usize = null;
var it = std.mem.splitSequence(u8, data[0..sep], "\r\n");
while (it.next()) |line| {
const colon = std.mem.indexOfScalar(u8, line, ':') orelse continue;
if (!std.ascii.eqlIgnoreCase(std.mem.trim(u8, line[0..colon], " "), "content-length")) continue;
clen = std.fmt.parseInt(usize, std.mem.trim(u8, line[colon + 1 ..], " "), 10) catch null;
}
const n = clen orelse return .poison;
const start = sep + 4;
if (n > 64 << 20) return .poison;
if (data.len < start + n) return .incomplete;
return .{ .frame = .{ .body_start = start, .body_end = start + n, .consumed = start + n } };
}
/// One message from the server. Parses into a throwaway arena; touches conn
/// state only under the mutex; replies never hold it (bounded writes must not
/// stall the mailbox).
fn dispatch(c: *Conn, io: std.Io, si: usize, g: u32, sock: c_int, raw: []const u8, arena_state: *std.heap.ArenaAllocator) void {
// The reader's one parse arena, reset per message: no mapping per
// `$/progress` report, and no more than parse_kept kept between them.
defer _ = arena_state.reset(.{ .retain_with_limit = parse_kept });
const arena = arena_state.allocator();
const v = std.json.parseFromSliceLeaky(std.json.Value, arena, raw, .{}) catch return;
if (v != .object) return;
if (str(get(v, "method"))) |method| {
if (get(v, "id")) |id| return serverRequest(c, io, arena, sock, method, id, get(v, "params"));
return notification(c, io, si, g, raw, method, get(v, "params"));
}
// a response: deliver to the one waiting query, if it is still waiting
const id = num(get(v, "id")) orelse return;
c.mu.lockUncancelable(io);
defer c.mu.unlock(io);
if (c.gen == g and c.want_id != 0 and id == c.want_id and c.resp == null) {
c.resp = sa.dupe(u8, raw) catch null;
c.cond.broadcast(io);
}
}
/// The server asked US something. Everything optional was declined in the
/// handshake, so a null-ish answer is always legal — but it must ARRIVE, or
/// the server blocks forever on its own question.
fn serverRequest(c: *Conn, io: std.Io, arena: std.mem.Allocator, sock: c_int, method: []const u8, id: std.json.Value, params: ?std.json.Value) void {
var b: std.ArrayList(u8) = .empty;
b.appendSlice(arena, "{\"jsonrpc\":\"2.0\",\"id\":") catch return;
switch (id) {
.integer => |n| b.print(arena, "{d}", .{n}) catch return,
.string => |t| jstr(&b, arena, t) catch return,
else => b.appendSlice(arena, "null") catch return,
}
if (std.mem.eql(u8, method, "workspace/configuration")) {
// one null per asked item — a bare null here is a protocol violation
// some servers punish with a parse loop
const n = items(get(params, "items")).len;
b.appendSlice(arena, ",\"result\":[") catch return;
for (0..n) |i| b.appendSlice(arena, if (i == 0) "null" else ",null") catch return;
b.appendSlice(arena, "]}") catch return;
} else if (std.mem.eql(u8, method, "workspace/applyEdit")) {
b.appendSlice(arena, ",\"result\":{\"applied\":false}}") catch return;
} else {
b.appendSlice(arena, ",\"result\":null}") catch return;
}
answerServer(c, io, sock, b.items);
}
fn notification(c: *Conn, io: std.Io, si: usize, g: u32, raw: []const u8, method: []const u8, params: ?std.json.Value) void {
const Method = enum { @"textDocument/publishDiagnostics", @"$/progress", @"window/showMessage", @"experimental/serverStatus" };
switch (std.meta.stringToEnum(Method, method) orelse return) {
.@"textDocument/publishDiagnostics" => {
const uri = str(get(params, "uri")) orelse return;
// keep the raw MESSAGE (params included); re-parsing it per query
// beats owning a parsed tree past this arena's life
const body = sa.dupe(u8, raw) catch return;
c.mu.lockUncancelable(io);
defer c.mu.unlock(io);
if (c.gen != g) {
sa.free(body);
return;
}
for (c.docs.items) |*d| if (std.mem.eql(u8, d.uri, uri)) {
d.stale = false;
break;
};
var slot: ?*DiagSet = null;
for (c.diags.items) |*d| if (std.mem.eql(u8, d.uri, uri)) {
slot = d;
break;
};
// Bounded in files and bytes: a new set that does not fit pushes
// out the oldest files' (the server sends a file's again when it
// changes); one bigger than the whole store is not kept.
if (body.len > max_diag_bytes) {
sa.free(body);
return;
}
if (slot) |d| {
c.diag_bytes -= d.body.len;
sa.free(d.body);
d.body = body;
c.diag_bytes += body.len;
} else {
while (c.diags.items.len > 0 and (c.diags.items.len >= max_diag_files or c.diag_bytes + body.len > max_diag_bytes)) {
const old = c.diags.orderedRemove(0);
c.diag_bytes -= old.body.len;
sa.free(old.uri);
sa.free(old.body);
}
const owned = sa.dupe(u8, uri) catch {
sa.free(body);
return;
};
c.diags.append(sa, .{ .uri = owned, .body = body }) catch {
sa.free(owned);
sa.free(body);
return;
};
c.diag_bytes += body.len;
}
c.cond.broadcast(io); // waitFresh watches this
},
.@"$/progress" => {
const value = get(params, "value") orelse return;
const pkind = str(get(value, "kind")) orelse return;
const msg = str(get(value, "message")) orelse "";
c.mu.lockUncancelable(io);
if (c.gen != g) {
c.mu.unlock(io);
return;
}
if (std.mem.eql(u8, pkind, "begin")) {
c.progress += 1;
const title = str(get(value, "title")) orelse "";
c.title_len = @intCast(@min(title.len, c.title.len));
@memcpy(c.title[0..c.title_len], title[0..c.title_len]);
var tbuf: [48]u8 = undefined;
const t = tbuf[0..c.title_len];
@memcpy(t, c.title[0..c.title_len]);
c.mu.unlock(io);
post(si, .chatty, "{s}: {s}\u{2026} {s}", .{ specs[si].name, t, msg });
return;
}
if (std.mem.eql(u8, pkind, "report")) {
var tbuf: [48]u8 = undefined;
const t = tbuf[0..c.title_len];
@memcpy(t, c.title[0..c.title_len]);
const pct = num(get(value, "percentage"));
c.mu.unlock(io);
if (pct) |p|
post(si, .chatty, "{s}: {s} {d}% {s}", .{ specs[si].name, t, p, msg })
else
post(si, .chatty, "{s}: {s} {s}", .{ specs[si].name, t, msg });
return;
}
// end
c.progress -= 1;
const idle = c.progress <= 0;
if (idle) c.progress = 0;
c.mu.unlock(io);
// the setpoint every burst of progress ends on; `.always` + the
// dedupe above means it lands exactly once however the reports raced
if (idle) post(si, .always, "{s}: ready", .{specs[si].name});
},
.@"window/showMessage" => {
const t = num(get(params, "type")) orelse 3;
if (t > 2) return; // info/log are the server's diary, not the user's
post(si, .always, "{s}: {s}", .{ specs[si].name, str(get(params, "message")) orelse "" });
},
// rust-analyzer's precise quiescence signal, opted into via
// experimental.serverStatusNotification
.@"experimental/serverStatus" => {
const health = str(get(params, "health")) orelse "ok";
const quiescent = if (get(params, "quiescent")) |q| q == .bool and q.bool else false;
c.mu.lockUncancelable(io);
if (c.gen == g) {
c.loading = !quiescent;
c.cond.broadcast(io);
}
c.mu.unlock(io);
if (!std.mem.eql(u8, health, "ok"))
post(si, .always, "{s}: {s} — {s}", .{ specs[si].name, health, str(get(params, "message")) orelse "" })
else if (quiescent)
post(si, .always, "{s}: ready", .{specs[si].name});
},
}
}
// ------------------------------------------------------------- introspection
fn status(io: std.Io, path: []const u8, out: *std.Io.Writer) !void {
// The index the file would ask first, what it holds and how old it is.
const dir = std.Io.Dir.path.dirname(path) orelse "/";
if (Scip.find(io, dir)) |found| if (found) |ix| {
var symbols: usize = 0;
for (ix.infos.items) |info| symbols += @intFromBool(info.len > 0);
var newer: usize = 0;
var pbuf: [4096]u8 = undefined;
for (ix.documents) |d| newer += @intFromBool(ix.stale(io, std.fmt.bufPrint(&pbuf, "{s}/{s}", .{ ix.root(), d.path }) catch continue));
try out.print("scip: {s}, {d} KB, {d} documents, {d} symbols", .{ ix.path(), (ix.size + 999) / 1000, ix.documents.len, symbols });
if (!hideTime()) {
const secs: std.time.epoch.EpochSeconds = .{ .secs = @intCast(@divTrunc(ix.mtime, std.time.ns_per_s)) };
const day = secs.getEpochDay().calculateYearDay();
const md = day.calculateMonthDay();
try out.print(", indexed {d}-{d:0>2}-{d:0>2} {d:0>2}:{d:0>2} UTC", .{ day.year, md.month.numeric(), md.day_index + 1, secs.getDaySeconds().getHoursIntoDay(), secs.getDaySeconds().getMinutesIntoHour() });
}
try out.print(", {d} files newer\n", .{newer});
} else {
try out.print("scip: no index.scip above {s}", .{dir});
if (specFor(path)) |si| try out.print("; Index runs {s}", .{if (libc.getenv(indexer_envs[si])) |v| std.mem.span(v) else specs[si].indexer});
try out.writeByte('\n');
} else |e| try out.print("scip: index.scip above {s}: {s}\n", .{ dir, @errorName(e) });
try out.print("language servers:\n", .{});
for (&specs, 0..) |*s, i| {
const c = &conns[i];
c.mu.lockUncancelable(io);
const state = c.state;
var rootbuf: [256]u8 = undefined;
const rootlen = @min(c.root.len, rootbuf.len);
@memcpy(rootbuf[0..rootlen], c.root[0..rootlen]);
const root = rootbuf[0..rootlen];
const enc = c.caps.enc;
const ndocs = c.docs.items.len;
const ndiag = c.diags.items.len;
const pull = c.caps.pull;
const chier = c.caps.call_hier;
const thier = c.caps.type_hier;
c.mu.unlock(io);
const env_v = if (libc.getenv(s.env)) |v| std.mem.span(v) else null;
// Never spawned is not off: the first query of its files starts it.
try out.print(" {s:<28} {s}", .{ s.name, if (state == .off) "not started yet (its first query starts it)" else @tagName(state) });
if (state == .ready or state == .starting) {
try out.print(" root {s} {s}", .{ root, @tagName(enc) });
if (pull) try out.print(" pull-diags", .{});
if (chier) try out.print(" call-hier", .{});
if (thier) try out.print(" type-hier", .{});
try out.print(" docs {d} diag-files {d}", .{ ndocs, ndiag });
}
if (env_v) |v| try out.print(" [{s}={s}]", .{ s.env, if (v.len == 0) "(disabled)" else v });
try out.print("\n ", .{});
for (s.exts) |e| try out.print("{s} ", .{e});
try out.print("\n", .{});
}
while (!log_mu.tryLock()) std.atomic.spinLoopHint();
defer log_mu.unlock();
try out.print("\nclient queries ({d} total, keeping {d}):\n", .{ log_total, log_cap });
var shown: usize = 0;
for (0..log_cap) |i| {
const e = &log_buf[(log_next + i) % log_cap];
if (!e.used) continue;
shown += 1;
if (hideTime()) {
try out.print(" {s:<18} {s:<14} {s:<20} {d:>4} row(s){s}{s}\n", .{
@tagName(e.kind), sourceName(e.spec), e.file[0..e.file_len], e.rows,
if (e.err_len > 0) " ERROR " else "", e.err[0..e.err_len],
});
} else {
try out.print(" {s:<18} {s:<14} {s:<20} {d:>7}us {d:>4} row(s){s}{s}\n", .{
@tagName(e.kind), sourceName(e.spec), e.file[0..e.file_len], e.us, e.rows,
if (e.err_len > 0) " ERROR " else "", e.err[0..e.err_len],
});
}
}
if (shown == 0) try out.print(" (none yet — press gd in a file with a server, then ask again)\n", .{});
}
// ------------------------------------------------------------------ plumbing
/// `"textDocument":{"uri":U}` — the params every request about a file
/// starts with.
fn docParams(arena: std.mem.Allocator, uri: []const u8) Err!std.ArrayList(u8) {
var b: std.ArrayList(u8) = .empty;
try b.appendSlice(arena, "\"textDocument\":{\"uri\":");
try jstr(&b, arena, uri);
try b.appendSlice(arena, "}");
return b;
}
/// `"textDocument":{"uri":U},"position":{...}` — the params shared by every
/// position request.
fn atPos(arena: std.mem.Allocator, uri: []const u8, pos: Pos) Err!std.ArrayList(u8) {
var b = try docParams(arena, uri);
try b.print(arena, ",\"position\":{{\"line\":{d},\"character\":{d}}}", .{ pos.line, pos.ch });
return b;
}
/// A message to the server from a query, the conn's mutex let go while it is
/// written: the reader goes on taking the server's output meanwhile, which a
/// server may be waiting to write before it reads more of ours.
fn send(c: *Conn, io: std.Io, body: []const u8, deadline: i64) Err!void {
const sock = c.sock;
c.mu.unlock(io);
defer c.mu.lockUncancelable(io);
return frame(c, io, sock, body, deadline);
}
fn frame(c: *Conn, io: std.Io, sock: c_int, body: []const u8, deadline: i64) Err!void {
if (sock < 0) return error.Dead;
c.write_mu.lockUncancelable(io);
defer releaseWrite(c, io, sock);
var hdr: [64]u8 = undefined;
const h = std.fmt.bufPrint(&hdr, "Content-Length: {d}\r\n\r\n", .{body.len}) catch return error.Protocol;
var started = false;
try sockWrite(io, sock, h, deadline, &started);
try sockWrite(io, sock, body, deadline, &started);
}
/// The reader's answer to a server request: written now if the socket is
/// free, else queued for the query writing (bounded; one that does not fit is
/// dropped, and the server's request goes unanswered).
fn answerServer(c: *Conn, io: std.Io, sock: c_int, body: []const u8) void {
var hdr: [64]u8 = undefined;
const h = std.fmt.bufPrint(&hdr, "Content-Length: {d}\r\n\r\n", .{body.len}) catch unreachable; // a usize's 20 digits and a short header fit 64
c.replies_mu.lockUncancelable(io);
const half = &c.replies[c.filling];
const len = &c.replies_len[c.filling];
if (len.* + h.len + body.len <= half.len) {
@memcpy(half[len.*..][0..h.len], h);
@memcpy(half[len.* + h.len ..][0..body.len], body);
len.* += h.len + body.len;
}
c.replies_mu.unlock(io);
if (c.write_mu.tryLock()) releaseWrite(c, io, sock);
}
/// Lets the socket go, first sending what the reader queued meanwhile, and
/// again for what it queues while that goes out.
fn releaseWrite(c: *Conn, io: std.Io, sock: c_int) void {
while (true) {
c.replies_mu.lockUncancelable(io);
const sent = c.filling;
const n = c.replies_len[sent];
if (n > 0) c.filling ^= 1;
c.replies_mu.unlock(io);
if (n > 0) {
var started = false;
sockWrite(null, sock, c.replies[sent][0..n], nowMs() + reply_ms, &started) catch {};
c.replies_len[sent] = 0;
}
c.write_mu.unlock(io);
c.replies_mu.lockUncancelable(io);
const more = c.replies_len[c.filling] > 0;
c.replies_mu.unlock(io);
if (!more or !c.write_mu.tryLock()) return;
}
}
/// Writes `bytes`, `started` once any byte of their message is out. Before
/// then, the deadline and a cancel stop it; after, the message is finished
/// however long the server takes to read it (bounded by wedge_ms), since
/// half of one ends the server's reading of every message after it.
fn sockWrite(io: ?std.Io, sock: c_int, bytes: []const u8, deadline: i64, started: *bool) Err!void {
var off: usize = 0;
while (off < bytes.len) {
if (!started.*) {
if (deadline - nowMs() <= 0) return error.Timeout;
if (io) |cancel_io| cancel_io.checkCancel() catch return error.Canceled;
} else if (nowMs() - deadline > wedge_ms) return error.Dead;
var pfd = [_]libc.pollfd{.{ .fd = sock, .events = libc.POLL.OUT, .revents = 0 }};
const pr = libc.poll(&pfd, 1, 500);
if (pr < 0) {
if (libc.errno(pr) == .INTR) continue;
return error.Dead;
}
if (pr == 0) continue;
const n = libc.send(sock, bytes.ptr + off, bytes.len - off, msg_nosignal);
if (n < 0) {
const e = libc.errno(n);
if (e == .INTR or e == .AGAIN) continue;
return error.Dead;
}
if (n == 0) return error.Dead;
started.* = true;
off += @intCast(n);
}
}
fn nowMs() i64 {
var ts: libc.timespec = undefined;
_ = libc.clock_gettime(.MONOTONIC, &ts);
return @as(i64, @intCast(ts.sec)) * 1000 + @divTrunc(@as(i64, @intCast(ts.nsec)), 1_000_000);
}
fn nowUs() u64 {
var ts: libc.timespec = undefined;
_ = libc.clock_gettime(.MONOTONIC, &ts);
return @as(u64, @intCast(ts.sec)) *| 1_000_000 +| @as(u64, @intCast(ts.nsec)) / 1000;
}
/// The spec's binary: the env override when set, else `bin`, PATH-searched
/// unless it names a path.
fn binOf(spec: *const Spec, buf: *[4096:0]u8) ?[:0]const u8 {
const name = if (libc.getenv(spec.env)) |v| std.mem.span(v) else spec.bin;
if (name.len == 0) return null;
if (std.mem.indexOfScalar(u8, name, '/') != null) {
const z = std.fmt.bufPrintSentinel(buf, "{s}", .{name}, 0) catch return null;
return if (libc.access(z.ptr, libc.X_OK) == 0) z else null;
}
const path = if (libc.getenv("PATH")) |p| std.mem.span(p) else "/usr/local/bin:/usr/bin:/bin";
var it = std.mem.tokenizeScalar(u8, path, ':');
while (it.next()) |dir| {
const cand = std.fmt.bufPrintSentinel(buf, "{s}/{s}", .{ dir, name }, 0) catch continue;
if (libc.access(cand.ptr, libc.X_OK) == 0) return cand;
}
return null;
}
/// Where the project starts: helix's find_root rule. Walk UP from `dir`; the
/// TOP-MOST directory holding a language marker wins (a cargo workspace's
/// root Cargo.toml beats the member crate's), the CLOSEST `.git` is the
/// fallback, the asking directory the last resort.
fn rootOf(dir: []const u8, markers: []const []const u8) []const u8 {
if (dir.len == 0 or dir[0] != '/') return "/";
var top_marker: ?[]const u8 = null;
var git: ?[]const u8 = null;
var d = dir;
var buf: [4096:0]u8 = undefined;
while (true) {
for (markers) |marker| {
const p = std.fmt.bufPrintSentinel(&buf, "{s}/{s}", .{ d, marker }, 0) catch continue;
if (libc.access(p.ptr, libc.F_OK) == 0) {
top_marker = d;
break;
}
}
if (git == null) {
if (std.fmt.bufPrintSentinel(&buf, "{s}/.git", .{d}, 0)) |p| {
if (libc.access(p.ptr, libc.F_OK) == 0) git = d;
} else |_| {}
}
d = std.Io.Dir.path.dirname(d) orelse break;
if (d.len <= 1) break;
}
return top_marker orelse git orelse dir;
}
/// A path as a `file://` URI, raw (no JSON quotes). Everything outside the
/// unreserved set is percent-encoded; `/` stays a separator.
fn uriOf(b: *std.ArrayList(u8), arena: std.mem.Allocator, path: []const u8) Err!void {
try b.appendSlice(arena, "file://");
for (path) |ch| {
if (std.ascii.isAlphanumeric(ch) or ch == '/' or ch == '-' or ch == '_' or ch == '.' or ch == '~') {
try b.append(arena, ch);
} else {
try b.print(arena, "%{X:0>2}", .{ch});
}
}
}
/// `file:///a/b%20c` -> `/a/b c`. Rows carry real paths; look.zig opens them
/// and `%20` is not a filename. A decoded CONTROL byte rejects the whole uri:
/// a `%0A` in a path would split one location into two physical rows — a
/// server-forged extra row in the results buffer — and no path worth opening
/// has a newline, tab or NUL in it.
fn pathOf(arena: std.mem.Allocator, uri: []const u8) ?[]const u8 {
var rest = uri;
if (std.mem.startsWith(u8, rest, "file://")) {
rest = rest["file://".len..];
if (rest.len > 0 and rest[0] != '/') return null; // an authority we cannot open
} else if (std.mem.indexOf(u8, rest, "://") != null) return null;
var out: std.ArrayList(u8) = .empty;
var i: usize = 0;
while (i < rest.len) {
var byte: u8 = rest[i];
if (rest[i] == '%' and i + 2 < rest.len) {
if (std.fmt.parseInt(u8, rest[i + 1 .. i + 3], 16)) |b| {
byte = b;
i += 3;
} else |_| i += 1;
} else i += 1;
if (byte < 0x20) return null;
out.append(arena, byte) catch return null;
}
return out.items;
}
/// A JSON string. Invalid UTF-8 becomes `?` one byte at a time rather than
/// U+FFFD: a buffer being typed into may be invalid mid-keystroke, and a
/// replacement that changed byte lengths would move every offset after it.
fn jstr(b: *std.ArrayList(u8), arena: std.mem.Allocator, s: []const u8) Err!void {
try b.append(arena, '"');
var i: usize = 0;
while (i < s.len) {
const ch = s[i];
if (ch < 0x80) {
switch (ch) {
'"' => try b.appendSlice(arena, "\\\""),
'\\' => try b.appendSlice(arena, "\\\\"),
'\n' => try b.appendSlice(arena, "\\n"),
'\r' => try b.appendSlice(arena, "\\r"),
'\t' => try b.appendSlice(arena, "\\t"),
else => if (ch < 0x20)
try b.print(arena, "\\u{x:0>4}", .{ch})
else
try b.append(arena, ch),
}
i += 1;
continue;
}
const l = std.unicode.utf8ByteSequenceLength(ch) catch {
try b.append(arena, '?');
i += 1;
continue;
};
if (i + l > s.len or !std.unicode.utf8ValidateSlice(s[i .. i + l])) {
try b.append(arena, '?');
i += 1;
continue;
}
try b.appendSlice(arena, s[i .. i + l]);
i += l;
}
try b.append(arena, '"');
}
const Pos = struct { line: u32, ch: u32 };
/// Byte offset -> LSP position. `lsp.lineCol` gives the line and the BYTE
/// column; only the column needs re-counting, and only when the server
/// refused utf-8.
fn posOf(src: []const u8, off: u32, enc: Enc) Pos {
const lc = lsp.lineCol(src, off);
if (enc == .utf8) return .{ .line = @intCast(lc.line), .ch = @intCast(lc.col) };
const bol = @min(off, src.len) - lc.col;
var units: u32 = 0;
var i: usize = bol;
while (i < bol + lc.col) {
const l = std.unicode.utf8ByteSequenceLength(src[i]) catch 1;
units += if (l == 4 and enc == .utf16) 2 else 1;
i += l;
}
return .{ .line = @intCast(lc.line), .ch = units };
}
// std.json.Value navigation: optional-in, optional-out, so a missing field
// and a wrongly-typed one read the same and neither can panic on a server
// that sends the unexpected.
fn get(v: ?std.json.Value, key: []const u8) ?std.json.Value {
const o = v orelse return null;
if (o != .object) return null;
return o.object.get(key);
}
fn str(v: ?std.json.Value) ?[]const u8 {
const o = v orelse return null;
return if (o == .string) o.string else null;
}
fn num(v: ?std.json.Value) ?i64 {
const o = v orelse return null;
return if (o == .integer) o.integer else null;
}
fn items(v: ?std.json.Value) []std.json.Value {
const o = v orelse return &.{};
return if (o == .array) o.array.items else &.{};
}
const Range = Scip.Range;
fn rangeOf(range: ?std.json.Value) ?Range {
const st = get(range, "start") orelse return null;
const en = get(range, "end") orelse return null;
return .{
.sl = coord(get(st, "line")) orelse return null,
.sc = coord(get(st, "character")) orelse return null,
.el = coord(get(en, "line")) orelse return null,
.ec = coord(get(en, "character")) orelse return null,
};
}
/// One protocol coordinate, VALIDATED rather than clamped: a negative line is
/// not "line zero", it is a malformed response, and a value past u32 would
/// panic the @intCast that follows. Server bytes are not trusted bytes.
fn coord(v: ?std.json.Value) ?u32 {
const n = num(v) orelse return null;
if (n < 0 or n > std.math.maxInt(u32)) return null;
return @intCast(n);
}
// ----------------------------------------------------------------- tests
test "caller trees reverse incoming paths and merge shared callers and sites" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
const fixture = try std.json.parseFromSliceLeaky(std.json.Value, arena, "[{\"from\":{\"name\":\"left\",\"uri\":\"file:///test.c\",\"selectionRange\":{\"start\":{\"line\":3,\"character\":0},\"end\":{\"line\":3,\"character\":4}}},\"fromRanges\":[{\"start\":{\"line\":3,\"character\":0},\"end\":{\"line\":3,\"character\":4}}]},{\"from\":{\"name\":\"right\",\"uri\":\"file:///test.c\",\"selectionRange\":{\"start\":{\"line\":4,\"character\":0},\"end\":{\"line\":4,\"character\":4}}},\"fromRanges\":[{\"start\":{\"line\":4,\"character\":0},\"end\":{\"line\":4,\"character\":4}}]},{\"from\":{\"name\":\"page\",\"uri\":\"file:///test.c\",\"selectionRange\":{\"start\":{\"line\":1,\"character\":0},\"end\":{\"line\":1,\"character\":4}}},\"fromRanges\":[{\"start\":{\"line\":1,\"character\":0},\"end\":{\"line\":1,\"character\":4}}]},{\"from\":{\"name\":\"page\",\"uri\":\"file:///test.c\",\"selectionRange\":{\"start\":{\"line\":1,\"character\":0},\"end\":{\"line\":1,\"character\":4}}},\"fromRanges\":[{\"start\":{\"line\":2,\"character\":0},\"end\":{\"line\":2,\"character\":4}}]},{\"from\":{\"name\":\"main\",\"uri\":\"file:///test.c\",\"selectionRange\":{\"start\":{\"line\":0,\"character\":0},\"end\":{\"line\":0,\"character\":4}}},\"fromRanges\":[{\"start\":{\"line\":0,\"character\":0},\"end\":{\"line\":0,\"character\":4}}]}]", .{});
const entries = try serverHops(arena, fixture);
var tree: CallTree = .{};
try tree.addPath(arena, &.{ entries[0], entries[2], entries[4] }, false);
try tree.addPath(arena, &.{ entries[1], entries[3], entries[4] }, false);
try std.testing.expectEqual(@as(usize, 1), tree.roots.items.len);
try std.testing.expectEqual(@as(usize, 4), tree.nodes.items.len);
const root = tree.nodes.items[tree.roots.items[0]];
try std.testing.expectEqualStrings("main", root.call.name);
try std.testing.expectEqual(@as(usize, 1), root.ranges.items.len);
const page = tree.nodes.items[root.children.items[0]];
try std.testing.expectEqual(@as(usize, 2), page.children.items.len);
try std.testing.expectEqual(@as(usize, 2), page.ranges.items.len);
try std.testing.expect(!root.ranges.items[0].focus);
for (page.ranges.items) |site| try std.testing.expect(!site.focus);
for (page.children.items) |id| try std.testing.expect(tree.nodes.items[id].ranges.items[0].focus);
var out: std.Io.Writer.Allocating = .init(arena);
var cx: Cx = .{ .io = std.testing.io, .arena = arena, .base = "/", .cur_path = "/test.c", .cur_src = "main_call();\npage_left();\npage_right();\nleft_call();\nright_call();\n", .out = &out.writer };
try renderCallers(&cx, .utf8, &tree, tree.roots.items, 0);
const text = out.written();
try std.testing.expectEqual(@as(usize, 2), std.mem.count(u8, text, lsp.callstack_match));
const main_at = std.mem.indexOf(u8, text, " main\n").?;
const page_at = std.mem.indexOf(u8, text, " page\n").?;
const left_at = std.mem.indexOf(u8, text, " left\n").?;
const right_at = std.mem.indexOf(u8, text, " right\n").?;
try std.testing.expect(main_at < page_at and page_at < left_at and left_at < right_at);
try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, text, "main_call();"));
try std.testing.expect(std.mem.indexOf(u8, text, "page_left();").? < std.mem.indexOf(u8, text, "page_right();").?);
try std.testing.expect(std.mem.indexOf(u8, text, "├──┬ test.c:4:") != null);
try std.testing.expect(std.mem.indexOf(u8, text, "╰──┬ test.c:1:") != null);
var recursive: CallTree = .{};
try recursive.addPath(arena, &.{ entries[0], entries[0] }, true);
try std.testing.expect(!recursive.nodes.items[recursive.roots.items[0]].cycle);
try std.testing.expect(recursive.nodes.items[1].cycle);
}
test "test callers sort after the rest, each group by place" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
const fixture = try std.json.parseFromSliceLeaky(std.json.Value, arena, "[{\"from\":{\"name\":\"test b\",\"uri\":\"file:///a.zig\",\"selectionRange\":{\"start\":{\"line\":0,\"character\":0},\"end\":{\"line\":0,\"character\":1}}}},{\"from\":{\"name\":\"z\",\"uri\":\"file:///b.zig\",\"selectionRange\":{\"start\":{\"line\":0,\"character\":0},\"end\":{\"line\":0,\"character\":1}}}},{\"from\":{\"name\":\"x\",\"uri\":\"file:///a_test.zig\",\"selectionRange\":{\"start\":{\"line\":0,\"character\":0},\"end\":{\"line\":0,\"character\":1}}}},{\"from\":{\"name\":\"y\",\"uri\":\"file:///a.zig\",\"selectionRange\":{\"start\":{\"line\":5,\"character\":0},\"end\":{\"line\":5,\"character\":1}}}}]", .{});
var tree: CallTree = .{};
for (try serverHops(arena, fixture)) |hop| try tree.nodes.append(arena, .{ .call = hop.call });
var order = [_]usize{ 0, 1, 2, 3 };
std.mem.sort(usize, &order, @as(*const CallTree, &tree), callerLess);
try std.testing.expectEqualSlices(usize, &.{ 3, 1, 0, 2 }, &order);
}
test "a mailbox wait is a cancelation point: a canceled worker stops waiting" {
const io = std.testing.io;
var c: Conn = .{};
const Waiter = struct {
fn run(conn: *Conn, wio: std.Io) error{Canceled}!void {
conn.mu.lockUncancelable(wio);
defer conn.mu.unlock(wio);
while (true) _ = try timedWait(conn, wio, nowMs() + 60_000);
}
};
var future = try io.concurrent(Waiter.run, .{ &c, io });
try std.testing.expectError(error.Canceled, future.cancel(io));
}
test "callstack cross-crate paths remain resolvable without absolute path clutter" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
const range = try std.json.parseFromSliceLeaky(std.json.Value, arena,
\\{"start":{"line":1,"character":3},"end":{"line":1,"character":6}}
, .{});
var out: std.Io.Writer.Allocating = .init(arena);
var cx: Cx = .{ .io = std.testing.io, .arena = arena, .base = "/workspace/merkle-tree/src", .cur_path = "", .cur_src = "", .out = &out.writer, .relative_parents = true };
try emitRange(&cx, .utf8, "file:///workspace/entry/src/entry.rs", range, "fn run()");
try std.testing.expectEqualStrings("../../entry/src/entry.rs:2:4-6 fn run()\n", out.written());
}
test "LSP client rename and format propagate incomplete edit encoding" {
const gpa = std.testing.allocator;
const uri = "file:///file.c";
const parsed = try std.json.parseFromSlice(std.json.Value, gpa,
\\{"changes":{"file:///file.c":[{"range":{"start":{"line":0,"character":0},"end":{"line":0,"character":3}},"newText":"A%\n"},{"range":{"start":{"line":0,"character":4},"end":{"line":0,"character":7}},"newText":"B"}]}}
, .{});
defer parsed.deinit();
const expected = "@put 0 3 A%25%0A\n@put 4 7 B\n";
for ([_]bool{ true, false }) |rename| {
var buffer: [128]u8 = undefined;
for (0..expected.len + 1) |capacity| {
var arena: std.heap.ArenaAllocator = .init(gpa);
defer arena.deinit();
var out: std.Io.Writer = .fixed(buffer[0..capacity]);
var cx: Cx = .{ .io = std.testing.io, .arena = arena.allocator(), .base = "/", .cur_path = "/file.c", .cur_src = "abc xyz", .out = &out };
const result = if (rename)
renameEdits(&cx, .utf8, uri, parsed.value, cx.cur_src, "abc", &.{})
else
formatEdits(&cx, .utf8, get(get(parsed.value, "changes"), uri).?, cx.cur_src);
if (capacity < expected.len) {
try std.testing.expectError(error.WriteFailed, result);
} else {
try result;
try std.testing.expectEqualStrings(expected, out.buffered());
}
}
}
}
test "a rename answered for this file alone, while another open file says the old name, previews and names it" {
const gpa = std.testing.allocator;
const parsed = try std.json.parseFromSlice(std.json.Value, gpa,
\\{"changes":{"file:///w/util.zig":[{"range":{"start":{"line":0,"character":7},"end":{"line":0,"character":10}},"newText":"sum"}]}}
, .{});
defer parsed.deinit();
var arena: std.heap.ArenaAllocator = .init(gpa);
defer arena.deinit();
var buffer: [512]u8 = undefined;
var out: std.Io.Writer = .fixed(&buffer);
var cx: Cx = .{ .io = std.testing.io, .arena = arena.allocator(), .base = "/w", .cur_path = "/w/util.zig", .cur_src = "pub fn add() void {}", .out = &out };
try renameEdits(&cx, .utf8, "file:///w/util.zig", parsed.value, cx.cur_src, "add", &.{"/w/main.zig"});
try std.testing.expectEqualStrings("util.zig:1:8-10 sum\nmain.zig: also says add, which the server did not rename\n", out.buffered());
try std.testing.expectEqualStrings("add", identAt("x = add(1);", 6));
try std.testing.expect(holdsWord("util.add(1)", "add") and !holdsWord("addNumbers", "add"));
}
test "frameNext distinguishes incomplete, valid and poison frames" {
try std.testing.expectEqual(FrameStep.incomplete, frameNext("Content-Length: 5\r\n"));
try std.testing.expectEqual(FrameStep.incomplete, frameNext("Content-Length: 5\r\n\r\nhel"));
const one = frameNext("Content-Length: 5\r\n\r\nhello").frame;
try std.testing.expectEqualStrings("hello", "Content-Length: 5\r\n\r\nhello"[one.body_start..one.body_end]);
const two = "content-length: 2\r\nX-Other: y\r\n\r\nab" ++ "Content-Length: 1\r\n\r\nz";
const first = frameNext(two).frame;
try std.testing.expectEqualStrings("ab", two[first.body_start..first.body_end]);
const second = frameNext(two[first.consumed..]).frame;
try std.testing.expectEqualStrings("z", two[first.consumed..][second.body_start..second.body_end]);
// complete-but-unusable headers can never re-synchronize: poison, not
// "keep buffering" — the wedge a review found and this line pins
try std.testing.expectEqual(FrameStep.poison, frameNext("Content-Length: nope\r\n\r\n"));
try std.testing.expectEqual(FrameStep.poison, frameNext("X-Only: y\r\n\r\n"));
try std.testing.expectEqual(FrameStep.poison, frameNext("Content-Length: 67108865\r\n\r\n"));
}
test "server coordinates are validated, not clamped" {
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
const bad = [_][]const u8{
\\{"start":{"line":-1,"character":0},"end":{"line":0,"character":1}}
,
\\{"start":{"line":0,"character":0},"end":{"line":0,"character":4294967296}}
,
\\{"start":{"line":0,"character":0},"end":{"line":0}}
};
for (bad) |json| {
const v = try std.json.parseFromSliceLeaky(std.json.Value, arena, json, .{});
try std.testing.expect(rangeOf(v) == null);
}
// strict offsets: past-EOL and past-EOF are refusals, EOL itself is real
const src = "ab\ncd";
try std.testing.expectEqual(@as(?usize, 2), strictOffset(src, 0, 2, .utf8));
try std.testing.expect(strictOffset(src, 0, 3, .utf8) == null);
try std.testing.expect(strictOffset(src, 2, 0, .utf8) == null);
try std.testing.expectEqual(@as(?usize, 5), strictOffset(src, 1, 2, .utf8));
}
test "uri round-trips spaces and utf-8" {
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
var b: std.ArrayList(u8) = .empty;
try uriOf(&b, arena, "/a dir/naïve.rs");
try std.testing.expectEqualStrings("file:///a%20dir/na%C3%AFve.rs", b.items);
try std.testing.expectEqualStrings("/a dir/naïve.rs", pathOf(arena, b.items).?);
try std.testing.expect(pathOf(arena, "file://host/x") == null);
// a %0A would split one location into two rows: rejected wholesale
try std.testing.expect(pathOf(arena, "file:///tmp/a%0A/tmp/b:1:1") == null);
try std.testing.expect(pathOf(arena, "file:///tmp/a%00b") == null);
try std.testing.expect(pathOf(arena, "https://x/y") == null);
}
test "posOf and strictOffset invert each other under both encodings" {
const src = "aé𝕏b\ncd\n"; // é: 2 bytes/1 unit, 𝕏: 4 bytes/2 units
inline for (.{ Enc.utf8, Enc.utf16 }) |enc| {
const off: u32 = 7; // the 'b'
const p = posOf(src, off, enc);
try std.testing.expectEqual(@as(u32, 0), p.line);
try std.testing.expectEqual(@as(?usize, off), strictOffset(src, p.line, p.ch, enc));
}
const p2 = posOf("aé𝕏b\ncd\n", 10, .utf16); // the 'd'
try std.testing.expectEqual(@as(u32, 1), p2.line);
try std.testing.expectEqual(@as(u32, 1), p2.ch);
}
test "rootOf takes the top-most marker and falls back to git then dir" {
// libc mkdtemp under /tmp rather than std.testing.tmpDir: rootOf probes
// with access(2) on ABSOLUTE paths, and /tmp has no ancestor markers to
// muddy the fallback assertions the way the repo's own .zig-cache does.
var tpl: [64:0]u8 = undefined;
_ = std.fmt.bufPrintSentinel(&tpl, "/tmp/pardes-rootof-XXXXXX", .{}, 0) catch unreachable;
const base_z = mkdtemp(&tpl) orelse return error.TestUnexpectedResult;
const base = std.mem.span(base_z);
defer {
var cmd: [128:0]u8 = undefined;
if (std.fmt.bufPrintSentinel(&cmd, "rm -rf {s}", .{base}, 0)) |z| _ = system(z.ptr) else |_| {}
}
var pb: [128:0]u8 = undefined;
for ([_][]const u8{ "/ws", "/ws/member", "/ws/member/src" }) |d| {
const z = try std.fmt.bufPrintSentinel(&pb, "{s}{s}", .{ base, d }, 0);
try std.testing.expect(libc.mkdir(z.ptr, 0o700) == 0);
}
for ([_][]const u8{ "/ws/Cargo.toml", "/ws/member/Cargo.toml" }) |f| {
const z = try std.fmt.bufPrintSentinel(&pb, "{s}{s}", .{ base, f }, 0);
const fd = libc.open(z.ptr, .{ .ACCMODE = .WRONLY, .CREAT = true }, @as(libc.mode_t, 0o600));
try std.testing.expect(fd >= 0);
_ = libc.close(fd);
}
const deep = try std.fmt.bufPrintSentinel(&pb, "{s}/ws/member/src", .{base}, 0);
const markers = [_][]const u8{"Cargo.toml"};
const root = rootOf(deep, &markers);
try std.testing.expect(std.mem.endsWith(u8, root, "/ws"));
// no language marker and no .git anywhere under /tmp: the asking dir wins
const nothing = rootOf(deep, &.{"no-such-marker"});
try std.testing.expect(std.mem.startsWith(u8, deep, nothing));
}
test "specFor routes extensions and honours the disable env" {
try std.testing.expect(specFor("/x/main.rs") != null);
try std.testing.expect(specFor("/x/README.md") == null);
try std.testing.expectEqualStrings("rust-analyzer", specs[specFor("/x/main.rs").?].name);
if (libc.getenv("PARDES_LSP_ZIG") == null) try std.testing.expectEqualStrings("zls", specs[specFor("/x/main.zig").?].name);
}
test "the transport this host actually gives us is a pair, and both ends are close-on-exec" {
// The spawn's FIRST fallible step, and for one release on macOS its last:
// `SOCK.CLOEXEC` is spelled for darwin in zig's libc bindings and rejected
// by darwin's socketpair(2), so this returned EPROTONOSUPPORT and no
// language server was ever forked on that platform. Nothing above the
// transport can notice — `ensure` reports the same `NoServer` a missing
// binary does — so the check belongs here, on the real function, in a test
// that runs on the host rather than on the linux target the snapshot
// suite cross-compiles to.
var sv: [2]libc.fd_t = undefined;
try std.testing.expect(transportPair(&sv));
defer {
_ = libc.close(sv[0]);
_ = libc.close(sv[1]);
}
// close-on-exec on both ends, however the platform got there: the flag on
// linux, fcntl on darwin. Without it every pty shell forked afterwards
// inherits the server's socket, which is the bug host_io.zig fixed for the
// pty master.
const FD_CLOEXEC: c_int = 1;
for (sv) |fd| try std.testing.expect(libc.fcntl(fd, libc.F.GETFD, @as(c_int, 0)) & FD_CLOEXEC != 0);
// and it is a connected PAIR, not two unrelated descriptors
const msg = "ping";
try std.testing.expectEqual(@as(isize, msg.len), libc.write(sv[0], msg, msg.len));
var got: [8]u8 = undefined;
try std.testing.expectEqual(@as(isize, msg.len), libc.read(sv[1], &got, got.len));
try std.testing.expectEqualStrings(msg, got[0..msg.len]);
}
test "LSP source snippets preserve indentation with UTF16 byte ranges and prose stays trimmed" {
const gpa = std.testing.allocator;
const source = "\t const 𝕏 = target; \t\r\n";
for ([_]bool{ false, true }) |multiline| {
var arena: std.heap.ArenaAllocator = .init(gpa);
defer arena.deinit();
const json = try std.fmt.allocPrint(arena.allocator(), "{{\"start\":{{\"line\":0,\"character\":14}},\"end\":{{\"line\":{d},\"character\":20}}}}", .{@as(u8, if (multiline) 1 else 0)});
const parsed = try std.json.parseFromSlice(std.json.Value, arena.allocator(), json, .{});
for ([_]bool{ false, true }) |prose| {
var buffer: [256]u8 = undefined;
var out: std.Io.Writer = .fixed(&buffer);
var cx: Cx = .{ .io = std.testing.io, .arena = arena.allocator(), .base = "/", .cur_path = "/file.c", .cur_src = source, .out = &out };
try emitRange(&cx, .utf16, "file:///file.c", parsed.value, if (prose) " explanatory label \t" else "");
const expected = try std.fmt.allocPrint(arena.allocator(), "file.c:1:17{s} {s}\n", .{
if (multiline) "" else "-22",
if (prose) "explanatory label" else "\t const 𝕏 = target; \t",
});
try std.testing.expectEqualStrings(expected, out.buffered());
try std.testing.expectEqual(@as(usize, 1), cx.rows);
}
}
}
test "a language with no server to start says so, not that it did not answer" {
const si = specFor("/x/a.py") orelse return;
const was = conns[si].state;
conns[si].state = .disabled;
defer conns[si].state = was;
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
var buf: [256]u8 = undefined;
var out: std.Io.Writer = .fixed(&buf);
try query(std.testing.io, arena.allocator(), .{ .kind = .hover, .path = "/x/a.py", .source = "", .offset = 0 }, &out);
try std.testing.expectEqualStrings("@none language server for .py not found\n", out.buffered());
}
test "Lspinfo before any query says a server is not started yet, not off" {
var out: std.Io.Writer.Allocating = .init(std.testing.allocator);
defer out.deinit();
try status(std.testing.io, "/x/notes.txt", &out.writer);
try std.testing.expect(std.mem.indexOf(u8, out.written(), "not started yet (its first query starts it)") != null);
}
test "a server that failed a moment ago is said to have failed, and when it is tried again, not to be missing" {
if (libc.getenv("PARDES_LSP_ZIG") != null) return error.SkipZigTest;
const io = std.testing.io;
const si = specFor("/x/a.zig").?;
const c = &conns[si];
c.mu.lockUncancelable(io);
const was = .{ c.state, c.retry_after_ms };
c.state = .dead;
c.retry_after_ms = nowMs() + 4500;
c.mu.unlock(io);
defer {
c.mu.lockUncancelable(io);
c.state = was[0];
c.retry_after_ms = was[1];
c.mu.unlock(io);
}
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
var out: std.Io.Writer.Allocating = .init(std.testing.allocator);
defer out.deinit();
try query(std.testing.io, arena.allocator(), .{ .kind = .hover, .path = "/x/a.zig", .source = "", .offset = 0 }, &out.writer);
try std.testing.expect(std.mem.indexOf(u8, out.written(), "zls failed recently; retry in 5s") != null);
}
test "reaping a server takes what it started with it: its process group goes, its children too" {
var fds: [2]libc.fd_t = undefined;
if (libc.pipe(&fds) != 0) return error.SkipZigTest;
const pid = libc.fork();
if (pid < 0) return error.SkipZigTest;
if (pid == 0) {
_ = libc.setsid();
const child = libc.fork();
if (child == 0) {
while (true) _ = usleep(100_000);
}
var word: [4]u8 = @bitCast(@as(i32, child));
_ = libc.write(fds[1], &word, 4);
while (true) _ = usleep(100_000);
}
_ = libc.close(fds[1]);
var word: [4]u8 = undefined;
try std.testing.expectEqual(@as(isize, 4), libc.read(fds[0], &word, 4));
_ = libc.close(fds[0]);
const grandchild: libc.pid_t = @bitCast(word);
reap(pid);
// Gone, or a zombie waiting for its new parent to reap it: not running.
var tries: u32 = 0;
const running = while (tries < 200) : (tries += 1) {
var path: [64]u8 = undefined;
const stat_path = try std.fmt.bufPrintSentinel(&path, "/proc/{d}/stat", .{grandchild}, 0);
const fd = libc.open(stat_path, .{ .ACCMODE = .RDONLY });
if (fd < 0) break false;
var buf: [256]u8 = undefined;
const n = libc.read(fd, &buf, buf.len);
_ = libc.close(fd);
if (n > 0) if (std.mem.lastIndexOfScalar(u8, buf[0..@intCast(n)], ')')) |close| {
if (buf[close + 2] == 'Z') break false;
};
_ = usleep(10_000);
} else true;
if (running) _ = libc.kill(grandchild, .KILL);
try std.testing.expect(!running);
}
|