summaryrefslogtreecommitdiff
path: root/core/syntax.zig
blob: 78bb6fd59c42499f3d700c9f2200772441581bcf (plain) (blame)
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
const std = @import("std");
const config = @import("pardes_options");
const tracy = @import("tracy.zig");
const grammar_manifest = @import("grammar_manifest.zig");
const locations = @import("locations.zig");
const regexp = @import("regexp.zig");
const c_heap = @import("c_heap");
const diff = @import("diff.zig");

/// The grammar sets built (`-Dgrammars`): a test that needs a grammar
/// not built skips.
pub const minimal_grammars = config.grammars != .none;
pub const full_grammars = config.grammars == .full;

pub const ts = @import("tree-sitter");
const ts_queries = @import("ts_queries");

const LanguageFn = *const fn () callconv(.c) *const ts.Language;

pub const Syn = grammar_manifest.Syn;

/// A query compiled when first asked for: "" for none, null when it fails.
const Lazy = struct { src: []const u8 = "", query: ?*ts.Query = null, failed: bool = false };

const Spec = struct {
    name: []const u8,
    exts: []const []const u8,
    /// A compiled-in grammar's, else `lang`, one handed in at run time.
    language: ?LanguageFn = null,
    lang: ?*const ts.Language = null,
    query_src: []const u8,
    /// helix's textobjects.scm and indents.scm for the grammar
    /// (vendor/queries), compiled the first time they are asked for
    objects: Lazy = .{},
    indents: Lazy = .{},
    selected: ?Selected = null,
    capture_styles: [256]u8 = undefined,
};

/// A grammar is in the build when the build gave its queries (build/core.zig
/// `treeSitter`): a tier's set, or the languages a package named.
fn grammarSelected(comptime g: grammar_manifest.Grammar) bool {
    return @hasDecl(ts_queries, g.name ++ "_highlights");
}

fn specCount() comptime_int {
    var count = 0;
    for (grammar_manifest.all) |g| {
        if (grammarSelected(g)) count += 1;
    }
    return count;
}
fn initSpecs() [specCount()]Spec {
    var out: [specCount()]Spec = undefined;
    var i = 0;
    inline for (grammar_manifest.all) |g| {
        if (grammarSelected(g)) {
            out[i] = .{
                .name = g.name,
                .exts = g.exts,
                .language = @extern(LanguageFn, .{ .name = "tree_sitter_" ++ g.name }),
                .query_src = @field(ts_queries, g.name ++ "_highlights"),
                .objects = .{ .src = @field(ts_queries, g.name ++ "_textobjects") },
                .indents = .{ .src = @field(ts_queries, g.name ++ "_indents") },
            };
            i += 1;
        }
    }
    return out;
}

var specs = initSpecs();

/// What tree-sitter allocates from, the runtime and every grammar's external
/// scanner (build.zig compiles them to use the runtime's allocator):
/// `start`'s allocator, through the shared C heap.
var syntax_allocator: std.mem.Allocator = undefined;
const syntax_heap = c_heap.Heap(&syntax_allocator);
var syntax_started = false;

extern fn ts_set_allocator(
    new_malloc: ?*const fn (size: usize) callconv(.c) ?*anyopaque,
    new_calloc: ?*const fn (nmemb: usize, size: usize) callconv(.c) ?*anyopaque,
    new_realloc: ?*const fn (ptr: ?*anyopaque, size: usize) callconv(.c) ?*anyopaque,
    new_free: ?*const fn (ptr: ?*anyopaque) callconv(.c) void,
) void;

pub fn start(gpa: std.mem.Allocator) void {
    std.debug.assert(!syntax_started);
    stop();
    syntax_allocator = gpa;
    syntax_started = true;
    ts_set_allocator(syntax_heap.malloc, syntax_heap.calloc, syntax_heap.realloc, syntax_heap.free);
}

pub fn stop() void {
    for (&specs) |*spec| dropSpec(spec);
    forgetLanguages();
    for (&diff_pieces) |*slot| {
        if (slot.*) |piece| syntax_allocator.free(piece.styles);
        slot.* = null;
    }
    diff_clock = 0;
    ts_set_allocator(null, null, null, null);
    syntax_started = false;
    syntax_allocator = undefined;
}

const Selected = struct {
    name: []const u8,
    lang: *const ts.Language,
    query: *ts.Query,
    parser: *ts.Parser,
    cursor: *ts.QueryCursor,
    capture_styles: []u8,
};

fn langOf(spec: *const Spec) *const ts.Language {
    return spec.lang orelse spec.language.?();
}

/// A grammar handed in at run time, beside the compiled-in ones: a
/// program's own (a sketch's language), its tree-sitter language and its
/// queries' sources, told by its extension (`.dsl`) as theirs are by
/// theirs. What it points at is the caller's: `forgetLanguages` before
/// the code it is in goes (a reload).
pub const Language = struct {
    name: []const u8,
    ext: []const u8,
    ts: *const ts.Language,
    highlights: []const u8 = "",
    textobjects: []const u8 = "",
    indents: []const u8 = "",

    /// A path its extension tells, in `buf`.
    pub fn path(l: Language, buf: []u8) []const u8 {
        return std.fmt.bufPrint(buf, "a{s}", .{l.ext}) catch "";
    }
};

var handed: [8]Spec = undefined;
var handed_exts: [8][1][]const u8 = undefined;
var handed_n: usize = 0;

/// `l` told by its extension from now on; one already told by it is
/// replaced (its parser and queries made again) unless it is the same.
/// False when eight are told already.
pub fn addLanguage(l: Language) bool {
    const at = for (handed[0..handed_n], 0..) |*spec, i| {
        if (std.mem.eql(u8, spec.exts[0], l.ext)) {
            if (spec.lang == l.ts and spec.query_src.ptr == l.highlights.ptr and spec.objects.src.ptr == l.textobjects.ptr) return true;
            dropSpec(spec);
            break i;
        }
    } else if (handed_n == handed.len) return false else handed_n;
    handed_exts[at] = .{l.ext};
    handed[at] = .{
        .name = l.name,
        .exts = &handed_exts[at],
        .lang = l.ts,
        .query_src = l.highlights,
        .objects = .{ .src = l.textobjects },
        .indents = .{ .src = l.indents },
    };
    handed_n = @max(handed_n, at + 1);
    return true;
}

/// Every grammar handed in at run time gone, with the parsers and queries
/// made for it.
pub fn forgetLanguages() void {
    for (handed[0..handed_n]) |*spec| dropSpec(spec);
    handed_n = 0;
}

fn dropSpec(spec: *Spec) void {
    if (spec.selected) |selected| {
        selected.cursor.destroy();
        selected.parser.destroy();
        selected.query.destroy();
    }
    spec.selected = null;
    for ([_]*Lazy{ &spec.objects, &spec.indents }) |lazy| {
        if (lazy.query) |q| q.destroy();
        lazy.* = .{ .src = lazy.src };
    }
}

/// The grammar a file's extension names: compiled in, else handed in.
fn byExt(ext: []const u8) ?*Spec {
    for (&specs) |*spec| for (spec.exts) |choice| {
        if (std.ascii.eqlIgnoreCase(ext, choice)) return spec;
    };
    for (handed[0..handed_n]) |*spec| if (std.ascii.eqlIgnoreCase(ext, spec.exts[0])) return spec;
    return null;
}

fn ensure(spec: *Spec) !Selected {
    if (spec.selected) |selected| return selected;
    const lang = langOf(spec);
    var error_offset: u32 = 0;
    const query = try ts.Query.create(lang, spec.query_src, &error_offset);
    errdefer query.destroy();
    if (query.captureCount() > spec.capture_styles.len) return error.TooManyCaptures;
    const capture_styles = spec.capture_styles[0..query.captureCount()];
    for (capture_styles, 0..) |*style, id| {
        const name = query.captureNameForId(@intCast(id)) orelse "";
        style.* = @backingInt(grammar_manifest.synFor(name));
        if (style.* == 0) query.disableCapture(name);
    }
    const parser = ts.Parser.create();
    errdefer parser.destroy();
    try parser.setLanguage(lang);
    const selected: Selected = .{
        .name = spec.name,
        .lang = lang,
        .query = query,
        .parser = parser,
        .cursor = ts.QueryCursor.create(),
        .capture_styles = capture_styles,
    };
    spec.selected = selected;
    return selected;
}

fn forExt(ext: []const u8) !?Selected {
    return try ensure(byExt(ext) orelse return null);
}

fn runQuery(styles: []u8, sel: Selected, tree: *ts.Tree, base: usize) void {
    const cursor = sel.cursor;
    cursor.exec(sel.query, tree.rootNode());
    while (cursor.nextMatch()) |match| {
        for (match.captures) |cap| {
            const style = sel.capture_styles[cap.index];
            if (style == 0) continue;
            const b = @min(base + cap.node.startByte(), styles.len);
            const end = @min(base + @as(usize, cap.node.endByte()), styles.len);
            if (end > b) @memset(styles[b..end], style);
        }
    }
}

pub fn highlightFileRange(gpa: std.mem.Allocator, path: []const u8, content: []const u8, start_raw: usize, end_raw: usize) ![]u8 {
    const zone = tracy.zone(@src(), "highlightFileRange");
    defer zone.end();
    const selected = (try forExt(std.Io.Dir.path.extension(path))) orelse return &.{};
    const start_byte = @min(start_raw, content.len);
    const end_byte = @max(start_byte, @min(end_raw, content.len));
    const source = content[start_byte..end_byte];
    const styles = try gpa.alloc(u8, source.len);
    @memset(styles, 0);
    paint(styles, source, selected);
    return styles;
}

/// Whether `highlightApart` can colour `path` on a worker: a grammar with
/// no injections (markdown's and typst's reach the shared parsers), made
/// ready here, on the loop, so the worker only reads its query.
pub fn readyApart(path: []const u8) bool {
    const selected = (forExt(std.Io.Dir.path.extension(path)) catch return false) orelse return false;
    return !std.mem.eql(u8, selected.name, "markdown") and !std.mem.eql(u8, selected.name, "typst");
}

/// `highlightFileRange` of `source` (a copy of the range), on a worker: a
/// parse and a query cursor of its own, the grammar's query shared (it
/// is only read); `halt` ends the parse early. After `readyApart`.
pub fn highlightApart(gpa: std.mem.Allocator, path: []const u8, source: []const u8, halt: *const std.atomic.Value(bool)) ![]u8 {
    const shared = (try forExt(std.Io.Dir.path.extension(path))) orelse return &.{};
    const tree = try parseApart(shared.lang, source, halt);
    defer tree.destroy();
    if (halt.load(.monotonic)) return error.Canceled;
    const cursor = ts.QueryCursor.create();
    defer cursor.destroy();
    const styles = try gpa.alloc(u8, source.len);
    @memset(styles, 0);
    var own = shared;
    own.cursor = cursor;
    runQuery(styles, own, tree, 0);
    return styles;
}

/// `text` parsed with a parser of its own, so a worker thread may ask: the
/// loop's parsers (`ensure`'s, one a language) are not touched, and a
/// language is safe to share. `halt`, set from another thread, ends the
/// parse early (error.Canceled).
fn parseApart(lang: *const ts.Language, text: []const u8, halt: *const std.atomic.Value(bool)) !*ts.Tree {
    const parser = ts.Parser.create();
    defer parser.destroy();
    try parser.setLanguage(lang);
    const Reader = struct {
        text: []const u8,
        fn read(payload: ?*anyopaque, byte: u32, _: ts.Point, n: *u32) callconv(.c) [*c]const u8 {
            const r: *@This() = @ptrCast(@alignCast(payload.?));
            const at = @min(byte, r.text.len);
            n.* = @intCast(r.text.len - at);
            return r.text.ptr + at;
        }
        fn progress(state: *ts.Parser.State) callconv(.c) bool {
            const flag: *const std.atomic.Value(bool) = @ptrCast(@alignCast(state.payload.?));
            return flag.load(.monotonic);
        }
    };
    var reader: Reader = .{ .text = text };
    return parser.parseWithOptions(
        .{ .payload = &reader, .read = Reader.read, .encoding = .utf8 },
        null,
        .{ .payload = @constCast(halt), .progress_callback = @ptrCast(&Reader.progress) },
    ) orelse error.Canceled;
}

/// Source spans are independent of editor rows. Locations output uses the same
/// declarations as sticky editor headers. Byte ends are exclusive; rows are
/// zero-based and inclusive, including the last signature/opening-brace row.
pub const ContextDeclaration = struct {
    start_byte: usize,
    end_byte: usize,
    start_line: usize,
    end_line: usize,
    header_end_byte: usize,
    header_end_line: usize,
};

pub fn supportsPath(path: []const u8) bool {
    return byExt(std.Io.Dir.path.extension(path)) != null;
}

/// A whole file's parse, kept by the file for the keys that walk its nodes
/// (helix's Alt-o and kin) and for a new line's indent. Opaque outside this
/// file; null without a grammar. With `old`, the kept tree told every edit
/// since its parse (`editTree`), the parse reuses what those left alone: a
/// character typed into a 9k-line file costs a few hundred µs, not 50 ms.
pub fn parseTree(path: []const u8, content: []const u8, old: ?*anyopaque) ?*anyopaque {
    const selected = (forExt(std.Io.Dir.path.extension(path)) catch return null) orelse return null;
    const tree = selected.parser.parseString(content, @ptrCast(@alignCast(old))) orelse return null;
    if (held_trees) |h| h.born.append(h.meta, @ptrCast(tree)) catch {};
    return @ptrCast(tree);
}

/// The kept tree told of an edit (ts_tree_edit): `old` the bytes taken out
/// after `before`, the text up to them, `ins` the bytes put in. Its nodes'
/// places follow the edit; what it says of the edited bytes is stale until
/// `parseTree` with it.
pub fn editTree(tree: *anyopaque, before: []const u8, old: []const u8, ins: []const u8) void {
    const from = advance(.{ .row = 0, .column = 0 }, before);
    const t: *ts.Tree = @ptrCast(@alignCast(tree));
    t.edit(.{
        .start_byte = @intCast(before.len),
        .old_end_byte = @intCast(before.len + old.len),
        .new_end_byte = @intCast(before.len + ins.len),
        .start_point = from,
        .old_end_point = advance(from, old),
        .new_end_point = advance(from, ins),
    });
}

/// The point `text` ends at, read from `from` (a column is bytes, as tree-sitter's).
fn advance(from: ts.Point, text: []const u8) ts.Point {
    const nl = std.mem.lastIndexOfScalar(u8, text, '\n') orelse return .{ .row = from.row, .column = from.column + @as(u32, @intCast(text.len)) };
    return .{ .row = from.row + @as(u32, @intCast(std.mem.count(u8, text, "\n"))), .column = @intCast(text.len - nl - 1) };
}

/// While a replica's rollback copy is held (core/rollback.zig) a tree parsed
/// is the speculation's, and one freed is put off: trees live on the C
/// heap, which the core's allocator cannot see. Null otherwise.
pub var held_trees: ?*HeldTrees = null;
pub const HeldTrees = struct {
    meta: std.mem.Allocator,
    born: std.ArrayListUnmanaged(*anyopaque) = .empty,
    freed: std.ArrayListUnmanaged(*anyopaque) = .empty,
};

pub fn freeTree(tree: *anyopaque) void {
    if (held_trees) |h| {
        for (h.born.items, 0..) |t, i| if (t == tree) {
            _ = h.born.swapRemove(i);
            return destroyTree(tree);
        };
        h.freed.append(h.meta, tree) catch destroyTree(tree);
        return;
    }
    destroyTree(tree);
}

pub fn destroyTree(tree: *anyopaque) void {
    const t: *ts.Tree = @ptrCast(@alignCast(tree));
    t.destroy();
}

/// Where a node walk goes from a range (helix object.rs and movement.rs).
pub const NodeWalk = @import("modal.zig").Normal.NodeWalk;
pub const Span = struct { from: usize, to: usize };

/// The spans `walk` takes the byte range [from, to) to, into `out`; `at` is
/// the range's cursor. None when the tree has nothing to say there.
pub fn walkNodes(tree_ptr: *anyopaque, walk: NodeWalk, from: usize, to: usize, at: usize, out: []Span) usize {
    if (out.len == 0) return 0;
    const tree: *const ts.Tree = @ptrCast(@alignCast(tree_ptr));
    const lo: u32 = @intCast(@min(from, std.math.maxInt(u32)));
    const hi: u32 = @intCast(@min(to, std.math.maxInt(u32)));
    if (walk == .parent_node_end or walk == .parent_node_start) {
        var node = tree.rootNode().namedDescendantForByteRange(lo, hi) orelse return 0;
        if (walk == .parent_node_end) {
            out[0] = .{ .from = node.endByte(), .to = node.endByte() };
            return 1;
        }
        // already at the node's lo: its first ancestor that starts earlier
        if (node.startByte() == at) {
            const first = node.startByte();
            while (node.startByte() >= first or !node.isNamed()) node = node.parent() orelse break;
        }
        out[0] = .{ .from = node.startByte(), .to = node.startByte() };
        return 1;
    }
    var cursor = tree.walk();
    defer cursor.destroy();
    // helix TreeCursor.reset_to_byte_range: the smallest node holding the range
    while (true) {
        const node = cursor.node();
        if (lo < node.startByte() or hi > node.endByte()) {
            _ = cursor.gotoParent();
            break;
        }
        if (cursor.gotoFirstChildForByte(lo) == null) break;
    }
    switch (walk) {
        .expand_node => while (cursor.node().startByte() == lo and cursor.node().endByte() == hi) {
            if (!cursor.gotoParent()) break;
        },
        .shrink_node => _ = cursor.gotoFirstChild(),
        .next_sibling => while (!cursor.gotoNextSibling()) {
            if (!cursor.gotoParent()) break;
        },
        .prev_sibling => while (!cursor.gotoPreviousSibling()) {
            if (!cursor.gotoParent()) break;
        },
        .all_siblings, .all_children => {
            if (walk == .all_siblings) {
                while (true) {
                    if (!cursor.gotoParent()) return 0;
                    if (cursor.node().childCount() > 1) break;
                }
            }
            // the named children, or nothing to say
            var n: usize = 0;
            if (!cursor.gotoFirstChild()) return 0;
            while (true) {
                const child = cursor.node();
                if (child.isNamed() and n < out.len) {
                    out[n] = .{ .from = child.startByte(), .to = child.endByte() };
                    n += 1;
                }
                if (!cursor.gotoNextSibling()) break;
            }
            return n;
        },
        .parent_node_end, .parent_node_start => unreachable,
    }
    const node = cursor.node();
    out[0] = .{ .from = node.startByte(), .to = node.endByte() };
    return 1;
}

/// helix's textobjects, which its `]f`, `mif` and kin select: the name a
/// query's captures begin with (`function.around`, `test.inside`).
pub const Object = @import("modal.zig").Normal.Object;

fn objectName(o: Object) []const u8 {
    return if (o == .xml_element) "xml-element" else @tagName(o);
}

/// The grammar's textobject query for `path`, compiled the first time; null
/// when the grammar has none.
fn objectQuery(path: []const u8) ?*ts.Query {
    const spec = specFor(path) orelse return null;
    return lazyQuery(spec, &spec.objects);
}

/// The grammar's indent query for `path` (core/indent.zig) and the
/// grammar's name; null when it has none.
pub fn indentQuery(path: []const u8) ?struct { *ts.Query, []const u8 } {
    const spec = specFor(path) orelse return null;
    return .{ lazyQuery(spec, &spec.indents) orelse return null, spec.name };
}

fn specFor(path: []const u8) ?*Spec {
    return byExt(std.Io.Dir.path.extension(path));
}

fn lazyQuery(spec: *Spec, lazy: *Lazy) ?*ts.Query {
    if (lazy.query) |q| return q;
    if (lazy.src.len == 0 or lazy.failed) return null;
    var error_offset: u32 = 0;
    lazy.query = ts.Query.create(langOf(spec), lazy.src, &error_offset) catch {
        lazy.failed = true;
        return null;
    };
    return lazy.query;
}

fn captureId(q: *const ts.Query, name: []const u8) ?u32 {
    for (0..q.captureCount()) |i| if (std.mem.eql(u8, q.captureNameForId(@intCast(i)) orelse "", name)) return @intCast(i);
    return null;
}

/// A match's `capture`, as one span over all its nodes (helix's grouped
/// capture), when the match's `#eq?` and `#match?` hold.
fn matchSpan(q: *const ts.Query, match: anytype, capture: u32, text: []const u8) ?Span {
    var span: ?Span = null;
    for (match.captures) |c| if (c.index == capture) {
        const s: Span = .{ .from = c.node.startByte(), .to = c.node.endByte() };
        span = if (span) |old| .{ .from = @min(old.from, s.from), .to = @max(old.to, s.to) } else s;
    };
    var found = span orelse return null;
    // a node that takes its line's newline (this zig grammar's comments)
    // is the line without it, as helix's grammars have it
    if (found.to > found.from + 1 and found.to <= text.len and text[found.to - 1] == '\n') found.to -= 1;
    const steps = q.predicatesForPattern(match.pattern_index);
    var i: usize = 0;
    while (i < steps.len) {
        var end = i;
        while (end < steps.len and steps[end].type != .done) end += 1;
        const pred = steps[i..end];
        i = end + 1;
        if (pred.len != 3 or pred[0].type != .string or pred[1].type != .capture) continue;
        const op = q.stringValueForId(pred[0].value_id) orelse continue;
        const subject = for (match.captures) |c| {
            if (c.index == pred[1].value_id) break text[@min(c.node.startByte(), text.len)..@min(c.node.endByte(), text.len)];
        } else continue;
        const want = if (pred[2].type == .string) q.stringValueForId(pred[2].value_id) orelse continue else for (match.captures) |c| {
            if (c.index == pred[2].value_id) break text[@min(c.node.startByte(), text.len)..@min(c.node.endByte(), text.len)];
        } else continue;
        switch (std.meta.stringToEnum(enum { @"eq?", @"match?" }, op) orelse continue) {
            .@"eq?" => if (!std.mem.eql(u8, subject, want)) return null,
            .@"match?" => {
                var re = regexp.Regex.compile(want) catch continue;
                if ((re.find(subject, 0, subject.len, subject.len) catch null) == null) return null;
            },
        }
    }
    return found;
}

/// `mi`/`ma`: the smallest `object.inside` (or `.around`) holding byte `at`
/// (helix textobject_treesitter). None without a query or such an object.
pub fn objectAt(path: []const u8, tree_ptr: *anyopaque, text: []const u8, object: Object, around: bool, at: usize) ?Span {
    const q = objectQuery(path) orelse return null;
    var buf: [32]u8 = undefined;
    const want = std.fmt.bufPrint(&buf, "{s}.{s}", .{ objectName(object), if (around) "around" else "inside" }) catch return null;
    const capture = captureId(q, want) orelse return null;
    const tree: *const ts.Tree = @ptrCast(@alignCast(tree_ptr));
    const cursor = ts.QueryCursor.create();
    defer cursor.destroy();
    cursor.exec(q, tree.rootNode());
    var best: ?Span = null;
    while (cursor.nextMatch()) |match| {
        const s = matchSpan(q, match, capture, text) orelse continue;
        if (!(s.from <= at and at < s.to)) continue;
        if (best == null or s.to - s.from < best.?.to - best.?.from) best = s;
    }
    const s = best orelse return null;
    if (s.from >= text.len or s.to >= text.len) return null;
    return s;
}

/// `]f`/`[f` and kin: the next object starting after byte `at`, or the
/// previous one ending before it (helix goto_treesitter_object), from the
/// first of `.movement`, `.around`, `.inside` the query names.
pub fn objectNext(path: []const u8, tree_ptr: *anyopaque, text: []const u8, objects: []const Object, forward: bool, at: usize, within: ?[2]usize, out: []?Span) void {
    @memset(out, null);
    const q = objectQuery(path) orelse return;
    // Each object's capture; one pass of the query finds them all (`]`'s
    // three painted targets, body_layer.treeTargets).
    var captures: [8]?u32 = @splat(null);
    for (objects, captures[0..objects.len]) |object, *capture| {
        var buf: [32]u8 = undefined;
        capture.* = for ([_][]const u8{ "movement", "around", "inside" }) |kind| {
            const want = std.fmt.bufPrint(&buf, "{s}.{s}", .{ objectName(object), kind }) catch break null;
            if (captureId(q, want)) |id| break id;
        } else null;
    }
    const tree: *const ts.Tree = @ptrCast(@alignCast(tree_ptr));
    const cursor = ts.QueryCursor.create();
    defer cursor.destroy();
    // Only the objects these bytes hold (a body's rows shown): its painted
    // targets (body_layer.paintTargets).
    if (within) |w| cursor.setByteRange(@intCast(w[0]), @intCast(w[1])) catch return;
    cursor.exec(q, tree.rootNode());
    while (cursor.nextMatch()) |match| for (captures[0..objects.len], out) |capture, *best| {
        const s = matchSpan(q, match, capture orelse continue, text) orelse continue;
        if (forward) {
            if (s.from <= at) continue;
            if (best.* == null or s.from < best.*.?.from or (s.from == best.*.?.from and s.to > best.*.?.to)) best.* = s;
        } else {
            if (s.to >= at) continue;
            if (best.* == null or s.to > best.*.?.to or (s.to == best.*.?.to and s.from < best.*.?.from)) best.* = s;
        }
    };
    for (out) |*best| if (best.*) |s| if (s.from >= text.len or s.to >= text.len) {
        best.* = null;
    };
}

/// Owned source analysis. Both slices use the allocator passed to analyzeSource.
/// The parsed tree is released before returning; callers can cache this result.
pub const SourceAnalysis = struct {
    declarations: []ContextDeclaration = &.{},
    colors: []u8 = &.{},

    pub fn deinit(self: *SourceAnalysis, gpa: std.mem.Allocator) void {
        gpa.free(self.declarations);
        gpa.free(self.colors);
        self.* = .{};
    }
};

pub fn analyzeSource(gpa: std.mem.Allocator, path: []const u8, content: []const u8, want_declarations: bool, want_colors: bool) !SourceAnalysis {
    if (content.len == 0 or (!want_declarations and !want_colors)) return .{};
    const selected = (try forExt(std.Io.Dir.path.extension(path))) orelse return .{};
    const tree = selected.parser.parseString(content, null) orelse return .{};
    defer tree.destroy();
    var result: SourceAnalysis = .{};
    errdefer result.deinit(gpa);
    if (want_declarations) result.declarations = (try contextFromTree(gpa, content, tree, null, &.{})).declarations;
    if (want_colors) {
        result.colors = try gpa.alloc(u8, content.len);
        @memset(result.colors, 0);
        paintTree(result.colors, content, selected, tree);
    }
    return result;
}

pub fn contextDeclarations(gpa: std.mem.Allocator, path: []const u8, content: []const u8) ![]ContextDeclaration {
    const analysis = try analyzeSource(gpa, path, content, true, false);
    return analysis.declarations;
}

/// A text's context, from one parse: its declarations (the sticky
/// headers', Locations') and its symbols (the Symbols picker's, UX DESIGN
/// N), both of the same allocator.
pub const Context = struct {
    declarations: []ContextDeclaration = &.{},
    symbols: []Symbol = &.{},

    pub fn deinit(c: *Context, gpa: std.mem.Allocator) void {
        gpa.free(c.declarations);
        gpa.free(c.symbols);
        c.* = .{};
    }
};

/// `content`'s context (its path's language), parsed here: a sticky
/// header's (File.refreshContext), a loaded text's.
pub fn context(gpa: std.mem.Allocator, path: []const u8, content: []const u8) !Context {
    if (content.len == 0) return .{};
    const spec = byExt(std.Io.Dir.path.extension(path)) orelse return .{};
    const selected = try ensure(spec);
    const tree = selected.parser.parseString(content, null) orelse return .{};
    defer tree.destroy();
    return contextFromTree(gpa, content, tree, null, rulesOf(spec.name));
}

/// `content`'s context, on a worker (`parseApart`). `halt` ends the parse
/// and the walk early (error.Canceled): a 1.2 MB file is seconds in a
/// Debug build.
pub fn contextApart(gpa: std.mem.Allocator, path: []const u8, content: []const u8, halt: *const std.atomic.Value(bool)) !Context {
    if (content.len == 0) return .{};
    const ext = std.Io.Dir.path.extension(path);
    const spec = specs: for (&specs) |*spec| {
        for (spec.exts) |choice| if (std.ascii.eqlIgnoreCase(ext, choice)) break :specs spec;
    } else return .{};
    const tree = try parseApart(langOf(spec), content, halt);
    defer tree.destroy();
    return contextFromTree(gpa, content, tree, halt, rulesOf(spec.name));
}

/// The declarations and, by `rules` (none: no symbols), the symbols of a
/// parse, in one walk of its nodes.
fn contextFromTree(gpa: std.mem.Allocator, content: []const u8, tree: *ts.Tree, halt: ?*const std.atomic.Value(bool), rules: []const Rule) !Context {
    var result: std.ArrayList(ContextDeclaration) = .empty;
    errdefer result.deinit(gpa);
    var symbols: SymbolWalk = .{ .gpa = gpa, .rules = rules, .source = content };
    errdefer symbols.out.deinit(gpa);
    // The cursor retains its ancestor stack: sibling visits do not repeatedly
    // reconstruct parents in broad syntax trees. Preorder preserves source order.
    var cursor = tree.rootNode().walk();
    defer cursor.destroy();
    var visited: usize = 0;
    while (true) {
        visited += 1;
        if (halt) |flag| if (visited % 4096 == 0 and flag.load(.monotonic)) return error.Canceled;
        const node = cursor.node();
        if (node.isNamed()) {
            if (contextSpan(node, content)) |span| {
                if (result.items.len == 0 or result.items[result.items.len - 1].start_line != span.start_line or
                    result.items[result.items.len - 1].end_line != span.end_line)
                    try result.append(gpa, span);
            }
            if (rules.len > 0) try symbols.visit(node);
        }
        if (cursor.gotoFirstChild()) continue;
        while (!cursor.gotoNextSibling()) {
            if (!cursor.gotoParent()) {
                const declarations = try result.toOwnedSlice(gpa);
                errdefer gpa.free(declarations);
                return .{ .declarations = declarations, .symbols = try symbols.out.toOwnedSlice(gpa) };
            }
        }
    }
}

fn contextSpan(node: ts.Node, source: []const u8) ?ContextDeclaration {
    const kind = node.kind();
    var body: ?ts.Node = null;
    var accepted = false;
    if (std.mem.eql(u8, kind, "Decl")) {
        // Zig's FnProto excludes its body: the surrounding Decl owns both.
        accepted = childOfKind(node, "FnProto") != null;
        body = childOfKind(node, "Block");
        if (body == null) return null;
    } else if (std.mem.eql(u8, kind, "ContainerDecl") or std.mem.eql(u8, kind, "TestDecl")) {
        accepted = true;
        body = childOfKind(node, "Block");
    } else {
        const kinds = [_][]const u8{
            "function_definition",   "function_declaration", "function_item",         "function",                "method_definition",
            "method_declaration",    "method",               "singleton_method",      "constructor_declaration", "destructor_definition",
            "class_definition",      "class_declaration",    "class_specifier",       "class",                   "singleton_class",
            "object_declaration",    "struct_item",          "struct_specifier",      "struct_declaration",      "union_specifier",
            "union_item",            "union_declaration",    "enum_item",             "enum_specifier",          "enum_declaration",
            "interface_declaration", "trait_item",           "trait_definition",      "impl_item",               "mod_item",
            "module_definition",     "module_declaration",   "module",                "namespace_definition",    "namespace_declaration",
            "record_declaration",    "type_declaration",     "extension_declaration", "protocol_declaration",
        };
        for (kinds) |candidate| if (std.mem.eql(u8, kind, candidate)) {
            accepted = true;
            break;
        };
        body = node.childByFieldName("body");
    }
    if (!accepted) return null;
    var owner = node;
    if (std.mem.eql(u8, kind, "ContainerDecl")) {
        // A multiline `const Name = struct` starts at the binding, not at the
        // struct token. Stop at real scopes so returned anonymous containers
        // do not inherit an enclosing function's signature.
        var ancestor = node.parent();
        while (ancestor) |parent| {
            const parent_kind = parent.kind();
            if (std.mem.eql(u8, parent_kind, "VarDecl")) {
                owner = parent;
                break;
            }
            if (std.mem.eql(u8, parent_kind, "Block") or std.mem.eql(u8, parent_kind, "Decl") or
                std.mem.eql(u8, parent_kind, "ContainerDecl") or std.mem.eql(u8, parent_kind, "FnProto") or
                std.mem.eql(u8, parent_kind, "ContainerField") or std.mem.eql(u8, parent_kind, "ParamDecl")) break;
            ancestor = parent.parent();
        }
    }
    const beginning = owner.startPoint();
    const end = node.endPoint();
    if (beginning.row >= end.row) return null;
    var header_end: usize = node.startByte();
    if (body) |block| {
        header_end = block.startByte();
        // Indentation grammars start their body at its first statement.
        if (header_end < source.len and source[header_end] == '{') {
            header_end += 1;
        } else {
            while (header_end > node.startByte() and std.ascii.isWhitespace(source[header_end - 1])) header_end -= 1;
        }
    } else {
        // Containers often expose their braces directly, without a body node.
        var i: u32 = 0;
        while (i < node.childCount()) : (i += 1) {
            const child = node.child(i) orelse continue;
            if (std.mem.eql(u8, child.kind(), "{")) {
                header_end = child.endByte();
                break;
            }
        }
        // Ruby and similar grammars have a body_statement without a field.
        if (header_end == node.startByte()) {
            header_end = std.mem.indexOfScalarPos(u8, source, header_end, '\n') orelse source.len;
        }
    }
    const line_start = @as(usize, owner.startByte()) - beginning.column;
    const header_line = beginning.row + std.mem.count(u8, source[line_start..@min(header_end, source.len)], "\n");
    const header_line_end = std.mem.indexOfScalarPos(u8, source, @min(header_end, source.len), '\n') orelse source.len;
    return .{
        .start_byte = line_start,
        .end_byte = node.endByte(),
        .start_line = beginning.row,
        .end_line = end.row - @as(usize, if (end.column == 0) 1 else 0),
        .header_end_byte = header_line_end,
        .header_end_line = header_line,
    };
}

// ---- symbols: the Symbols picker's (UX DESIGN N) ----

/// What a symbol is, in the Symbols picker's order (UX DESIGN N2): types,
/// functions, fields, then the rest (consts, vars, modules, other) as one
/// group. A `scope` is listed nowhere: it names its members (Rust's
/// `impl S`: `S.new`).
pub const SymbolKind = enum(u8) {
    type,
    function,
    field,
    constant,
    variable,
    module,
    other,
    scope,

    /// Its mark in a row (UX DESIGN N4): one letter, `·` for the other.
    pub fn mark(k: SymbolKind) []const u8 {
        return switch (k) {
            .type => "t",
            .function => "f",
            .field => "m",
            .constant => "c",
            .variable => "v",
            .module => "n",
            .other, .scope => "·",
        };
    }

    /// Its group in the picker: 0 types, 1 functions, 2 fields, 3 the rest.
    pub fn group(k: SymbolKind) u8 {
        return @min(@intFromEnum(k), 3);
    }
};

/// A declaration the Symbols picker lists: its kind, the line and bytes of
/// its name, and the symbol it is declared in.
pub const Symbol = struct {
    kind: SymbolKind,
    /// The line its name is on, from 0.
    line: u32,
    name_start: u32,
    name_end: u32,
    /// Where what its row says after its name ends (a function's
    /// signature): its body's start, else its own end. Its row cuts it at
    /// its name's line's end.
    end: u32,
    /// The symbol it is declared in, by its index + 1 (0: none): its name
    /// qualifies this one's (`Counts.lines`).
    parent: u32 = 0,
};

/// How a node of a grammar is a symbol (UX DESIGN N2: one table a language).
const Rule = struct {
    node: []const u8,
    kind: SymbolKind,
    how: How = .plain,
    /// The field naming it; without it, its declarator's name (C's) or the
    /// first name under it (`nameOf`). "": none (an anonymous scope).
    name: []const u8 = "name",
    /// A form's first words and the kinds they declare (`.head`).
    heads: []const struct { []const u8, SymbolKind } = &.{},
    /// Not one under a node of this kind (Pascal's declProc heading the
    /// defProc that is the symbol).
    unless_in: []const u8 = "",
};

const How = enum {
    /// Its kind as given.
    plain,
    /// Only with a body (C's `struct s { ... }`; `struct s x;` names the
    /// type, declares none); unnamed, a scope (an anonymous struct's fields
    /// are its owner's).
    body,
    /// C's declaration: a function where a declarator on the way to its
    /// name is one's; else a const where `const` says so (its kind a var).
    declarator,
    /// A binding whose value tells: a type, a function, a module (Zig's
    /// `const S = struct`, `@import`, JavaScript's arrow function); else a
    /// const or a var by its keyword.
    value,
    /// A binding that is a field in a type (a Python class's attribute,
    /// Kotlin's property); else a const or a var by its keyword. Named
    /// by a name, never a pattern (`self.x = ...`).
    binding,
    /// A form whose first word says what it declares (Elixir's `def f`,
    /// Clojure's `(defn f ...)`), named by its second.
    head,
    /// No row: a scope its members are named in, by its own name (Rust's
    /// `impl S`) or its owner's (an anonymous struct).
    scope,
};

const c_rules = [_]Rule{
    .{ .node = "function_definition", .kind = .function },
    .{ .node = "declaration", .kind = .variable, .how = .declarator },
    .{ .node = "field_declaration", .kind = .field, .how = .declarator },
    .{ .node = "struct_specifier", .kind = .type, .how = .body },
    .{ .node = "union_specifier", .kind = .type, .how = .body },
    .{ .node = "enum_specifier", .kind = .type, .how = .body },
    .{ .node = "enumerator", .kind = .field },
    .{ .node = "type_definition", .kind = .type },
    .{ .node = "preproc_def", .kind = .other },
    .{ .node = "preproc_function_def", .kind = .other },
};

/// The kind tables, by grammar (grammar_manifest.zig): a grammar with none
/// (JSON, CSS, HTML, Markdown, Typst) lists no symbols.
const symbol_rules = [_]struct { []const u8, []const Rule }{
    .{ "zig", &.{
        // Named by its FnProto's `function` (symbolOf).
        .{ .node = "Decl", .kind = .function, .name = "" },
        .{ .node = "VarDecl", .kind = .variable, .how = .value, .name = "variable_type_function" },
        .{ .node = "ContainerField", .kind = .field },
        .{ .node = "TestDecl", .kind = .other, .name = "" },
        .{ .node = "ContainerDecl", .kind = .type, .how = .scope, .name = "" },
    } },
    .{ "c", &c_rules },
    .{ "cpp", &(c_rules ++ [_]Rule{
        .{ .node = "class_specifier", .kind = .type, .how = .body },
        .{ .node = "namespace_definition", .kind = .module },
        .{ .node = "alias_declaration", .kind = .type },
    }) },
    .{ "rust", &.{
        .{ .node = "function_item", .kind = .function },
        .{ .node = "function_signature_item", .kind = .function },
        .{ .node = "struct_item", .kind = .type },
        .{ .node = "enum_item", .kind = .type },
        .{ .node = "union_item", .kind = .type },
        .{ .node = "trait_item", .kind = .type },
        .{ .node = "type_item", .kind = .type },
        .{ .node = "impl_item", .kind = .type, .how = .scope, .name = "type" },
        .{ .node = "field_declaration", .kind = .field },
        .{ .node = "enum_variant", .kind = .field },
        .{ .node = "const_item", .kind = .constant },
        .{ .node = "static_item", .kind = .variable },
        .{ .node = "mod_item", .kind = .module },
        .{ .node = "macro_definition", .kind = .other },
    } },
    .{ "go", &.{
        .{ .node = "function_declaration", .kind = .function },
        .{ .node = "method_declaration", .kind = .function },
        .{ .node = "method_elem", .kind = .function },
        .{ .node = "type_spec", .kind = .type },
        .{ .node = "type_alias", .kind = .type },
        .{ .node = "field_declaration", .kind = .field },
        .{ .node = "const_spec", .kind = .constant },
        .{ .node = "var_spec", .kind = .variable },
    } },
    .{ "python", &.{
        .{ .node = "class_definition", .kind = .type },
        .{ .node = "function_definition", .kind = .function },
        .{ .node = "assignment", .kind = .variable, .how = .binding, .name = "left" },
    } },
    .{ "javascript", &.{
        .{ .node = "function_declaration", .kind = .function },
        .{ .node = "generator_function_declaration", .kind = .function },
        .{ .node = "class_declaration", .kind = .type },
        .{ .node = "method_definition", .kind = .function },
        .{ .node = "field_definition", .kind = .field, .name = "property" },
        .{ .node = "variable_declarator", .kind = .variable, .how = .value },
    } },
    .{ "java", &.{
        .{ .node = "class_declaration", .kind = .type },
        .{ .node = "interface_declaration", .kind = .type },
        .{ .node = "enum_declaration", .kind = .type },
        .{ .node = "record_declaration", .kind = .type },
        .{ .node = "annotation_type_declaration", .kind = .type },
        .{ .node = "method_declaration", .kind = .function },
        .{ .node = "constructor_declaration", .kind = .function },
        .{ .node = "field_declaration", .kind = .field },
        .{ .node = "enum_constant", .kind = .field },
        .{ .node = "constant_declaration", .kind = .constant },
    } },
    .{ "c_sharp", &.{
        .{ .node = "class_declaration", .kind = .type },
        .{ .node = "struct_declaration", .kind = .type },
        .{ .node = "interface_declaration", .kind = .type },
        .{ .node = "enum_declaration", .kind = .type },
        .{ .node = "record_declaration", .kind = .type },
        .{ .node = "delegate_declaration", .kind = .type },
        .{ .node = "namespace_declaration", .kind = .module },
        .{ .node = "file_scoped_namespace_declaration", .kind = .module },
        .{ .node = "method_declaration", .kind = .function },
        .{ .node = "constructor_declaration", .kind = .function },
        .{ .node = "destructor_declaration", .kind = .function },
        .{ .node = "field_declaration", .kind = .field },
        .{ .node = "property_declaration", .kind = .field },
        .{ .node = "event_field_declaration", .kind = .field },
        .{ .node = "enum_member_declaration", .kind = .field },
    } },
    .{ "kotlin", &.{
        .{ .node = "class_declaration", .kind = .type },
        .{ .node = "object_declaration", .kind = .type },
        .{ .node = "companion_object", .kind = .type, .how = .scope, .name = "" },
        .{ .node = "function_declaration", .kind = .function },
        .{ .node = "property_declaration", .kind = .variable, .how = .binding },
        .{ .node = "type_alias", .kind = .type },
        .{ .node = "enum_entry", .kind = .field },
    } },
    .{ "scala", &.{
        .{ .node = "class_definition", .kind = .type },
        .{ .node = "object_definition", .kind = .type },
        .{ .node = "trait_definition", .kind = .type },
        .{ .node = "enum_definition", .kind = .type },
        .{ .node = "type_definition", .kind = .type },
        .{ .node = "function_definition", .kind = .function },
        .{ .node = "function_declaration", .kind = .function },
        .{ .node = "val_definition", .kind = .constant, .how = .binding, .name = "pattern" },
        .{ .node = "var_definition", .kind = .variable, .how = .binding, .name = "pattern" },
        .{ .node = "simple_enum_case", .kind = .field },
        .{ .node = "full_enum_case", .kind = .field },
    } },
    .{ "ruby", &.{
        .{ .node = "class", .kind = .type },
        .{ .node = "singleton_class", .kind = .type, .how = .scope, .name = "" },
        .{ .node = "module", .kind = .module },
        .{ .node = "method", .kind = .function },
        .{ .node = "singleton_method", .kind = .function },
    } },
    .{ "php", &.{
        .{ .node = "class_declaration", .kind = .type },
        .{ .node = "interface_declaration", .kind = .type },
        .{ .node = "trait_declaration", .kind = .type },
        .{ .node = "enum_declaration", .kind = .type },
        .{ .node = "function_definition", .kind = .function },
        .{ .node = "method_declaration", .kind = .function },
        .{ .node = "property_declaration", .kind = .field },
        .{ .node = "enum_case", .kind = .field },
        .{ .node = "const_declaration", .kind = .constant },
        .{ .node = "namespace_definition", .kind = .module },
    } },
    .{ "bash", &.{
        .{ .node = "function_definition", .kind = .function },
        .{ .node = "variable_assignment", .kind = .variable, .how = .binding },
    } },
    .{ "haskell", &.{
        .{ .node = "data_type", .kind = .type },
        .{ .node = "newtype", .kind = .type },
        .{ .node = "type_synomym", .kind = .type },
        .{ .node = "class", .kind = .type },
        .{ .node = "instance", .kind = .type, .how = .scope },
        .{ .node = "function", .kind = .function },
        .{ .node = "bind", .kind = .constant },
        .{ .node = "data_constructor", .kind = .field },
    } },
    .{ "ocaml", &.{
        .{ .node = "type_binding", .kind = .type },
        .{ .node = "module_binding", .kind = .module },
        .{ .node = "module_type_definition", .kind = .type },
        .{ .node = "class_binding", .kind = .type },
        .{ .node = "method_definition", .kind = .function },
        .{ .node = "let_binding", .kind = .constant, .how = .value, .name = "pattern" },
        .{ .node = "field_declaration", .kind = .field },
        .{ .node = "constructor_declaration", .kind = .field },
    } },
    .{ "erlang", &.{
        .{ .node = "fun_decl", .kind = .function },
        .{ .node = "record_decl", .kind = .type },
        .{ .node = "record_field", .kind = .field },
        .{ .node = "type_alias", .kind = .type },
        .{ .node = "pp_define", .kind = .other },
        .{ .node = "module_attribute", .kind = .module },
    } },
    .{ "elixir", &.{
        .{ .node = "call", .kind = .other, .how = .head, .heads = &.{
            .{ "defmodule", .module },   .{ "defprotocol", .type },  .{ "def", .function },
            .{ "defp", .function },      .{ "defdelegate", .function }, .{ "defguard", .function },
            .{ "defguardp", .function }, .{ "defmacro", .other },    .{ "defmacrop", .other },
        } },
    } },
    .{ "clojure", &.{
        .{ .node = "list_lit", .kind = .other, .how = .head, .heads = &.{
            .{ "ns", .module },        .{ "def", .constant },    .{ "defonce", .constant },  .{ "defn", .function },
            .{ "defn-", .function },   .{ "defmulti", .function }, .{ "defmethod", .function }, .{ "defmacro", .other },
            .{ "defrecord", .type },   .{ "deftype", .type },    .{ "defprotocol", .type },  .{ "definterface", .type },
            .{ "defstruct", .type },
        } },
    } },
    .{ "fortran", &.{
        .{ .node = "module", .kind = .module },
        .{ .node = "program", .kind = .module },
        .{ .node = "subroutine", .kind = .function },
        .{ .node = "function", .kind = .function },
        .{ .node = "derived_type_definition", .kind = .type },
        .{ .node = "variable_declaration", .kind = .variable, .how = .binding },
    } },
    .{ "ada", &.{
        .{ .node = "package_declaration", .kind = .module },
        .{ .node = "package_body", .kind = .module },
        .{ .node = "full_type_declaration", .kind = .type },
        .{ .node = "subprogram_declaration", .kind = .function },
        .{ .node = "subprogram_body", .kind = .function },
        .{ .node = "object_declaration", .kind = .variable, .how = .binding },
        .{ .node = "component_declaration", .kind = .field },
    } },
    .{ "pascal", &.{
        .{ .node = "declType", .kind = .type },
        .{ .node = "declProc", .kind = .function, .unless_in = "defProc" },
        .{ .node = "defProc", .kind = .function },
        .{ .node = "declConst", .kind = .constant },
        .{ .node = "declVar", .kind = .variable, .how = .binding },
        .{ .node = "declField", .kind = .field },
    } },
    .{ "powershell", &.{
        .{ .node = "function_statement", .kind = .function },
        .{ .node = "class_statement", .kind = .type },
        .{ .node = "class_method_definition", .kind = .function },
        .{ .node = "class_property_definition", .kind = .field },
        .{ .node = "enum_statement", .kind = .type },
        .{ .node = "enum_member", .kind = .field },
    } },
};

fn rulesOf(grammar: []const u8) []const Rule {
    for (symbol_rules) |entry| if (std.mem.eql(u8, entry[0], grammar)) return entry[1];
    return &.{};
}

/// A walk's symbols, node by node in preorder (`contextFromTree`).
const SymbolWalk = struct {
    gpa: std.mem.Allocator,
    rules: []const Rule,
    source: []const u8,
    out: std.ArrayList(Symbol) = .empty,
    /// The scopes the node is in, the innermost last.
    scopes: [max_scopes]Scope = undefined,
    depth: u8 = 0,

    /// Where a scope ends, its kind, and the symbol its members are named
    /// in (an index + 1, 0 none).
    const Scope = struct { end: u32, kind: SymbolKind, symbol: u32 };
    /// Deeper scopes are their parent's.
    const max_scopes = 32;

    fn visit(w: *SymbolWalk, node: ts.Node) !void {
        while (w.depth > 0 and w.scopes[w.depth - 1].end <= node.startByte()) w.depth -= 1;
        const in: Scope = if (w.depth > 0) w.scopes[w.depth - 1] else .{ .end = 0, .kind = .module, .symbol = 0 };
        // A test's body (a macro's) lists nothing: its types are its
        // locals' (a test's `const Find = struct`).
        if (in.kind == .other) return;
        const kind_name = node.kind();
        const rule = for (w.rules) |r| {
            if (std.mem.eql(u8, r.node, kind_name)) break r;
        } else return;
        const found = symbolOf(rule, node, w.source, in.kind) orelse return;
        // A body's consts and vars are its locals, none of them listed.
        const local = in.kind != .type and in.kind != .module and in.kind != .scope;
        if (local and (found.kind == .constant or found.kind == .variable)) return;
        var named = in.symbol;
        if (found.name) |name| {
            // A longer name is cut (a test's sentence), on a character.
            var end = name.endByte();
            if (end - name.startByte() > max_name) {
                end = name.startByte() + max_name;
                while (end > name.startByte() and w.source[end] & 0xc0 == 0x80) end -= 1;
            }
            try w.out.append(w.gpa, .{
                .kind = found.kind,
                .line = name.startPoint().row,
                .name_start = name.startByte(),
                .name_end = end,
                .end = found.end,
                .parent = in.symbol,
            });
            // A const's or a field's members are not named in it.
            if (found.kind == .type or found.kind == .function or found.kind == .module or found.kind == .scope) named = @intCast(w.out.items.len);
        }
        if (w.depth == max_scopes) return;
        w.scopes[w.depth] = .{ .end = node.endByte(), .kind = if (found.kind == .scope) rule.kind else found.kind, .symbol = named };
        w.depth += 1;
    }
};

/// What node `node` declares by `rule`, in a scope of kind `in`: its kind,
/// its name (null: an anonymous scope) and where its row's words end.
fn symbolOf(rule: Rule, node: ts.Node, source: []const u8, in: SymbolKind) ?struct { kind: SymbolKind, name: ?ts.Node, end: u32 } {
    if (rule.unless_in.len > 0) if (node.parent()) |up| if (std.mem.eql(u8, up.kind(), rule.unless_in)) return null;
    var kind = rule.kind;
    var name: ?ts.Node = null;
    var end = if (node.childByFieldName("body")) |body| body.startByte() else node.endByte();
    switch (rule.how) {
        .plain => name = nameOf(node, rule.name),
        .scope => {
            name = nameOf(node, rule.name);
            kind = .scope;
        },
        .body => {
            if (node.childByFieldName("body") == null) return null;
            name = nameOf(node, rule.name);
            if (name == null) kind = .scope;
        },
        .declarator => {
            var d = node;
            while (d.childByFieldName("declarator")) |next| {
                if (std.mem.eql(u8, next.kind(), "function_declarator")) kind = .function;
                d = next;
            }
            name = nameOf(node, rule.name);
            if (kind == .variable and constant(source, node.startByte(), name orelse return null)) kind = .constant;
        },
        .value => {
            // Named by a name, never a pattern (`const { a, b } = ...`,
            // OCaml's `let () = ...`).
            name = nameOf(node, rule.name);
            if (name) |n| if (!nameLike(n.kind())) return null;
            kind = valueKind(node, source) orelse kind;
            // JavaScript's keyword is its declaration's (`const a = 1, b`).
            const from = if (std.mem.eql(u8, rule.node, "variable_declarator")) (node.parent() orelse node).startByte() else node.startByte();
            if (kind == .variable and constant(source, from, name orelse return null)) kind = .constant;
        },
        .binding => {
            const n = node.childByFieldName(rule.name) orelse nameOf(node, rule.name) orelse return null;
            if (!nameLike(n.kind())) return null;
            name = n;
            if (in == .type) kind = .field else if (kind == .variable and constant(source, node.startByte(), n)) kind = .constant;
        },
        .head => {
            const elixir = std.mem.eql(u8, rule.node, "call");
            const first = (if (elixir) node.childByFieldName("target") else node.namedChild(0)) orelse return null;
            const word = source[first.startByte()..first.endByte()];
            kind = for (rule.heads) |h| {
                if (std.mem.eql(u8, h[0], word)) break h[1];
            } else return null;
            var second = (if (elixir) childOfKind(node, "arguments") else node.namedChild(1)) orelse return null;
            if (elixir) second = second.namedChild(0) orelse return null;
            if (second.childByFieldName("target")) |target| second = target;
            name = if (nameLike(second.kind())) second else nameOf(second, "name");
        },
    }
    // Zig's: a function's name is its prototype's, its body a Block; a
    // test's its string.
    if (std.mem.eql(u8, rule.node, "Decl")) {
        const proto = childOfKind(node, "FnProto") orelse return null;
        name = proto.childByFieldName("function");
        if (childOfKind(node, "Block")) |block| end = block.startByte();
    } else if (std.mem.eql(u8, rule.node, "TestDecl")) {
        const first = node.namedChild(0) orelse return null;
        if (std.mem.eql(u8, first.kind(), "Block")) return null;
        name = first;
        if (childOfKind(node, "Block")) |block| end = block.startByte();
    }
    if (name == null and kind != .scope) return null;
    if (name) |n| if (n.endByte() <= n.startByte()) return null;
    return .{ .kind = kind, .name = name, .end = end };
}

/// The longest name a symbol has: a longer one is cut.
const max_name = 200;

/// The node naming `node`: its field `field`, whole on its line (C++'s
/// `namespace v8::internal`, Rust's `impl Vec<T>`); without one, its
/// declarator's (C's `int *f(void)`: `f`); else the first name under it,
/// past its type, value, body and parameters (Kotlin's, Fortran's).
fn nameOf(node: ts.Node, field: []const u8) ?ts.Node {
    if (field.len == 0) return null;
    var n = node;
    if (node.childByFieldName(field)) |f| {
        if (f.startPoint().row == f.endPoint().row) return f;
        n = f;
    } else while (n.childByFieldName("declarator")) |d| n = d;
    if (nameLike(n.kind())) return n;
    if (n.childByFieldName("name")) |f| if (nameLike(f.kind())) return f;
    return firstName(n, 3);
}

fn firstName(node: ts.Node, depth: u8) ?ts.Node {
    if (depth == 0) return null;
    const skipped = [_][]const u8{ "type", "value", "body", "parameters", "return_type", "returns", "result", "superclass", "arguments", "default", "trait" };
    var i: u32 = 0;
    while (i < node.childCount()) : (i += 1) {
        const child = node.child(i) orelse continue;
        if (!child.isNamed()) continue;
        const field = node.fieldNameForChild(i) orelse "";
        if (for (skipped) |s| {
            if (std.mem.eql(u8, s, field)) break true;
        } else false) continue;
        const kind = child.kind();
        if (std.mem.indexOf(u8, kind, "modifier") != null or std.mem.indexOf(u8, kind, "annotation") != null or
            std.mem.indexOf(u8, kind, "parameter") != null or std.mem.indexOf(u8, kind, "attribute") != null or
            std.mem.indexOf(u8, kind, "decorator") != null or std.mem.indexOf(u8, kind, "comment") != null or
            std.mem.indexOf(u8, kind, "literal") != null) continue;
        if (nameLike(kind)) return child;
        if (firstName(child, depth - 1)) |found| return found;
    }
    return null;
}

/// A node kind that is a name: an identifier, a `*_name`, a word.
fn nameLike(kind: []const u8) bool {
    if (std.ascii.endsWithIgnoreCase(kind, "identifier") or std.mem.endsWith(u8, kind, "name")) return true;
    for ([_][]const u8{ "word", "constant", "atom", "variable", "constructor", "type_constructor", "alias" }) |k| {
        if (std.mem.eql(u8, kind, k)) return true;
    }
    return false;
}

/// What a binding's value makes it, where it says (else null): Zig's
/// `struct {...}`, `error{...}`, `@This()`, `@Type(...)` a type and
/// `@import(...)` a module; JavaScript's function a function and class a
/// type; OCaml's `let f x = ...` (a parameter) a function.
fn valueKind(node: ts.Node, source: []const u8) ?SymbolKind {
    if (node.childByFieldName("value")) |value| {
        const kind = value.kind();
        for ([_][]const u8{ "arrow_function", "function_expression", "generator_function" }) |k| if (std.mem.eql(u8, kind, k)) return .function;
        if (std.mem.eql(u8, kind, "class")) return .type;
        return null;
    }
    if (childOfKind(node, "parameter") != null) return .function;
    // Zig's value: the last of the VarDecl, under its ErrorUnionExpr.
    var v = node.namedChild(node.namedChildCount() -| 1) orelse return null;
    while (std.mem.eql(u8, v.kind(), "ErrorUnionExpr")) v = v.namedChild(0) orelse return null;
    if (!std.mem.eql(u8, v.kind(), "SuffixExpr")) return null;
    const first = v.namedChild(0) orelse return null;
    const kind = first.kind();
    if (std.mem.eql(u8, kind, "ContainerDecl") or std.mem.eql(u8, kind, "ErrorSetDecl")) return .type;
    if (!std.mem.eql(u8, kind, "BUILTINIDENTIFIER")) return null;
    const builtin = source[first.startByte()..first.endByte()];
    if (std.mem.eql(u8, builtin, "@This") or std.mem.eql(u8, builtin, "@Type")) return .type;
    if ((std.mem.eql(u8, builtin, "@import") or std.mem.eql(u8, builtin, "@cImport")) and v.namedChildCount() == 2) return .module;
    return null;
}

/// Whether a binding is a const: a keyword says so between `from` and its
/// name, or after the name before its value (Ada's `K : constant`).
fn constant(source: []const u8, from: usize, name: ts.Node) bool {
    const after = source[name.endByte()..];
    const before_value = std.mem.indexOfAny(u8, after, "=\n") orelse after.len;
    for ([_][]const u8{ source[@min(from, name.startByte())..name.startByte()], after[0..before_value] }) |text| {
        var words = std.mem.tokenizeAny(u8, text, " \t\r\n,:()*&");
        while (words.next()) |word| for ([_][]const u8{ "const", "constexpr", "val", "final", "readonly", "parameter", "constant" }) |k| {
            if (std.mem.eql(u8, word, k)) return true;
        };
    }
    return false;
}

fn paint(styles: []u8, source: []const u8, selected: Selected) void {
    const tree = selected.parser.parseString(source, null) orelse return;
    defer tree.destroy();
    paintTree(styles, source, selected, tree);
}

fn paintTree(styles: []u8, source: []const u8, selected: Selected, tree: *ts.Tree) void {
    runQuery(styles, selected, tree, 0);
    if (std.mem.eql(u8, selected.name, "markdown")) {
        inject(styles, source, tree.rootNode(), true);
    } else if (std.mem.eql(u8, selected.name, "typst")) {
        inject(styles, source, tree.rootNode(), false);
    }
}

pub fn highlightLocations(gpa: std.mem.Allocator, content: []const u8, start_byte_raw: usize, end_byte_raw: usize) ![]u8 {
    const tz = tracy.zone(@src(), "highlightLocations");
    defer tz.end();
    const start_byte = @min(start_byte_raw, content.len);
    const end_byte = @max(start_byte, @min(end_byte_raw, content.len));
    const source = content[start_byte..end_byte];
    const styles = try gpa.alloc(u8, source.len);
    errdefer gpa.free(styles);
    @memset(styles, 0);
    var memo_ext: []const u8 = "\x00";
    var memo: ?Selected = null;
    var painted = false;

    var offset: usize = 0;
    var lines = std.mem.splitScalar(u8, source, '\n');
    while (lines.next()) |line| {
        defer offset += line.len + 1;
        const code = codeAfterLocation(line) orelse continue;
        const ext = std.Io.Dir.path.extension(code.path);
        if (!std.mem.eql(u8, ext, memo_ext)) {
            memo_ext = ext;
            memo = forExt(ext) catch null;
        }
        const selected = memo orelse continue;
        paint(styles[offset + code.at ..][0..code.text.len], code.text, selected);
        painted = true;
    }
    if (!painted) {
        gpa.free(styles);
        return &.{};
    }
    return styles;
}

/// Formatted results carry the exact source boundary independently of their
/// padded location column. This also colors context whose location is hidden.
/// Consecutive source rows share one parse, retaining multiline syntax.
pub fn highlightLocationRows(gpa: std.mem.Allocator, content: []const u8, rows: []const locations.Row) ![]u8 {
    if (content.len == 0 or rows.len == 0) return &.{};
    const styles = try gpa.alloc(u8, content.len);
    errdefer gpa.free(styles);
    @memset(styles, 0);
    const code = try gpa.alloc(u8, content.len);
    defer gpa.free(code);
    const colors = try gpa.alloc(u8, content.len);
    defer gpa.free(colors);
    const SourceRow = struct { index: usize, start: usize, len: usize };
    const sources = try gpa.alloc(SourceRow, rows.len);
    defer gpa.free(sources);
    var source_count: usize = 0;
    var offset: usize = 0;
    for (rows, 0..) |row, index| {
        if (offset >= content.len) break;
        const end = std.mem.indexOfScalarPos(u8, content, offset, '\n') orelse content.len;
        const source_start = offset + @min(row.code_start, end - offset);
        const address_only = row.location_end > 0 and source_start == end;
        // A row its producer coloured whole is coloured below: no
        // fragment of it to parse.
        const coloured = row.colors.len > 0 and row.colors.len >= end - source_start;
        if (!address_only and !coloured) {
            sources[source_count] = .{ .index = index, .start = source_start, .len = end - source_start };
            source_count += 1;
        }
        offset = @min(end + 1, content.len);
    }
    var painted = false;
    var first: usize = 0;
    while (first < source_count) {
        const first_row = rows[sources[first].index];
        var end = first + 1;
        while (end < source_count) : (end += 1) {
            const row = rows[sources[end].index];
            const previous = rows[sources[end - 1].index];
            if (!std.mem.eql(u8, row.path, first_row.path) or row.at.line != previous.at.line +| 1) break;
        }
        const language = (forExt(std.Io.Dir.path.extension(first_row.path)) catch null);
        if (language) |selected| {
            var code_len: usize = 0;
            for (sources[first..end]) |source| {
                @memcpy(code[code_len..][0..source.len], content[source.start..][0..source.len]);
                code_len += source.len;
                if (code_len < code.len) {
                    code[code_len] = '\n';
                    code_len += 1;
                }
            }
            if (code_len > 0) {
                @memset(colors[0..code_len], 0);
                paint(colors[0..code_len], code[0..code_len], selected);
                painted = true;
                var at: usize = 0;
                for (sources[first..end]) |source| {
                    @memcpy(styles[source.start..][0..source.len], colors[at..][0..source.len]);
                    at += source.len + 1;
                }
            }
        }
        first = end;
    }
    // A shown context range can begin inside a comment/string whose opener was
    // omitted. Formatter snapshots from the complete source take precedence,
    // including zero styles that remove misleading fragment-parser captures.
    offset = 0;
    for (rows) |row| {
        if (offset >= content.len) break;
        const end = std.mem.indexOfScalarPos(u8, content, offset, '\n') orelse content.len;
        const source_start = offset + @min(row.code_start, end - offset);
        const len = @min(row.colors.len, end - source_start);
        if (len > 0) {
            @memcpy(styles[source_start..][0..len], row.colors[0..len]);
            painted = true;
        }
        offset = @min(end + 1, content.len);
    }
    // Declaration context is intentionally muted by the output painter. Keep
    // its source in parsing groups, then remove every syntax/style flag after
    // complete-source snapshots have been applied.
    offset = 0;
    for (rows) |row| {
        if (offset >= content.len) break;
        const end = std.mem.indexOfScalarPos(u8, content, offset, '\n') orelse content.len;
        if (row.declaration) {
            const source_start = offset + @min(row.code_start, end - offset);
            @memset(styles[source_start..end], 0);
        }
        offset = @min(end + 1, content.len);
    }
    if (!painted) {
        gpa.free(styles);
        return &.{};
    }
    return styles;
}

fn codeAfterLocation(line: []const u8) ?struct { path: []const u8, at: usize, text: []const u8 } {
    const trimmed = std.mem.trimStart(u8, line, " \t");
    const target = locations.parseRaw(trimmed);
    if (target.at.line == 0) return null;
    const at = line.len - trimmed.len + target.code_start;
    if (at >= line.len) return null;
    return .{ .path = target.path, .at = at, .text = line[at..] };
}

fn forLang(name: []const u8) !?Selected {
    const canonical = if (grammar_manifest.byName(name)) |i| grammar_manifest.all[i].name else name;
    for (&specs) |*spec| {
        if (std.ascii.eqlIgnoreCase(canonical, spec.name)) return try ensure(spec);
    }
    return null;
}

fn inject(styles: []u8, source: []const u8, node: ts.Node, markdown: bool) void {
    const kind = node.kind();
    if (markdown and std.mem.eql(u8, kind, "inline")) {
        const begin: usize = node.startByte();
        const end: usize = node.endByte();
        if (begin >= end or end > source.len) return;
        const text = source[begin..end];
        // Every colored inline capture requires one of these delimiters.
        if (std.mem.indexOfAny(u8, text, "*_`[<\\\r\n") == null) return;
        const selected = (forLang("markdown_inline") catch return) orelse return;
        const tree = selected.parser.parseString(text, null) orelse return;
        defer tree.destroy();
        runQuery(styles, selected, tree, begin);
        return;
    }
    if (std.mem.eql(u8, kind, if (markdown) "fenced_code_block" else "raw_blck")) {
        const lang = if (markdown) blk: {
            const info = childOfKind(node, "info_string") orelse return;
            break :blk childOfKind(info, "language") orelse return;
        } else node.childByFieldName("lang") orelse return;
        const content = childOfKind(node, if (markdown) "code_fence_content" else "blob") orelse return;
        const selected = (forLang(source[lang.startByte()..lang.endByte()]) catch return) orelse return;
        const begin: usize = content.startByte();
        const end: usize = content.endByte();
        if (begin > end or end > source.len) return;
        const tree = selected.parser.parseString(source[begin..end], null) orelse return;
        defer tree.destroy();
        @memset(styles[begin..end], 0);
        runQuery(styles, selected, tree, begin);
        return;
    }
    var i: u32 = 0;
    const count = node.childCount();
    while (i < count) : (i += 1) {
        if (node.child(i)) |child| inject(styles, source, child, markdown);
    }
}

fn childOfKind(node: ts.Node, kind: []const u8) ?ts.Node {
    var i: u32 = 0;
    const count = node.childCount();
    while (i < count) : (i += 1) {
        if (node.child(i)) |c| {
            if (std.mem.eql(u8, c.kind(), kind)) return c;
        }
    }
    return null;
}

/// A style byte: a Syn in its low bits (syn_bits), and over them the
/// grounds a theme resolves (colors.Chrome's add and del): `ground_add` or `ground_del`,
/// a row added or removed (its hue); `ground_emph`, the stronger ground;
/// `ground_line`, the faint one. A row's first byte says its row's ground:
/// emph the stronger to the pane's edge, line the faint one, neither none
/// (only its marker in the hue). Any later byte's emph is its own cell's
/// ground: the words a changed line changed (hunks.zig).
pub const ground_add: u8 = 0x80;
pub const ground_del: u8 = 0x40;
pub const ground_emph: u8 = 0x20;
pub const ground_line: u8 = 0x10;
pub const syn_bits: u8 = 0x0f;

/// A file section's hunks are parsed together, each side as one text, in
/// pieces: a piece takes whole hunks until it holds `diff_piece_lines`
/// lines, and a hunk longer than `diff_piece_cut` is cut there, counted
/// from the section's first hunk. So a view parses about what a file's
/// view does (its rows and a margin), however many small hunks it shows,
/// and a 20k-line new file is parsed where it is shown, not whole. A string
/// or comment across a cut colours as a fragment would.
const diff_piece_lines = 40;
const diff_piece_cut = 80;

/// Painted hunk pieces, keyed by their bytes and language: scrolling back
/// over a hunk, or a terminal repainting the same output every frame,
/// parses nothing again. Freed by `stop`.
const DiffPiece = struct { hash: u64, styles: []u8, used: u64 };
var diff_pieces: [96]?DiffPiece = @splat(null);
var diff_clock: u64 = 0;

/// The styles of `content[start..end)` read as a unified diff: headers
/// muted, `@@` lines as keywords, and each hunk's code in the language of
/// the file its section names. A hunk's old side (context and removed
/// lines) and new side (context and added lines) are each parsed whole, so
/// a string or comment that spans lines colours as it does in the file.
/// Added and removed lines carry `ground_add`/`ground_del`, the first byte
/// the strong row ground too (`ground_emph`). A file in no
/// language pardes knows keeps the plain colours: added lines as strings,
/// removed ones as numbers.
pub fn highlightDiff(gpa: std.mem.Allocator, content: []const u8, start_raw: usize, end_raw: usize) ![]u8 {
    return highlightDiffRows(gpa, content, start_raw, end_raw, false);
}

/// The same for a terminal's rows, where a row the terminal wrapped
/// continues the diff line above it.
pub fn highlightDiffRows(gpa: std.mem.Allocator, content: []const u8, start_raw: usize, end_raw: usize, continued_rows: bool) ![]u8 {
    return diffStyles(gpa, content, start_raw, end_raw, continued_rows, true);
}

/// `highlightDiff` without the language's ink: each hunk line in one
/// colour as a file in no language pardes knows has it, the grounds, markers
/// and changed words as they are (a patch's pane with `Syntax` off).
pub fn highlightDiffPlain(gpa: std.mem.Allocator, content: []const u8, start_raw: usize, end_raw: usize) ![]u8 {
    return diffStyles(gpa, content, start_raw, end_raw, false, false);
}

fn diffStyles(gpa: std.mem.Allocator, content: []const u8, start_raw: usize, end_raw: usize, continued_rows: bool, language: bool) ![]u8 {
    const tz = tracy.zone(@src(), "highlightDiff");
    defer tz.end();
    const start_byte = @min(start_raw, content.len);
    const end_byte = @max(start_byte, @min(end_raw, content.len));
    const styles = try gpa.alloc(u8, end_byte - start_byte);
    errdefer gpa.free(styles);
    @memset(styles, 0);
    const window: DiffWindow = .{ .styles = styles, .start = start_byte };

    var walk: diff.Walk = .{ .continued_rows = continued_rows };
    // The run of hunk lines not painted yet, with each line's kind.
    var piece_start: ?usize = null;
    var piece_end: usize = 0;
    var piece_path: []const u8 = "";
    var kinds: [diff_piece_cut]diff.Kind = undefined;
    var nkinds: usize = 0;
    var at = diff.anchorBefore(content, start_byte);
    while (true) {
        const nl = std.mem.indexOfScalarPos(u8, content, at, '\n') orelse content.len;
        const got = walk.step(content[at..nl]);
        const body = switch (got.kind) {
            .context, .added, .removed, .no_newline => true,
            // The next hunk of the section goes on in the same piece.
            .hunk => piece_start != null and nkinds < diff_piece_lines,
            else => false,
        };
        if (piece_start) |ps| if (!body or nkinds == diff_piece_cut) {
            if (piece_end >= start_byte) try paintDiffPiece(gpa, window, content[ps..piece_end], ps, kinds[0..nkinds], piece_path, language);
            piece_start = null;
            nkinds = 0;
        };
        if (at >= end_byte and piece_start == null) break;
        if (body and (piece_start != null or got.kind != .hunk)) {
            if (piece_start == null) {
                piece_start = at;
                piece_path = walk.path();
            }
            kinds[nkinds] = got.kind;
            nkinds += 1;
            piece_end = nl;
        } else if (nl >= start_byte) {
            const style: Syn = switch (got.kind) {
                .hunk => .keyword,
                .meta, .old_path, .new_path => .comment,
                else => .none,
            };
            if (style != .none) window.fill(at, nl - at, @backingInt(style));
        }
        if (nl >= content.len) break;
        at = nl + 1;
    }
    if (piece_start) |ps| if (piece_end >= start_byte)
        try paintDiffPiece(gpa, window, content[ps..piece_end], ps, kinds[0..nkinds], piece_path, language);
    return styles;
}

/// The styles of `content[start..]` a diff is painted into: what falls
/// outside them is dropped.
const DiffWindow = struct {
    styles: []u8,
    start: usize,
    fn put(w: DiffWindow, at: usize, bytes: []const u8) void {
        const lo = @max(at, w.start);
        const hi = @min(at + bytes.len, w.start + w.styles.len);
        if (lo < hi) @memcpy(w.styles[lo - w.start .. hi - w.start], bytes[lo - at .. hi - at]);
    }
    fn fill(w: DiffWindow, at: usize, len: usize, style: u8) void {
        const lo = @max(at, w.start);
        const hi = @min(at + len, w.start + w.styles.len);
        if (lo < hi) @memset(w.styles[lo - w.start .. hi - w.start], style);
    }
};

fn paintDiffPiece(gpa: std.mem.Allocator, window: DiffWindow, bytes: []const u8, at: usize, kinds: []const diff.Kind, path: []const u8, language: bool) !void {
    const selected: ?Selected = if (language and syntax_started) (forExt(std.Io.Dir.path.extension(path)) catch null) else null;
    if (selected) |sel| {
        const hash = std.hash.Wyhash.hash(std.hash.Wyhash.hash(0, sel.name), bytes);
        diff_clock += 1;
        for (&diff_pieces) |*slot| if (slot.*) |*piece| if (piece.hash == hash and piece.styles.len == bytes.len) {
            piece.used = diff_clock;
            return window.put(at, piece.styles);
        };
        const colored = try syntax_allocator.alloc(u8, bytes.len);
        errdefer syntax_allocator.free(colored);
        try paintHunk(gpa, colored, bytes, kinds, sel);
        window.put(at, colored);
        // An empty slot, else the least recently used.
        var oldest: usize = 0;
        for (&diff_pieces, 0..) |*slot, i| {
            const piece = slot.* orelse {
                oldest = i;
                break;
            };
            if (piece.used < diff_pieces[oldest].?.used) oldest = i;
        }
        if (diff_pieces[oldest]) |old| syntax_allocator.free(old.styles);
        diff_pieces[oldest] = .{ .hash = hash, .styles = colored, .used = diff_clock };
        return;
    }
    // No language: each line in one colour, as diffs were always shown.
    var lines = std.mem.splitScalar(u8, bytes, '\n');
    var offset: usize = 0;
    for (kinds) |kind| {
        const line = lines.next() orelse break;
        const style: u8 = switch (kind) {
            .added => @backingInt(Syn.string) | ground_add,
            .removed => @backingInt(Syn.number) | ground_del,
            .no_newline => @backingInt(Syn.comment),
            .hunk => @backingInt(Syn.keyword),
            else => 0,
        };
        if (style != 0) window.fill(at + offset, line.len, style);
        if (style & (ground_add | ground_del) != 0 and line.len > 0) window.fill(at + offset, 1, style | ground_emph);
        offset += line.len + 1;
    }
}

/// One piece's styles: its old side and its new side each parsed as one
/// text, and every line's code coloured from its side, behind its
/// one-character prefix. A `@@` line between its hunks is in neither.
fn paintHunk(gpa: std.mem.Allocator, out: []u8, bytes: []const u8, kinds: []const diff.Kind, sel: Selected) !void {
    @memset(out, 0);
    const old_src = try gpa.alloc(u8, bytes.len);
    defer gpa.free(old_src);
    const new_src = try gpa.alloc(u8, bytes.len);
    defer gpa.free(new_src);
    var old_len: usize = 0;
    var new_len: usize = 0;
    var lines = std.mem.splitScalar(u8, bytes, '\n');
    for (kinds) |kind| {
        const line = lines.next() orelse break;
        const code = line[codeStart(line, kind)..];
        // A row a terminal wrapped goes on the line above, as it was printed.
        const joined = continuesRow(line, kind);
        if (kind == .context or kind == .removed) {
            if (joined and old_len > 0) old_len -= 1;
            @memcpy(old_src[old_len..][0..code.len], code);
            old_len += code.len;
            old_src[old_len] = '\n';
            old_len += 1;
        }
        if (kind == .context or kind == .added) {
            if (joined and new_len > 0) new_len -= 1;
            @memcpy(new_src[new_len..][0..code.len], code);
            new_len += code.len;
            new_src[new_len] = '\n';
            new_len += 1;
        }
    }
    // A side is parsed only when a line takes its colours from it: the old
    // side for removed lines, the new side for added lines, and context
    // from the new side, else from the old. A piece that only adds or only
    // removes is one parse.
    var removes = false;
    var adds = false;
    for (kinds) |kind| {
        removes = removes or kind == .removed;
        adds = adds or kind == .added;
    }
    const context_new = adds or !removes;
    const old_colors = try gpa.alloc(u8, old_len);
    defer gpa.free(old_colors);
    @memset(old_colors, 0);
    if (!context_new or removes) paint(old_colors, old_src[0..old_len], sel);
    const new_colors = try gpa.alloc(u8, new_len);
    defer gpa.free(new_colors);
    @memset(new_colors, 0);
    if (context_new) paint(new_colors, new_src[0..new_len], sel);

    lines = std.mem.splitScalar(u8, bytes, '\n');
    var offset: usize = 0;
    var old_at: usize = 0;
    var new_at: usize = 0;
    for (kinds) |kind| {
        const line = lines.next() orelse break;
        defer offset += line.len + 1;
        const skip = codeStart(line, kind);
        const code_len = line.len - skip;
        const dst = out[offset + skip ..][0..code_len];
        if (continuesRow(line, kind)) {
            if ((kind == .context or kind == .removed) and old_at > 0) old_at -= 1;
            if ((kind == .context or kind == .added) and new_at > 0) new_at -= 1;
        }
        switch (kind) {
            .removed => @memcpy(dst, old_colors[old_at..][0..code_len]),
            .added => @memcpy(dst, new_colors[new_at..][0..code_len]),
            .context => @memcpy(dst, if (context_new) new_colors[new_at..][0..code_len] else old_colors[old_at..][0..code_len]),
            .no_newline => @memset(out[offset..][0..line.len], @backingInt(Syn.comment)),
            .hunk => @memset(out[offset..][0..line.len], @backingInt(Syn.keyword)),
            else => {},
        }
        if (kind == .context or kind == .removed) old_at += code_len + 1;
        if (kind == .context or kind == .added) new_at += code_len + 1;
        const flag: u8 = switch (kind) {
            .added => ground_add,
            .removed => ground_del,
            else => 0,
        };
        if (flag != 0) for (out[offset..][0..line.len]) |*b| {
            b.* |= flag;
        };
        if (flag != 0 and line.len > 0) out[offset] |= ground_emph;
    }
}

fn continuesRow(line: []const u8, kind: diff.Kind) bool {
    return line.len > 0 and codeStart(line, kind) == 0 and
        (kind == .context or kind == .added or kind == .removed);
}

/// Where a hunk line's code starts: past its prefix, which a blank context
/// line (its space stripped) and a terminal's wrapped row have none of.
fn codeStart(line: []const u8, kind: diff.Kind) usize {
    if (line.len == 0) return 0;
    return switch (kind) {
        .context => @intFromBool(line[0] == ' '),
        .added => @intFromBool(line[0] == '+'),
        .removed => @intFromBool(line[0] == '-'),
        else => 0,
    };
}

fn diffSynAt(styles: []const u8, text: []const u8, needle: []const u8, offset: usize) Syn {
    return @fromBackingInt(@intCast(styles[std.mem.indexOf(u8, text, needle).? + offset] & syn_bits));
}

test {
    _ = diff;
    _ = @import("indent.zig");
}

test "every vendored textobject and indent query compiles against its grammar" {
    var failed: usize = 0;
    for (&specs) |*spec| for ([_]Lazy{ spec.objects, spec.indents }, [_][]const u8{ "textobjects", "indents" }) |lazy, what| {
        if (lazy.src.len == 0) continue;
        var error_offset: u32 = 0;
        const q = ts.Query.create(langOf(spec), lazy.src, &error_offset) catch {
            std.debug.print("{s} for {s} do not compile (offset {d})\n", .{ what, spec.name, error_offset });
            failed += 1;
            continue;
        };
        q.destroy();
    };
    try std.testing.expectEqual(@as(usize, 0), failed);
}

test "syntax context nested Zig containers and multiline function signatures" {
    if (comptime !minimal_grammars) return error.SkipZigTest;
    const gpa = std.testing.allocator;
    start(gpa);
    defer stop();
    const source =
        "pub const Outer = struct {\n" ++
        "    const Inner = struct {\n" ++
        "        pub fn run(\n" ++
        "            value: u32,\n" ++
        "        ) void {\n" ++
        "            const ignored = .{\n" ++
        "                value,\n" ++
        "            };\n" ++
        "        }\n" ++
        "    };\n" ++
        "};\n";
    const declarations = try contextDeclarations(gpa, "nested.zig", source);
    defer gpa.free(declarations);
    try std.testing.expectEqual(@as(usize, 3), declarations.len);
    try std.testing.expectEqual(@as(usize, 0), declarations[0].start_line);
    try std.testing.expectEqual(@as(usize, 10), declarations[0].end_line);
    try std.testing.expectEqual(@as(usize, 1), declarations[1].start_line);
    try std.testing.expectEqual(@as(usize, 2), declarations[2].start_line);
    try std.testing.expectEqual(@as(usize, 4), declarations[2].header_end_line);
    try std.testing.expectEqual(@as(usize, 8), declarations[2].end_line);
    try std.testing.expectEqualStrings("        pub fn run(\n            value: u32,\n        ) void {", source[declarations[2].start_byte..declarations[2].header_end_byte]);
    const unsupported = try contextDeclarations(gpa, "notes.unknown", source);
    defer gpa.free(unsupported);
    try std.testing.expectEqual(@as(usize, 0), unsupported.len);
}

test "syntax context Python class and function body excludes first statement" {
    if (!full_grammars) return error.SkipZigTest;
    const gpa = std.testing.allocator;
    start(gpa);
    defer stop();
    const source = "class Outer:\n    def run(\n        self, value,\n    ):\n        return value\n";
    const declarations = try contextDeclarations(gpa, "nested.py", source);
    defer gpa.free(declarations);
    try std.testing.expectEqual(@as(usize, 2), declarations.len);
    try std.testing.expectEqual(@as(usize, 0), declarations[0].header_end_line);
    try std.testing.expectEqual(@as(usize, 3), declarations[1].header_end_line);
}

test "syntax context multiline bindings and C++ namespaces preserve declaration starts" {
    if (comptime !minimal_grammars) return error.SkipZigTest;
    const gpa = std.testing.allocator;
    start(gpa);
    defer stop();
    const zig_source = "const Outer =\n    struct {\n        field: u8,\n    };\n";
    const zig_declarations = try contextDeclarations(gpa, "nested.zig", zig_source);
    defer gpa.free(zig_declarations);
    try std.testing.expectEqual(@as(usize, 1), zig_declarations.len);
    try std.testing.expectEqual(@as(usize, 0), zig_declarations[0].start_line);
    try std.testing.expectEqual(@as(usize, 1), zig_declarations[0].header_end_line);
    if (!minimal_grammars) return error.SkipZigTest;
    const cpp_source = "namespace example {\nstruct Outer {\n    int run() {\n        return 1;\n    }\n};\n}\n";
    const cpp_declarations = try contextDeclarations(gpa, "nested.cpp", cpp_source);
    defer gpa.free(cpp_declarations);
    try std.testing.expectEqual(@as(usize, 3), cpp_declarations.len);
    for (cpp_declarations, 0..) |declaration, row| {
        try std.testing.expectEqual(row, declaration.start_line);
        try std.testing.expectEqual(row, declaration.header_end_line);
    }
}

test "syntax context Rust modules impls and methods remain nested" {
    if (!full_grammars) return error.SkipZigTest;
    const gpa = std.testing.allocator;
    start(gpa);
    defer stop();
    const source = "mod outer {\n    impl Example {\n        fn run(&self) {\n            work();\n        }\n    }\n}\n";
    const declarations = try contextDeclarations(gpa, "nested.rs", source);
    defer gpa.free(declarations);
    try std.testing.expectEqual(@as(usize, 3), declarations.len);
    for (declarations, 0..) |declaration, row| {
        try std.testing.expectEqual(row, declaration.start_line);
        try std.testing.expectEqual(row, declaration.header_end_line);
        try std.testing.expectEqual(@as(usize, 6) - row, declaration.end_line);
    }
}

test "syntax formatted locations color hidden context and preserve multiline source" {
    if (!minimal_grammars) return error.SkipZigTest;
    const gpa = std.testing.allocator;
    start(gpa);
    defer stop();
    const first = "a path.c:1   \t/* open";
    const second = "             \t| comment body";
    const third = "a path.c:3   \t*/ int value = 42;";
    const content = first ++ "\n" ++ second ++ "\n" ++ third ++ "\n";
    const path = @constCast("a path.c");
    const rows = [_]locations.Row{
        .{ .kind = .match, .path = path, .code_start = "a path.c:1   \t".len, .location_end = 0, .at = .{ .line = 1 } },
        .{ .kind = .context, .path = path, .code_start = "             \t| ".len, .location_end = 0, .at = .{ .line = 2 } },
        .{ .kind = .match, .path = path, .code_start = "a path.c:3   \t".len, .location_end = 0, .at = .{ .line = 3 } },
    };
    const styles = try highlightLocationRows(gpa, content, &rows);
    defer gpa.free(styles);
    const body = std.mem.indexOf(u8, content, "comment body").?;
    try std.testing.expectEqual(@backingInt(Syn.comment), styles[body]);
    try std.testing.expectEqual(@backingInt(Syn.none), styles[body - 1]);
    const number = std.mem.indexOf(u8, content, "42").?;
    try std.testing.expectEqual(@backingInt(Syn.number), styles[number]);
    try std.testing.expectEqual(@backingInt(Syn.none), styles[0]);
}

test "syntax formatted locations separate alignment from Markdown indentation" {
    if (!full_grammars) return error.SkipZigTest;
    const gpa = std.testing.allocator;
    start(gpa);
    defer stop();
    const content = "short.md:1          \t# Heading\n" ++ "longer path.md:5   \t    # Code\n";
    const rows = [_]locations.Row{
        .{ .kind = .match, .path = @constCast("short.md"), .code_start = "short.md:1          \t".len, .location_end = 0, .at = .{ .line = 1 } },
        .{ .kind = .match, .path = @constCast("longer path.md"), .code_start = "longer path.md:5   \t".len, .location_end = 0, .at = .{ .line = 5 } },
    };
    const styles = try highlightLocationRows(gpa, content, &rows);
    defer gpa.free(styles);
    try std.testing.expectEqual(@backingInt(Syn.keyword), styles[std.mem.indexOf(u8, content, "Heading").?]);
    try std.testing.expectEqual(@backingInt(Syn.string), styles[std.mem.indexOf(u8, content, "Code").?]);
}

test "syntax a results row is coloured by the file its location names" {
    if (comptime !minimal_grammars) return error.SkipZigTest;
    start(std.testing.allocator);
    defer stop();
    const gpa = std.testing.allocator;
    const content =
        "src/a.zig:1:1 const S = struct {};\n" ++
        "src/b.md:2:1 # heading\n" ++
        "just some prose with a colon: here\n" ++
        "src/c.zig:3:1\n";
    const styles = try highlightLocations(gpa, content, 0, content.len);
    defer gpa.free(styles);
    try std.testing.expectEqual(content.len, styles.len);
    for (styles[0.."src/a.zig:1:1".len]) |b| try std.testing.expectEqual(@as(u8, 0), b);
    const zig_kw = std.mem.indexOf(u8, content, "struct").?;
    try std.testing.expectEqual(@backingInt(Syn.keyword), styles[zig_kw]);
    try std.testing.expectEqual(@backingInt(Syn.keyword), styles[zig_kw + 5]);
    const prose = std.mem.indexOf(u8, content, "just some prose").?;
    for (styles[prose .. prose + 14]) |b| try std.testing.expectEqual(@as(u8, 0), b);
    const bare = std.mem.indexOf(u8, content, "src/c.zig").?;
    for (styles[bare..]) |b| try std.testing.expectEqual(@as(u8, 0), b);
}

test "syntax a buffer with no locations in it keeps no highlights at all" {
    start(std.testing.allocator);
    defer stop();
    const content = "nothing has been said yet\n0: save: AccessDenied  (x2)\n";
    const styles = try highlightLocations(std.testing.allocator, content, 0, content.len);
    defer std.testing.allocator.free(styles);
    try std.testing.expectEqual(@as(usize, 0), styles.len);
}

test "syntax codeAfterLocation takes whole-token locations and nothing else" {
    const got = codeAfterLocation("src/x.zig:7:2-9 fn main() void {") orelse
        return error.ShouldBeALocation;
    try std.testing.expectEqualStrings("src/x.zig", got.path);
    try std.testing.expectEqualStrings("fn main() void {", got.text);
    try std.testing.expect(codeAfterLocation("main.zig some words") == null);
    try std.testing.expect(codeAfterLocation("note: this is prose") == null);
    try std.testing.expect(codeAfterLocation("src/x.zig:7:2x rest") == null);
    try std.testing.expect(codeAfterLocation("src/x.zig:7:2") == null);
    try std.testing.expect(codeAfterLocation("") == null);
    try std.testing.expect(codeAfterLocation("   leading space") == null);
    const indented = "    some directory/x.zig:7:2-9     return 42;";
    const nested = codeAfterLocation(indented) orelse return error.ShouldBeALocation;
    try std.testing.expectEqualStrings("some directory/x.zig", nested.path);
    try std.testing.expectEqualStrings("    return 42;", nested.text);
    try std.testing.expectEqualStrings(nested.text, indented[nested.at..]);
}

test "syntax default full grammar set highlights Typst source" {
    if (!full_grammars) return error.SkipZigTest;
    start(std.testing.allocator);
    defer stop();

    const source = "// note\n#let answer = 42\n#let text = \"hello\"\n";
    const styles = try highlightFileRange(std.testing.allocator, "paper.typst", source, 0, source.len);
    defer std.testing.allocator.free(styles);

    const comment_at = std.mem.indexOf(u8, source, "// note").?;
    const keyword_at = std.mem.indexOf(u8, source, "let").?;
    const number_at = std.mem.indexOf(u8, source, "42").?;
    const string_at = std.mem.indexOf(u8, source, "\"hello\"").?;
    try std.testing.expectEqual(Syn.comment, @as(Syn, @fromBackingInt(@intCast(styles[comment_at]))));
    try std.testing.expectEqual(Syn.keyword, @as(Syn, @fromBackingInt(@intCast(styles[keyword_at]))));
    try std.testing.expectEqual(Syn.number, @as(Syn, @fromBackingInt(@intCast(styles[number_at]))));
    try std.testing.expectEqual(Syn.string, @as(Syn, @fromBackingInt(@intCast(styles[string_at]))));

    const short_ext = try highlightFileRange(std.testing.allocator, "paper.typ", source, 0, source.len);
    defer std.testing.allocator.free(short_ext);
    try std.testing.expectEqual(Syn.keyword, @as(Syn, @fromBackingInt(@intCast(short_ext[keyword_at]))));
}

test "syntax Typst markup constructs paint and raw blocks inject their language" {
    if (!full_grammars) return error.SkipZigTest;
    start(std.testing.allocator);
    defer stop();

    const source =
        \\// note
        \\= Heading Title
        \\Some *bold* text with `raw` inline.
        \\#import "mod.typ": helper
        \\#let answer = 42
        \\#emit(7, "arg")
        \\```zig
        \\fn widget() u8 { return 99; }
        \\```
        \\
    ;
    const styles = try highlightFileRange(std.testing.allocator, "paper.typ", source, 0, source.len);
    defer std.testing.allocator.free(styles);

    const synAt = struct {
        fn f(s: []const u8, src: []const u8, needle: []const u8, offset: usize) Syn {
            return @fromBackingInt(@intCast(s[std.mem.indexOf(u8, src, needle).? + offset]));
        }
    }.f;
    try std.testing.expectEqual(Syn.keyword, synAt(styles, source, "= Heading", 0));
    try std.testing.expectEqual(Syn.keyword, synAt(styles, source, "Heading", 0));
    try std.testing.expectEqual(Syn.comment, synAt(styles, source, "bold", 0));
    try std.testing.expectEqual(Syn.string, synAt(styles, source, "raw` inline", 0));
    try std.testing.expectEqual(Syn.keyword, synAt(styles, source, "emit", 0));
    try std.testing.expectEqual(Syn.keyword, synAt(styles, source, "#emit", 0));
    try std.testing.expectEqual(Syn.string, synAt(styles, source, "```zig", 0));
    try std.testing.expectEqual(Syn.string, synAt(styles, source, "```zig", 3));
    try std.testing.expectEqual(Syn.keyword, synAt(styles, source, "fn widget", 0));
    try std.testing.expectEqual(Syn.number, synAt(styles, source, "99", 0));
    try std.testing.expectEqual(Syn.none, synAt(styles, source, "widget", 0));

    try std.testing.expectEqual(Syn.comment, synAt(styles, source, "// note", 0));
    try std.testing.expectEqual(Syn.keyword, synAt(styles, source, "import", 0));
    try std.testing.expectEqual(Syn.keyword, synAt(styles, source, "let", 0));
    try std.testing.expectEqual(Syn.number, synAt(styles, source, "42", 0));
    try std.testing.expectEqual(Syn.string, synAt(styles, source, "\"arg\"", 0));
}

test "syntax markdown highlights markup, injects inline spans and fenced code blocks" {
    if (!full_grammars) return error.SkipZigTest;
    start(std.testing.allocator);
    defer stop();

    const source =
        "# Heading *slant* Title\n" ++
        "\n" ++
        "Prose with **stout** and *lean* plus `snippet` inline.\n" ++
        "\n" ++
        "```zig\n" ++
        "fn gadget() u8 { return 77; }\n" ++
        "```\n";
    const styles = try highlightFileRange(std.testing.allocator, "doc.md", source, 0, source.len);
    defer std.testing.allocator.free(styles);

    const synAt = struct {
        fn f(s: []const u8, src: []const u8, needle: []const u8, offset: usize) Syn {
            return @fromBackingInt(@intCast(s[std.mem.indexOf(u8, src, needle).? + offset]));
        }
    }.f;
    try std.testing.expectEqual(Syn.keyword, synAt(styles, source, "Title", 0));
    try std.testing.expectEqual(Syn.number, synAt(styles, source, "slant", 0));
    try std.testing.expectEqual(Syn.comment, synAt(styles, source, "stout", 0));
    try std.testing.expectEqual(Syn.number, synAt(styles, source, "lean", 0));
    try std.testing.expectEqual(Syn.string, synAt(styles, source, "snippet", 0));
    try std.testing.expectEqual(Syn.string, synAt(styles, source, "```zig", 0));
    try std.testing.expectEqual(Syn.keyword, synAt(styles, source, "fn gadget", 0));
    try std.testing.expectEqual(Syn.number, synAt(styles, source, "77", 0));
    try std.testing.expectEqual(Syn.none, synAt(styles, source, "gadget", 0));
}

test "syntax inline fast path agrees with full Markdown query" {
    if (!full_grammars) return error.SkipZigTest;
    start(std.testing.allocator);
    defer stop();
    const selected = (try forLang("markdown_inline")).?;
    const check = struct {
        fn compare(sel: Selected, source: []const u8) !void {
            const tree = sel.parser.parseString(source, null) orelse return error.ParseFailed;
            defer tree.destroy();
            const expected = try std.testing.allocator.alloc(u8, source.len);
            defer std.testing.allocator.free(expected);
            const actual = try std.testing.allocator.alloc(u8, source.len);
            defer std.testing.allocator.free(actual);
            for ([_]Syn{ .none, .keyword }) |background| {
                @memset(expected, @backingInt(background));
                @memset(actual, @backingInt(background));
                runQuery(expected, sel, tree, 0);
                inject(actual, source, tree.rootNode(), true);
                if (!std.mem.eql(u8, expected, actual)) std.debug.print("inline mismatch: {s}\n", .{source});
                try std.testing.expectEqualSlices(u8, expected, actual);
            }
        }
    }.compare;
    for ([_][]const u8{
        "",                                         "plain prose",
        "ação Ελληνικά 日本語 🙂",
        "123 456",                                  "tabs\tand spaces",
        "'quoted' (parentheses) \"double quotes\"", "https://example.org [email protected]",
        "&amp; &#10; &#x20;",                       "~~struck~~ $formula$",
        "*emphasis* __strong__",                    "**bold** _emphasis_",
        "`code` and ``a`b``",                       "[text](target \"title\")",
        "![description](image)",                    "[shortcut] [reference][label]",
        "[[wiki|text]]",                            "<https://example.org> <[email protected]>",
        "<i>text</i>",                              "\\*escaped\\*",
        "soft\nline",                               "hard  \nline",
        "hard\\\nline",                             "tab\t\nline",
        "hard  \r\nline",                           "hard  \rline",
        "**broken",                                 "[broken](",
        "`broken",
    }) |source| try check(selected, source);
    for (0..128) |byte| {
        const char: u8 = @intCast(byte);
        const source = [_]u8{ char, 'a', 'b', char, ' ', char, char, 'c', char, char };
        try check(selected, &source);
    }
}

test "syntax plain Markdown keeps block styles without starting the inline parser" {
    if (!full_grammars) return error.SkipZigTest;
    start(std.testing.allocator);
    defer stop();
    const source = "# Heading\n\nPlain prose.\n\n    indented code\n";
    const styles = try highlightFileRange(std.testing.allocator, "a.md", source, 0, source.len);
    defer std.testing.allocator.free(styles);
    try std.testing.expectEqual(@backingInt(Syn.keyword), styles[2]);
    try std.testing.expectEqual(@backingInt(Syn.none), styles[std.mem.indexOf(u8, source, "Plain").?]);
    try std.testing.expectEqual(@backingInt(Syn.string), styles[std.mem.indexOf(u8, source, "indented").?]);
    for (specs) |spec| {
        if (std.mem.eql(u8, spec.name, "markdown_inline")) try std.testing.expect(spec.selected == null);
    }
}

test "syntax highlightDiff colors unified diff lines by prefix" {
    const diff_text =
        "diff --git a/x b/x\n" ++
        "--- a/x\n" ++
        "+++ b/x\n" ++
        "@@ -1,2 +1,2 @@\n" ++
        " context\n" ++
        "-old line\n" ++
        "+new line\n";
    const styles = try highlightDiff(std.testing.allocator, diff_text, 0, diff_text.len);
    defer std.testing.allocator.free(styles);
    try std.testing.expectEqual(Syn.comment, diffSynAt(styles, diff_text, "diff --git", 0));
    try std.testing.expectEqual(Syn.comment, diffSynAt(styles, diff_text, "--- a/x", 0));
    try std.testing.expectEqual(Syn.comment, diffSynAt(styles, diff_text, "+++ b/x", 0));
    try std.testing.expectEqual(Syn.keyword, diffSynAt(styles, diff_text, "@@ -1,2", 0));
    try std.testing.expectEqual(Syn.none, diffSynAt(styles, diff_text, " context", 0));
    // A file in no known language: each line in one colour, and tinted.
    try std.testing.expectEqual(Syn.number, diffSynAt(styles, diff_text, "-old line", 0));
    try std.testing.expectEqual(Syn.string, diffSynAt(styles, diff_text, "+new line", 0));
    try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "-old line").?] & ground_del != 0);
    try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "+new line").? + 4] & ground_add != 0);
    try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, " context").?] & (ground_add | ground_del) == 0);
    // The row's ground on its first byte: the strong one, its other bytes none.
    try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "-old line").?] & ground_emph != 0);
    try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "+new line").? + 4] & (ground_emph | ground_line) == 0);
}

test "syntax a Zig hunk is coloured as Zig, each side parsed whole" {
    if (comptime !minimal_grammars) return error.SkipZigTest;
    start(std.testing.allocator);
    defer stop();
    const diff_text =
        "diff --git a/src/shape.zig b/src/shape.zig\n" ++
        "index 1111111..2222222 100644\n" ++
        "--- a/src/shape.zig\n" ++
        "+++ b/src/shape.zig\n" ++
        "@@ -1,6 +1,6 @@\n" ++
        " const Shape = struct {\n" ++
        "-    side: u8 = 7,\n" ++
        "+    side: u16 = 42,\n" ++
        "     const note =\n" ++
        "-        \\\\old words defer\n" ++
        "+        \\\\new words defer\n" ++
        "     ;\n" ++
        " };\n";
    const styles = try highlightDiff(std.testing.allocator, diff_text, 0, diff_text.len);
    defer std.testing.allocator.free(styles);
    try std.testing.expectEqual(Syn.keyword, diffSynAt(styles, diff_text, "struct", 0));
    try std.testing.expectEqual(Syn.number, diffSynAt(styles, diff_text, "7,", 0));
    try std.testing.expectEqual(Syn.number, diffSynAt(styles, diff_text, "42", 0));
    // A multiline string, told apart only by parsing the side it is on:
    // `defer` inside it is no keyword.
    try std.testing.expectEqual(Syn.string, diffSynAt(styles, diff_text, "old words defer", 10));
    try std.testing.expectEqual(Syn.string, diffSynAt(styles, diff_text, "new words defer", 10));
    // The prefix is no code: it carries the tint alone.
    const added = std.mem.indexOf(u8, diff_text, "+    side").?;
    try std.testing.expectEqual(ground_add | ground_emph, styles[added]);
    try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "42").?] & ground_add != 0);
    try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "7,").?] & ground_del != 0);
    try std.testing.expectEqual(Syn.comment, diffSynAt(styles, diff_text, "index 111", 0));

    // A window in the middle is coloured as the whole is.
    const from = std.mem.indexOf(u8, diff_text, "     const note").?;
    const part = try highlightDiff(std.testing.allocator, diff_text, from, diff_text.len);
    defer std.testing.allocator.free(part);
    try std.testing.expectEqualSlices(u8, styles[from..], part);
}

test "syntax a Python hunk is coloured as Python" {
    if (!full_grammars) return error.SkipZigTest;
    start(std.testing.allocator);
    defer stop();
    const diff_text =
        "--- a/tool.py\n" ++
        "+++ b/tool.py\n" ++
        "@@ -1,3 +1,4 @@\n" ++
        " def run(n):\n" ++
        "-    return n\n" ++
        "+    # doubled now\n" ++
        "+    return n * 2\n" ++
        " \n";
    const styles = try highlightDiff(std.testing.allocator, diff_text, 0, diff_text.len);
    defer std.testing.allocator.free(styles);
    try std.testing.expectEqual(Syn.keyword, diffSynAt(styles, diff_text, "def", 0));
    try std.testing.expectEqual(Syn.keyword, diffSynAt(styles, diff_text, "return n\n", 0));
    try std.testing.expectEqual(Syn.comment, diffSynAt(styles, diff_text, "# doubled", 2));
    try std.testing.expectEqual(Syn.number, diffSynAt(styles, diff_text, "2\n", 0));
}

test "syntax a deleted file's lines are coloured in its language" {
    if (comptime !minimal_grammars) return error.SkipZigTest;
    start(std.testing.allocator);
    defer stop();
    const diff_text =
        "diff --git a/gone.zig b/gone.zig\n" ++
        "deleted file mode 100644\n" ++
        "--- a/gone.zig\n" ++
        "+++ /dev/null\n" ++
        "@@ -1,2 +0,0 @@\n" ++
        "-const Gone = enum { a };\n" ++
        "-// the end\n";
    const styles = try highlightDiff(std.testing.allocator, diff_text, 0, diff_text.len);
    defer std.testing.allocator.free(styles);
    try std.testing.expectEqual(Syn.keyword, diffSynAt(styles, diff_text, "enum", 0));
    try std.testing.expectEqual(Syn.comment, diffSynAt(styles, diff_text, "// the end", 3));
    try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "enum").?] & ground_del != 0);
    try std.testing.expectEqual(Syn.comment, diffSynAt(styles, diff_text, "deleted file", 0));
}

test "syntax a hunk in no known language keeps the line colours" {
    start(std.testing.allocator);
    defer stop();
    const diff_text =
        "--- a/notes.unknownext\n" ++
        "+++ b/notes.unknownext\n" ++
        "@@ -1 +1 @@\n" ++
        "-const struct 1\n" ++
        "+const struct 2\n";
    const styles = try highlightDiff(std.testing.allocator, diff_text, 0, diff_text.len);
    defer std.testing.allocator.free(styles);
    try std.testing.expectEqual(Syn.number, diffSynAt(styles, diff_text, "struct 1", 0));
    try std.testing.expectEqual(Syn.string, diffSynAt(styles, diff_text, "struct 2", 0));
    try std.testing.expectEqual(Syn.string, diffSynAt(styles, diff_text, "+const struct 2", 0));
}

test "syntax git diff output in a command pane is told and coloured by its rows" {
    if (comptime !minimal_grammars) return error.SkipZigTest;
    start(std.testing.allocator);
    defer stop();
    // A command pane's rows: its command line, then git's output, with one
    // long added line the terminal wrapped onto a second row.
    const rows = [_][]const u8{
        "git diff",
        "diff --git a/main.zig b/main.zig",
        "--- a/main.zig",
        "+++ b/main.zig",
        "@@ -1,2 +1,2 @@",
        " pub fn main() void {",
        "+    const answer: u32 = 42; // the ",
        "wrapped rest",
        "-    return;",
        "",
    };
    try std.testing.expect(diff.looksLikeDiff(&rows));
    try std.testing.expect(!diff.looksLikeDiff(rows[5..]));
    const text = try std.mem.join(std.testing.allocator, "\n", &rows);
    defer std.testing.allocator.free(text);
    const styles = try highlightDiffRows(std.testing.allocator, text, 0, text.len, true);
    defer std.testing.allocator.free(styles);
    try std.testing.expectEqual(Syn.none, diffSynAt(styles, text, "git diff", 0));
    try std.testing.expectEqual(Syn.keyword, diffSynAt(styles, text, "fn main", 0));
    try std.testing.expectEqual(Syn.number, diffSynAt(styles, text, "42", 0));
    // The wrapped row stays an added line, and inside the comment.
    try std.testing.expect(styles[std.mem.indexOf(u8, text, "wrapped rest").?] & ground_add != 0);
    try std.testing.expectEqual(Syn.comment, diffSynAt(styles, text, "wrapped rest", 0));
    try std.testing.expect(styles[std.mem.indexOf(u8, text, "return").?] & ground_del != 0);
}

test "syntax a section's small hunks share one parse" {
    if (comptime !minimal_grammars) return error.SkipZigTest;
    const gpa = std.testing.allocator;
    start(gpa);
    defer stop();
    const diff_text =
        "--- a/x.zig\n+++ b/x.zig\n" ++
        "@@ -1 +1 @@\n-const a = 1;\n+const a = 2;\n" ++
        "@@ -10 +10 @@\n-const b = 1;\n+const b = 2;\n" ++
        "@@ -20 +20 @@\n-const c = 1;\n+const c = 2;\n" ++
        "--- a/y.zig\n+++ b/y.zig\n" ++
        "@@ -1 +1 @@\n-const d = 1;\n+const d = 2;\n";
    const styles = try highlightDiff(gpa, diff_text, 0, diff_text.len);
    defer gpa.free(styles);
    var cached: usize = 0;
    for (diff_pieces) |slot| cached += @intFromBool(slot != null);
    try std.testing.expectEqual(@as(usize, 2), cached); // x.zig's three hunks, and y.zig's
    try std.testing.expectEqual(Syn.keyword, diffSynAt(styles, diff_text, "@@ -10", 0));
    try std.testing.expectEqual(Syn.number, diffSynAt(styles, diff_text, "2;\n@@ -20", 0));
    try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "@@ -10").?] & (ground_add | ground_del) == 0);
}

test "syntax a hunk painted once is kept, and a long one is parsed in pieces" {
    if (comptime !minimal_grammars) return error.SkipZigTest;
    const gpa = std.testing.allocator;
    start(gpa);
    defer stop();
    var text: std.Io.Writer.Allocating = .init(gpa);
    defer text.deinit();
    const n = diff_piece_cut * 20 + 10;
    try text.writer.print("--- /dev/null\n+++ b/big.zig\n@@ -0,0 +1,{d} @@\n", .{n});
    for (0..n) |i| try text.writer.print("+const v{d} = {d};\n", .{ i, i });
    const content = text.written();
    const at = std.mem.indexOf(u8, content, "+const v1000 ").?;
    const window = try highlightDiff(gpa, content, at, at + 200);
    defer gpa.free(window);
    try std.testing.expectEqual(Syn.number, @as(Syn, @fromBackingInt(@intCast(window["+const v1000 = ".len] & syn_bits))));
    var cached: usize = 0;
    for (diff_pieces) |slot| if (slot) |piece| {
        cached += 1;
        // One piece of many, not the whole hunk.
        try std.testing.expect(piece.styles.len < content.len / 4);
    };
    try std.testing.expectEqual(@as(usize, 1), cached);
    const again = try highlightDiff(gpa, content, at, at + 200);
    defer gpa.free(again);
    try std.testing.expectEqualSlices(u8, window, again);
    cached = 0;
    for (diff_pieces) |slot| cached += @intFromBool(slot != null);
    try std.testing.expectEqual(@as(usize, 1), cached);
}

test "syntax result fragments preserve source indentation and inline markup" {
    start(std.testing.allocator);
    defer stop();
    const fixtures = [_]struct { path: []const u8, source: []const u8 }{
        .{ .path = "a.zig", .source = "    const number = 42; // note" },
        .{ .path = "    nested path/a.zig", .source = "    return call(42, \"hello\"); // note" },
        .{ .path = "a.md", .source = "# Heading *slant*" },
        .{ .path = "a.md", .source = "**bold** and `code`" },
        .{ .path = "a.md", .source = "    # this is indented code" },
        .{ .path = "a.md", .source = "\t# tab-indented code" },
        .{ .path = "a.py", .source = "    return \"hello\"" },
    };
    for (fixtures) |fixture| {
        const expected = try highlightFileRange(std.testing.allocator, fixture.path, fixture.source, 0, fixture.source.len);
        defer std.testing.allocator.free(expected);
        const row = try std.fmt.allocPrint(std.testing.allocator, "{s}:12:3-9 {s}", .{ fixture.path, fixture.source });
        defer std.testing.allocator.free(row);
        const actual = try highlightLocations(std.testing.allocator, row, 0, row.len);
        defer std.testing.allocator.free(actual);
        if (expected.len == 0) {
            try std.testing.expectEqual(@as(usize, 0), actual.len);
            continue;
        }
        const code_at = row.len - fixture.source.len;
        try std.testing.expectEqualSlices(u8, expected, actual[code_at..]);
        for (actual[0..code_at]) |style| try std.testing.expectEqual(@as(u8, 0), style);
    }
}

test "syntax query filtering preserves upstream colors" {
    var allocator: std.heap.DebugAllocator(.{ .stack_trace_frames = 0, .safety = true }) = .init;
    defer if (allocator.deinit() != .ok) @panic("leaked syntax query allocations");
    start(allocator.allocator());
    defer stop();
    const source = "// comment\n# Heading *inline*\nconst value = 42;\nif (true) { return \"quoted\"; }\n/* multi\nline */\n";
    inline for (grammar_manifest.all) |grammar| {
        if (comptime grammarSelected(grammar)) {
            const selected = (try forLang(grammar.name)).?;
            const raw_source = @field(ts_queries, grammar.name ++ "_highlights_unfiltered");
            var error_offset: u32 = 0;
            const raw_query = try ts.Query.create(selected.lang, raw_source, &error_offset);
            defer raw_query.destroy();
            var reference = selected;
            reference.query = raw_query;
            reference.capture_styles = try std.testing.allocator.alloc(u8, raw_query.captureCount());
            defer std.testing.allocator.free(reference.capture_styles);
            for (reference.capture_styles, 0..) |*style, id| style.* = @backingInt(grammar_manifest.synFor(raw_query.captureNameForId(@intCast(id)) orelse ""));
            const tree = selected.parser.parseString(source, null) orelse return error.ParseFailed;
            defer tree.destroy();
            var expected: [source.len]u8 = @splat(0);
            var actual: [source.len]u8 = @splat(0);
            runQuery(&expected, reference, tree, 0);
            runQuery(&actual, selected, tree, 0);
            if (!std.mem.eql(u8, &expected, &actual)) std.debug.print("query mismatch: {s}\n", .{grammar.name});
            try std.testing.expectEqualSlices(u8, &expected, &actual);
        }
    }
}

test "syntax Zig keyword captures cover both bytes beyond line ten thousand" {
    if (comptime !minimal_grammars) return error.SkipZigTest;
    start(std.testing.allocator);
    defer stop();
    const code = "pub fn main() void {\n    if (true) return;\n}\n";
    const source = try std.testing.allocator.alloc(u8, 10_001 + code.len);
    defer std.testing.allocator.free(source);
    @memset(source[0..10_001], '\n');
    @memcpy(source[10_001..], code);
    const styles = try highlightFileRange(std.testing.allocator, "a.zig", source, 10_001, source.len);
    defer std.testing.allocator.free(styles);
    for ([_][]const u8{ "fn", "if" }) |keyword| {
        const at = std.mem.indexOf(u8, code, keyword).?;
        try std.testing.expectEqual(@backingInt(Syn.keyword), styles[at]);
        try std.testing.expectEqual(@backingInt(Syn.keyword), styles[at + 1]);
    }
}

test "syntax allocator switching clears default-runtime caches" {
    if (comptime !minimal_grammars) return error.SkipZigTest;
    const source = "fn main() void {}";
    const initial = try highlightFileRange(std.testing.allocator, "a.zig", source, 0, source.len);
    std.testing.allocator.free(initial);
    start(std.testing.allocator);
    const custom = try highlightFileRange(std.testing.allocator, "a.zig", source, 0, source.len);
    std.testing.allocator.free(custom);
    stop();
    const restored = try highlightFileRange(std.testing.allocator, "a.zig", source, 0, source.len);
    defer std.testing.allocator.free(restored);
    defer stop();
    try std.testing.expectEqual(@backingInt(Syn.keyword), restored[0]);
    try std.testing.expectEqual(@backingInt(Syn.keyword), restored[1]);
}

test "syntax location context snapshots retain omitted multiline comment scope" {
    if (!minimal_grammars) return error.SkipZigTest;
    const gpa = std.testing.allocator;
    start(gpa);
    defer stop();
    const source = "/* documentation\nconst int value = 42;\n*/\n";
    const source_colors = try highlightFileRange(gpa, "a.c", source, 0, source.len);
    defer gpa.free(source_colors);
    const code = "const int value = 42;";
    const source_start = std.mem.indexOf(u8, source, code).?;
    const content = "| \t" ++ code ++ "\n";
    const rows = [_]locations.Row{.{
        .kind = .context,
        .path = @constCast("a.c"),
        .code_start = "| \t".len,
        .location_end = 0,
        .at = .{ .line = 2 },
        .colors = source_colors[source_start..][0..code.len],
    }};
    const styles = try highlightLocationRows(gpa, content, &rows);
    defer gpa.free(styles);
    for (styles[rows[0].code_start..][0..code.len]) |style|
        try std.testing.expectEqual(@backingInt(Syn.comment), style);
    try std.testing.expectEqual(@backingInt(Syn.none), styles[0]);
}

test "syntax declaration locations clear snapshots without muting ordinary context" {
    if (comptime !minimal_grammars) return error.SkipZigTest;
    const gpa = std.testing.allocator;
    start(gpa);
    defer stop();
    const header = "pub fn run() void {";
    const content = "| \t" ++ header ++ "\n| \t    const value = 42;\nfile.zig:3\t}\n";
    var snapshots = @as([header.len]u8, @splat(0xff));
    const path = @constCast("file.zig");
    const rows = [_]locations.Row{
        .{ .kind = .context, .path = path, .code_start = 3, .location_end = 0, .at = .{ .line = 1 }, .colors = &snapshots, .declaration = true },
        .{ .kind = .context, .path = path, .code_start = 3, .location_end = 0, .at = .{ .line = 2 } },
        .{ .kind = .match, .path = path, .code_start = "file.zig:3\t".len, .location_end = 0, .at = .{ .line = 3 } },
    };
    const styles = try highlightLocationRows(gpa, content, &rows);
    defer gpa.free(styles);
    for (styles[3..][0..header.len]) |style| try std.testing.expectEqual(@as(u8, 0), style);
    try std.testing.expectEqual(@backingInt(Syn.number), styles[std.mem.indexOf(u8, content, "42").?]);
}

test "syntax stacked addresses do not split multiline source groups" {
    if (!minimal_grammars) return error.SkipZigTest;
    const gpa = std.testing.allocator;
    start(gpa);
    defer stop();
    const content = "a.c:1:1\n/* open\na.c:2:1\nint value = 42;\na.c:3:1\n*/ int other = 7;\n";
    const path = @constCast("a.c");
    const rows = [_]locations.Row{
        .{ .kind = .match, .path = path, .code_start = 7, .location_end = 7, .at = .{ .line = 1 } },
        .{ .kind = .preview, .path = path, .code_start = 0, .location_end = 0, .at = .{ .line = 1 } },
        .{ .kind = .match, .path = path, .code_start = 7, .location_end = 7, .at = .{ .line = 2 } },
        .{ .kind = .preview, .path = path, .code_start = 0, .location_end = 0, .at = .{ .line = 2 } },
        .{ .kind = .match, .path = path, .code_start = 7, .location_end = 7, .at = .{ .line = 3 } },
        .{ .kind = .preview, .path = path, .code_start = 0, .location_end = 0, .at = .{ .line = 3 } },
    };
    const styles = try highlightLocationRows(gpa, content, &rows);
    defer gpa.free(styles);
    try std.testing.expectEqual(@backingInt(Syn.comment), styles[std.mem.indexOf(u8, content, "42").?]);
    try std.testing.expectEqual(@backingInt(Syn.number), styles[std.mem.indexOf(u8, content, "7;").?]);
    for ([_][]const u8{ "a.c:1:1", "a.c:2:1", "a.c:3:1" }) |label| {
        const at = std.mem.indexOf(u8, content, label).?;
        for (styles[at..][0..label.len]) |style| try std.testing.expectEqual(@backingInt(Syn.none), style);
    }
}

test "syntax source analysis preserves declarations and injected colors" {
    const gpa = std.testing.allocator;
    start(gpa);
    defer stop();
    const Fixture = struct { path: []const u8, source: []const u8 };
    for ([_]Fixture{
        .{ .path = "a.zig", .source = "const Outer = struct {\n // comment\n const Inner = struct {\n pub fn run(\n x: u32,\n ) u32 { return x; }\n };\n};\n" },
        .{ .path = "a.cpp", .source = "namespace Outer {\nstruct Inner {\nint run(\n int x\n) { return x; }\n};\n}\n" },
        .{ .path = "a.rs", .source = "mod outer {\nstruct Inner {}\nimpl Inner {\nfn run(\n &self\n) {}\n}\n}\n" },
        .{ .path = "a.js", .source = "function outer() {\nclass Inner {\nrun(\n x\n) { return x; }\n}\n}\n" },
        .{ .path = "a.py", .source = "class Outer:\n    class Inner:\n        def run(\n            self, x\n        ):\n            return x\n" },
        .{ .path = "a.md", .source = "# Heading\n\n```zig\npub fn run() void {}\n```\n" },
        .{ .path = "a.typst", .source = "= Heading\n\n```zig\npub fn run() void {}\n```\n" },
    }) |fixture| {
        if (!supportsPath(fixture.path)) continue;
        var analysis = try analyzeSource(gpa, fixture.path, fixture.source, true, true);
        defer analysis.deinit(gpa);
        const colors = try highlightFileRange(gpa, fixture.path, fixture.source, 0, fixture.source.len);
        defer gpa.free(colors);
        try std.testing.expectEqualSlices(u8, colors, analysis.colors);

        // Compare the previous named-node walk to the cursor walk, including
        // source ordering, wrapper deduplication and inclusive declaration ends.
        const selected = (try forExt(std.Io.Dir.path.extension(fixture.path))).?;
        const tree = selected.parser.parseString(fixture.source, null).?;
        defer tree.destroy();
        var reference: std.ArrayList(ContextDeclaration) = .empty;
        defer reference.deinit(gpa);
        var node = tree.rootNode();
        walk: while (true) {
            if (contextSpan(node, fixture.source)) |span| {
                if (reference.items.len == 0 or reference.items[reference.items.len - 1].start_line != span.start_line or
                    reference.items[reference.items.len - 1].end_line != span.end_line)
                    try reference.append(gpa, span);
            }
            if (node.namedChild(0)) |child| {
                node = child;
                continue;
            }
            while (node.nextNamedSibling() == null) node = node.parent() orelse break :walk;
            node = node.nextNamedSibling().?;
        }
        try std.testing.expectEqual(reference.items.len, analysis.declarations.len);
        for (reference.items, analysis.declarations) |old, new| try std.testing.expect(std.meta.eql(old, new));

        var declarations_only = try analyzeSource(gpa, fixture.path, fixture.source, true, false);
        defer declarations_only.deinit(gpa);
        try std.testing.expectEqual(@as(usize, 0), declarations_only.colors.len);
        try std.testing.expectEqual(analysis.declarations.len, declarations_only.declarations.len);
        var colors_only = try analyzeSource(gpa, fixture.path, fixture.source, false, true);
        defer colors_only.deinit(gpa);
        try std.testing.expectEqual(@as(usize, 0), colors_only.declarations.len);
        try std.testing.expectEqualSlices(u8, analysis.colors, colors_only.colors);
    }
    var unsupported = try analyzeSource(gpa, "a.unknown", "text", true, true);
    unsupported.deinit(gpa);
    try std.testing.expectEqual(@as(usize, 0), unsupported.declarations.len);
    try std.testing.expectEqual(@as(usize, 0), unsupported.colors.len);
}

test "tables are the pipe_tables tree-sitter finds" {
    if (!full_grammars) return error.SkipZigTest;
    start(std.testing.allocator);
    defer stop();
    const Tables = @import("Tables.zig");
    const source =
        "# Tables\n" ++
        "\n" ++
        "| a | b |\n" ++
        "|---|:-:|\n" ++
        "| 1 | 2 |\n" ++
        "no pipe row\n" ++
        "\n" ++
        "a | b\n" ++
        "--|--\n" ++
        "c | d\n" ++
        "# heading ends it\n" ++
        "| x |\n" ++
        "|---|\n" ++
        "\n" ++
        "```\n" ++
        "| in | fence |\n" ++
        "|----|-------|\n" ++
        "```\n" ++
        "\n" ++
        "| one | two |\n" ++
        "|-----|\n" ++
        "\n" ++
        "  | indented | table |\n" ++
        "  | -------- | ----- |\n" ++
        "  | row      | here  |\n" ++
        "> quote ends\n" ++
        "\n" ++
        "| esc \\| aped | two |\n" ++
        "| --- | --- |\n" ++
        "- list ends\n";
    const selected = (try forLang("markdown")).?;
    const tree = selected.parser.parseString(source, null) orelse return error.ParseFailed;
    defer tree.destroy();
    // Every pipe_table node's lines, wherever it is in the tree.
    var found: std.ArrayList([2]u32) = .empty;
    defer found.deinit(std.testing.allocator);
    var stack: std.ArrayList(ts.Node) = .empty;
    defer stack.deinit(std.testing.allocator);
    try stack.append(std.testing.allocator, tree.rootNode());
    while (stack.pop()) |node| {
        if (std.mem.eql(u8, node.kind(), "pipe_table")) {
            const end = node.endPoint();
            try found.append(std.testing.allocator, .{ node.startPoint().row, end.row + @intFromBool(end.column > 0) });
            continue;
        }
        var i = node.childCount();
        while (i > 0) : (i -= 1) if (node.child(i - 1)) |child| try stack.append(std.testing.allocator, child);
    }
    // The tables, the indented one and the escaped pipe's; not the fence's
    // or the one whose delimiter has a cell too few.
    try std.testing.expectEqual(@as(usize, 5), found.items.len);
    var t: Tables = .{};
    defer t.deinit(std.testing.allocator);
    try t.scan(@import("config.zig").tab_width, std.testing.allocator, source);
    var mine: std.ArrayList([2]u32) = .empty;
    defer mine.deinit(std.testing.allocator);
    for (t.list.items) |table| try mine.append(std.testing.allocator, .{ table.first, table.end });
    std.testing.expectEqualSlices([2]u32, found.items, mine.items) catch |e| {
        std.debug.print("tree-sitter {any}\nTables     {any}\n", .{ found.items, mine.items });
        return e;
    };
}

test "a kept tree told its edits parses to the fresh parse's tree, places and all" {
    if (comptime !minimal_grammars) return error.SkipZigTest;
    const gpa = std.testing.allocator;
    const a = "const std = @import(\"std\");\n\nfn f(x: u32) u32 {\n    return x;\n}\n\ntest \"t\" {\n    _ = f(1);\n}\n";
    const old_tree = parseTree("a.zig", a, null) orelse return error.NoTree;
    // Two edits in a row, as typing makes them: a line opened in f, then a
    // call typed on it (one of them spans rows, one does not).
    const Edit = struct { off: usize, len: usize, ins: []const u8 };
    const edits = [_]Edit{ .{ .off = 47, .len = 0, .ins = "\n    " }, .{ .off = 52, .len = 0, .ins = "g(x);" } };
    var text: []u8 = try gpa.dupe(u8, a);
    defer gpa.free(text);
    for (edits) |e| {
        editTree(old_tree, text[0..e.off], text[e.off..][0..e.len], e.ins);
        const next = try std.mem.concat(gpa, u8, &.{ text[0..e.off], e.ins, text[e.off + e.len ..] });
        gpa.free(text);
        text = next;
    }
    try std.testing.expect(std.mem.indexOf(u8, text, "u32 {\n    g(x);\n    return x;") != null);
    const reused = parseTree("a.zig", text, old_tree) orelse return error.NoTree;
    defer destroyTree(reused);
    destroyTree(old_tree);
    const fresh = parseTree("a.zig", text, null) orelse return error.NoTree;
    defer destroyTree(fresh);
    const r: *ts.Tree = @ptrCast(@alignCast(reused));
    const f: *ts.Tree = @ptrCast(@alignCast(fresh));
    const rs = try r.rootNode().toSexp(gpa);
    defer gpa.free(rs);
    const fs = try f.rootNode().toSexp(gpa);
    defer gpa.free(fs);
    try std.testing.expectEqualStrings(fs, rs);
    try std.testing.expect(!r.rootNode().hasError());
    // The places too: the test block's, past both edits.
    const at: u32 = @intCast(std.mem.indexOf(u8, text, "test").?);
    const rn = r.rootNode().descendantForByteRange(at, at + 4).?;
    const fn_ = f.rootNode().descendantForByteRange(at, at + 4).?;
    try std.testing.expectEqual(fn_.startPoint(), rn.startPoint());
    try std.testing.expectEqual(fn_.endPoint(), rn.endPoint());
    try std.testing.expectEqual(fn_.startByte(), rn.startByte());
}

test "syntax: a grammar handed in at run time colours and walks as the one compiled in" {
    if (comptime !minimal_grammars) return error.SkipZigTest;
    const gpa = std.testing.allocator;
    start(gpa);
    defer stop();
    const zig_lang = @extern(LanguageFn, .{ .name = "tree_sitter_zig" })();
    try std.testing.expect(addLanguage(.{ .name = "mine", .ext = ".mine", .ts = zig_lang, .highlights = ts_queries.zig_highlights }));
    // the same again is kept; told again with other queries, replaced
    try std.testing.expect(addLanguage(.{ .name = "mine", .ext = ".mine", .ts = zig_lang, .highlights = ts_queries.zig_highlights }));
    try std.testing.expect(supportsPath("x.mine"));
    const src = "const x = 1; // one\nfn f() void {}\n";
    const want = try highlightFileRange(gpa, "a.zig", src, 0, src.len);
    defer gpa.free(want);
    const got = try highlightFileRange(gpa, "a.mine", src, 0, src.len);
    defer gpa.free(got);
    try std.testing.expectEqualSlices(u8, want, got);
    const tree = parseTree("a.mine", src, null) orelse return error.NoTree;
    defer freeTree(tree);
    var spans: [4]Span = undefined;
    try std.testing.expect(walkNodes(tree, .expand_node, 6, 7, 6, &spans) > 0);
    forgetLanguages();
    try std.testing.expect(!supportsPath("x.mine"));
}

/// Each of `source`'s symbols as `mark qualified name`, in the walk's order.
fn symbolLines(gpa: std.mem.Allocator, path: []const u8, source: []const u8) ![]const u8 {
    var made = try context(gpa, path, source);
    defer made.deinit(gpa);
    var out: std.Io.Writer.Allocating = .init(gpa);
    defer out.deinit();
    for (made.symbols) |sym| {
        if (sym.kind == .scope) continue;
        try out.writer.print("{s} ", .{sym.kind.mark()});
        var chain: [8]u32 = undefined;
        var n: usize = 0;
        var up = sym.parent;
        while (up != 0 and n < chain.len) : (up = made.symbols[up - 1].parent) {
            chain[n] = up;
            n += 1;
        }
        while (n > 0) {
            n -= 1;
            const s = made.symbols[chain[n] - 1];
            try out.writer.print("{s}.", .{source[s.name_start..s.name_end]});
        }
        try out.writer.print("{s}\n", .{source[sym.name_start..sym.name_end]});
    }
    return out.toOwnedSlice();
}

test "syntax symbols: a Zig file's types, functions, fields and the rest by their declarations and values, each named in the containers it is in; a function's locals and an unnamed test none of them (UX DESIGN N2)" {
    if (comptime !minimal_grammars) return error.SkipZigTest;
    const gpa = std.testing.allocator;
    start(gpa);
    defer stop();
    const source =
        \\const std = @import("std");
        \\pub const Counts = struct {
        \\    lines: usize = 0,
        \\    pub const zero: Counts = .{};
        \\    pub fn add(c: *Counts) void {
        \\        const local = 1;
        \\        c.lines += local;
        \\    }
        \\};
        \\const Mode = enum { fast, slow };
        \\const Failure = error{ Late, Lost };
        \\const Self = @This();
        \\var hits: u32 = 0;
        \\fn List(comptime T: type) type {
        \\    return struct { items: []T };
        \\}
        \\test "count" {
        \\    const Local = struct {
        \\        fn helper() void {}
        \\    };
        \\    _ = Local;
        \\}
        \\test {}
        \\extern fn tick() void;
        \\
    ;
    // A test's name longer than a row's room is cut, its body still none.
    const xs: [250]u8 = @splat('x');
    const long = "test \"" ++ xs ++ "\" {\n    const Inner = struct {};\n    _ = Inner;\n}\n";
    const lines = try symbolLines(gpa, "a.zig", source ++ long);
    defer gpa.free(lines);
    try std.testing.expectEqualStrings(
        \\n std
        \\t Counts
        \\m Counts.lines
        \\c Counts.zero
        \\f Counts.add
        \\t Mode
        \\m Mode.fast
        \\m Mode.slow
        \\t Failure
        \\t Self
        \\v hits
        \\f List
        \\m List.items
        \\· "count"
        \\f tick
        \\
    ++ "· \"" ++ xs[0 .. max_name - 1].* ++ "\n", lines);
}

test "syntax symbols: C, C++, Rust, Go, Python and JavaScript by their kind tables, members named in their types, an impl's in its type, locals none" {
    if (!full_grammars) return error.SkipZigTest;
    const gpa = std.testing.allocator;
    start(gpa);
    defer stop();
    const cases = [_]struct { path: []const u8, source: []const u8, want: []const u8 }{
        .{ .path = "a.c", .source = "#define LIMIT 4\nstruct point { int x; int *y; };\ntypedef struct { int a; } pair;\nenum color { RED };\nstatic int counter = 0;\nconst int limit = 4;\nint add(int a) { int local = a; return local; }\nint later(void);\nstruct point p;\n", .want = "· LIMIT\nt point\nm point.x\nm point.y\nt pair\nm pair.a\nt color\nm color.RED\nv counter\nc limit\nf add\nf later\nv p\n" },
        .{ .path = "a.cc", .source = "namespace torque {\nclass Parser : public Base {\n public:\n  Parser();\n  int Parse(int depth) const { return depth; }\n  int depth_;\n};\nint Parser::Run(int n) { int local = n; return local; }\nusing Alias = int;\n}\nnamespace v8::internal {\nint flags;\n}\n", .want = "n torque\nt torque.Parser\nf torque.Parser.Parser\nf torque.Parser.Parse\nm torque.Parser.depth_\nf torque.Parser::Run\nt torque.Alias\nn v8::internal\nv v8::internal.flags\n" },
        .{ .path = "a.rs", .source = "mod m {\npub struct S { pub a: u32 }\nenum E { A, B(u32) }\ntrait T { fn f(&self); }\nimpl S { pub fn new() -> Self { let x = 1; S { a: x } } }\nconst C: u32 = 1;\nstatic G: u32 = 2;\nmacro_rules! mac { () => {} }\n}\n", .want = "n m\nt m.S\nm m.S.a\nt m.E\nm m.E.A\nm m.E.B\nt m.T\nf m.T.f\nf m.S.new\nc m.C\nv m.G\n· m.mac\n" },
        .{ .path = "a.go", .source = "package main\ntype S struct { A int }\ntype I interface { M() }\nconst C = 1\nvar V = 2\nfunc F() { var x = 1; _ = x }\nfunc (s *S) M() {}\n", .want = "t S\nm S.A\nt I\nf I.M\nc C\nv V\nf F\nf M\n" },
        .{ .path = "a.py", .source = "X = 1\nclass C:\n    attr = 2\n    def m(self):\n        y = 3\n        self.z = 4\ndef f():\n    pass\n", .want = "v X\nt C\nm C.attr\nf C.m\nf f\n" },
        .{ .path = "a.js", .source = "const A = 1;\nlet b = 2;\nfunction f() { const local = 1; }\nclass K { field = 1; m() {} }\nconst arrow = () => 1;\nconst Klass = class {};\nconst { x, y } = A;\n", .want = "c A\nv b\nf f\nt K\nm K.field\nf K.m\nf arrow\nt Klass\n" },
    };
    for (cases) |case| {
        const lines = try symbolLines(gpa, case.path, case.source);
        defer gpa.free(lines);
        std.testing.expectEqualStrings(case.want, lines) catch |err| {
            std.debug.print("in {s}\n", .{case.path});
            return err;
        };
    }
}

test "syntax symbols: every kind table names nodes of its grammar, and a grammar with none (JSON) lists no symbol" {
    if (!full_grammars) return error.SkipZigTest;
    const gpa = std.testing.allocator;
    start(gpa);
    defer stop();
    var tables: usize = 0;
    for (symbol_rules) |entry| {
        const spec = for (&specs) |*spec| {
            if (std.mem.eql(u8, spec.name, entry[0])) break spec;
        } else return error.NoGrammar;
        for (entry[1]) |rule| std.testing.expect(langOf(spec).idForNodeKind(rule.node, true) != 0) catch |err| {
            std.debug.print("{s} has no node {s}\n", .{ entry[0], rule.node });
            return err;
        };
        tables += 1;
    }
    try std.testing.expectEqual(@as(usize, 23), tables);
    var made = try context(gpa, "a.json", "{\"a\": 1}\n");
    defer made.deinit(gpa);
    try std.testing.expectEqual(@as(usize, 0), made.symbols.len);
}