tabnas-bnf 0.1.30

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

//! The emitter: `emit_grammar_spec` runs the rewrite passes and turns the
//! desugared grammar into a [`GrammarSpec`]. Mirrors the emit half of
//! `ts/src/compiler.ts`: token allocation, the contest context, the ref
//! registry, and the production, chain, tail-repeat and probe emitters.
//!
//! The emitter turns each alternative into one or more tabnas rule alts.
//! A "single-segment" alternative (at most one rule reference, trailing)
//! collapses to a single tabnas alt; any alternative with two or more ref
//! boundaries is chained through synthetic continuation rules named
//! `<prodname>$stepN`.
//!
//! Every alternate is written field by field in the order the canonical
//! compiler's object literal writes it, because the serialised text is
//! compared byte for byte against TypeScript's.

use std::cell::{Cell, RefCell};
use std::rc::Rc;

use indexmap::{IndexMap, IndexSet};
use serde_json::{json, Map, Value};

use crate::analysis::{
    alt_prefixes, alt_prefixes_raw, compute_first_sets, compute_follow_pairs, compute_follow_sets,
    dispatch_prefixes, first_of_alt, is_single_segment, resolve_suffix_debts, token_class_names,
    FirstSets, FollowPairs, FollowSets, Nullable, Tokens,
};
use crate::annotate::{plan_array_helpers, plan_value_annotations};
use crate::budget::{
    alt_units, memo_limit, probe_rule_units, rule_units, EmitBudget, Subject, STEP_ALTERNATES,
    STEP_REMOVE, STEP_TOKEN_CLASS, STEP_TOKEN_SET,
};
use crate::desugar::desugar;
use crate::factor::{left_factor, seq_token_span, LOOKAHEAD_K};
use crate::ir::{
    self, builtin_token, check_element_depth, diag_name, escape_regexp,
    is_effectively_case_sensitive, regex_key, set_diag_name, term_key_of, ConvertOptions, Element,
    EmitError, Kind, NodeKind, SrcSpan, ValueAnnotation,
};
use crate::leftrec::eliminate_left_recursion_keeping;
use crate::leftrec::rewrite_tail_repeats;
use crate::probe::rewrite_probe_dispatches;
use crate::prose::{
    lift_literal_tokens, normalize_builtin_tokens, nullable_rules, resolve_prose_terminals,
    validate_repetitions,
};
use crate::ranges::{
    char_ranges_overlap, class_analysis, class_pattern, code_unit_reach, fold_case_ranges,
    normalize_ranges, pattern_char_ranges, CharRange,
};
use crate::shared::{origin_of, AsElement, Grammar, Production, Sequence};
use crate::spec::{AltSpec, GrammarSpec, RefAction, RuleSpec};

/// A match-token matcher as the engine's wire format carries it:
/// `@~/source/flags` when eager, `@/source/flags` otherwise.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct MatchToken {
    pub source: String,
    pub flags: String,
    pub eager: bool,
}

impl MatchToken {
    pub fn serialized(&self) -> String {
        let sentinel = if self.eager { "@~/" } else { "@/" };
        format!("{}{}/{}", sentinel, self.source, self.flags)
    }
}

/// The counter a repeat loop keeps in the rule's `n` bag, to tell the
/// iteration that enters the loop from the ones that come back to it (see
/// `emit_repeat_loop`). Only the entering one allocates the node every
/// iteration accumulates into; one that allocated again would discard
/// what the iterations before it matched. The loop cannot tell by its
/// name, which is the same every time, so it counts: 0 (or unset, which
/// every engine reads as 0) on the way in, 1 once it has entered.
///
/// `n` because it has to survive a replace, which `u` does not, and
/// because a counter that was never set reads as 0 in every engine, so
/// the entering iteration needs nothing from whoever pushed the loop (an
/// unset `k` is absent, which only `$exist` or an operator that fails
/// open can match). `n` also reaches every rule the loop pushes, so the
/// push of an item clears it: a loop reached from inside an item enters
/// afresh. One name serves every loop for the same reason: a counter at 1
/// never reaches a rule the loop did not replace itself with. Debt
/// counters are `debt_…` (`fresh_debt_counter`), so none can be this one.
const LOOP_COUNTER: &str = "rep";

/// Where an entry goes once it matches: the rule it pushes, or, for a
/// repeat loop's continue alternative, the rule it hands over to by
/// replacement. Two entries going to the same place are the same
/// decision, whichever way they get there.
fn descent_of(o: &AltSpec) -> Option<&str> {
    o.p().or_else(|| o.r())
}

/// The recovery sync group appended to a tag: `<tag>,<group>`. Only a
/// CLOSE alternate that names a token can be a sync point, and this
/// emitter produces exactly two: the start wrapper's `#ZZ` (`end`) and a
/// tail repeat's separator continuation (`comma`). Tag all of them or
/// none: one tagged alternate anywhere switches the engine's fallback
/// off for every rule below it.
fn sync_g(tag: &str, group: &str) -> String {
    format!("{tag},{group}")
}

/// Whether a pattern has top-level alternation, in which case anchoring
/// it needs a non-capturing group: `^a|bc` anchors only the first branch.
fn has_top_level_alternation(pattern: &str) -> bool {
    let chars: Vec<char> = pattern.chars().collect();
    let mut in_class = false;
    let mut depth = 0usize;
    let mut i = 0;
    while i < chars.len() {
        let c = chars[i];
        if c == '\\' {
            i += 2;
            continue;
        }
        if in_class {
            if c == ']' {
                in_class = false;
            }
        } else if c == '[' {
            in_class = true;
        } else if c == '(' {
            depth += 1;
        } else if c == ')' {
            depth = depth.saturating_sub(1);
        } else if c == '|' && depth == 0 {
            return true;
        }
        i += 1;
    }
    false
}

fn anchorable(pattern: &str) -> String {
    if has_top_level_alternation(pattern) {
        format!("(?:{pattern})")
    } else {
        pattern.to_string()
    }
}

/// The pattern as a JavaScript `RegExp.source` reads it: an unescaped `/`
/// outside a character class becomes `\/`, and every line terminator is
/// written as its escape. The serialized token strings match the
/// canonical compiler's byte for byte, and the engine's `@/…/flags`
/// reader splits on the last slash, which this keeps unambiguous.
fn js_regex_source(pattern: &str) -> String {
    let mut out = String::with_capacity(pattern.len());
    let mut in_class = false;
    let mut chars = pattern.chars().peekable();
    while let Some(c) = chars.next() {
        match c {
            '\\' => {
                out.push('\\');
                if let Some(next) = chars.next() {
                    match next {
                        '\n' => out.push_str("\\n"),
                        '\r' => out.push_str("\\r"),
                        '\u{2028}' => out.push_str("\\u2028"),
                        '\u{2029}' => out.push_str("\\u2029"),
                        other => out.push(other),
                    }
                }
            }
            '[' => {
                in_class = true;
                out.push(c);
            }
            ']' => {
                in_class = false;
                out.push(c);
            }
            '/' if !in_class => out.push_str("\\/"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\u{2028}' => out.push_str("\\u2028"),
            '\u{2029}' => out.push_str("\\u2029"),
            other => out.push(other),
        }
    }
    out
}

/// Token names the engine's own matchers own. A lifted literal that would
/// land on one must be renamed instead: the engine refuses a fixed-token
/// entry under a matcher-owned name.
pub(crate) fn is_engine_owned_token(name: &str) -> bool {
    builtin_token(name.trim_start_matches('#')).is_some()
        || matches!(name, "#BD" | "#ZZ" | "#UK" | "#AA" | "#SP" | "#LN" | "#CM")
}

/// Allocate a token name for a literal: the preferred (lifted) name when
/// free, else the literal reduced to `[A-Za-z0-9]` with underscores and
/// upper-cased (`#T` when nothing is left), numbered on collision. An
/// astral character reduces to two underscores, as it does in the
/// canonical compiler, which counts UTF-16 units.
fn alloc_token_name(literal: &str, used: &mut IndexSet<String>, preferred: Option<&str>) -> String {
    // Not a name holding whitespace: an alternate's `s` separates token
    // names with it, so `#P L` would read as two tokens there, and the
    // literal takes the name its text gives it instead. Whitespace as every
    // runtime reads it (`is_name_space`). Mirrors the TS `allocTokenName`.
    let preferred = preferred.filter(|p| !p.chars().any(crate::analysis::is_name_space));
    if let Some(preferred) = preferred {
        let want = format!("#{preferred}");
        if !used.contains(&want) && !is_engine_owned_token(&want) {
            used.insert(want.clone());
            return want;
        }
    }
    let mut base = String::new();
    for c in literal.chars() {
        if c.is_ascii_alphanumeric() {
            base.push(c.to_ascii_uppercase());
        } else if (c as u32) > 0xFFFF {
            base.push_str("__");
        } else {
            base.push('_');
        }
    }
    let base = base.trim_matches('_');
    let candidate = if base.is_empty() {
        "#T".to_string()
    } else {
        format!("#{base}")
    };
    if !used.contains(&candidate) && !is_engine_owned_token(&candidate) {
        used.insert(candidate.clone());
        return candidate;
    }
    let mut i = 1;
    while used.contains(&format!("{candidate}{i}")) {
        i += 1;
    }
    let chosen = format!("{candidate}{i}");
    used.insert(chosen.clone());
    chosen
}

fn ends_with_word_char(s: &str) -> bool {
    s.chars()
        .last()
        .is_some_and(|c| c.is_ascii_alphanumeric() || c == '_')
}

/// Answers "can these two tokens claim the same input character?", with
/// memoisation on the token and on the PAIR. The contest checks are
/// quadratic in dispatch entries while the distinct token pairs behind
/// them are few.
struct ContestCtx {
    fixed_tokens: IndexMap<String, Option<String>>,
    match_tokens: IndexMap<String, MatchToken>,
    /// The coverage of a class that became a token SET over atoms, so it
    /// appears in neither token table.
    set_ranges: IndexMap<String, Vec<CharRange>>,
    /// The token classes of `ConvertOptions::token_classes`: production
    /// to its set, and set to its member tokens.
    class_sets: IndexMap<String, String>,
    class_members: IndexMap<String, Vec<String>>,
    /// Every token set the emitted spec declares (class-partition sets and
    /// token classes alike), for the heads predicate.
    token_sets: IndexMap<String, Vec<String>>,
    /// Token name to the literal it was allocated for and whether it is
    /// case-sensitive, for the heads predicate's prefix test.
    literal_by_token: IndexMap<String, (String, bool)>,
    word_keywords: bool,
    range_cache: RefCell<IndexMap<String, Option<Vec<CharRange>>>>,
    overlap_cache: RefCell<IndexMap<String, bool>>,
    contest_cache: RefCell<IndexMap<String, bool>>,
}

impl ContestCtx {
    /// Character coverage per token, or `None` when unknown (and the
    /// guard emission stays conservative). A fixed token covers its
    /// literal's first code point; a match token covers whatever its
    /// leading character class covers, both cases of every ASCII letter
    /// when it is case-insensitive.
    fn token_ranges_of(&self, tok: &str) -> Option<Vec<CharRange>> {
        if let Some(hit) = self.range_cache.borrow().get(tok) {
            return hit.clone();
        }
        let ranges: Option<Vec<CharRange>> = if let Some(spanned) = self.set_ranges.get(tok) {
            Some(normalize_ranges(spanned))
        } else {
            let mut r: Option<Vec<CharRange>> = None;
            if let Some(Some(lit)) = self.fixed_tokens.get(tok) {
                if let Some(c) = lit.chars().next() {
                    r = Some(code_unit_reach(&[(c as u32, c as u32)], ""));
                }
            } else if let Some(re) = self.match_tokens.get(tok) {
                // Strip the emitter's own `^` anchor (and grouping) so the
                // parser sees the pattern as written.
                let mut src = re
                    .source
                    .strip_prefix('^')
                    .unwrap_or(&re.source)
                    .to_string();
                if let Some(inner) = src.strip_prefix("(?:").and_then(|s| s.strip_suffix(')')) {
                    src = inner.to_string();
                }
                r = pattern_char_ranges(&src, &re.flags);
                if let Some(rr) = &r {
                    if re.flags.contains('i') {
                        r = Some(fold_case_ranges(rr));
                    }
                }
                r = r.map(|rr| code_unit_reach(&rr, &re.flags));
            }
            r.map(|r| normalize_ranges(&r))
        };
        self.range_cache
            .borrow_mut()
            .insert(tok.to_string(), ranges.clone());
        ranges
    }

    fn tokens_overlap(&self, a: &str, b: &str) -> bool {
        let key = if a < b {
            format!("{a}\0{b}")
        } else {
            format!("{b}\0{a}")
        };
        if let Some(hit) = self.overlap_cache.borrow().get(&key) {
            return *hit;
        }
        // Kept only while the memo has room (`MAX_MEMO_ENTRIES`).
        let keep = self.overlap_cache.borrow().len() < memo_limit();
        let ma = self.class_members.get(a);
        let mb = self.class_members.get(b);
        let out = if ma.is_some() || mb.is_some() {
            // A token class meets what any member meets, the same token
            // included; coverage alone would miss an engine token in it.
            // `token_class_names` keeps a set out of every set's members;
            // were one to get in, this provisional answer, the
            // conservative one, is what ends the expansion when it comes
            // back to the same pair.
            self.overlap_cache.borrow_mut().insert(key.clone(), true);
            let xs: Vec<String> = ma.cloned().unwrap_or_else(|| vec![a.to_string()]);
            let ys: Vec<String> = mb.cloned().unwrap_or_else(|| vec![b.to_string()]);
            xs.iter()
                .any(|x| ys.iter().any(|y| x == y || self.tokens_overlap(x, y)))
        } else {
            let ra = self.token_ranges_of(a);
            let rb = self.token_ranges_of(b);
            match (ra, rb) {
                (Some(ra), Some(rb)) => char_ranges_overlap(&ra, &rb),
                _ => false,
            }
        };
        // A provisional answer that is not kept goes again.
        if keep {
            self.overlap_cache.borrow_mut().insert(key, out);
        } else {
            self.overlap_cache.borrow_mut().shift_remove(&key);
        }
        out
    }

    /// Can the lexer hand the same input to two dispatch heads, so that a
    /// choice between them on one token is no choice? The same token can;
    /// a literal can meet a literal it is a prefix of, or that is a prefix
    /// of it, case-folded when either is insensitive, except two
    /// whole-word keywords under `word_keywords`, whose boundary guard
    /// keeps `option` off `optional`; a token set meets whatever one of
    /// its members meets; a character class, or an atom of one, meets what
    /// its coverage overlaps; an engine token meets itself and what its
    /// matcher can take when the parser asks (`engine_token_meets`). Narrower than `tokens_overlap` on purpose: that is the
    /// lexer's question, whether two heads can claim one CHARACTER.
    /// Mirrors the TypeScript `headsContest`.
    fn heads_contest(&self, a: &str, b: &str) -> bool {
        if a == b {
            return true;
        }
        // The engine's ANY token takes every token, so it meets every head.
        if a == "#AA" || b == "#AA" {
            return true;
        }
        let key = if a < b {
            format!("{a}\0{b}")
        } else {
            format!("{b}\0{a}")
        };
        if let Some(hit) = self.contest_cache.borrow().get(&key) {
            return *hit;
        }
        // Kept only while the memo has room (`MAX_MEMO_ENTRIES`).
        let keep = self.contest_cache.borrow().len() < memo_limit();
        let ma = self.token_sets.get(a.trim_start_matches('#'));
        let mb = self.token_sets.get(b.trim_start_matches('#'));
        let la = self.literal_by_token.get(a);
        let lb = self.literal_by_token.get(b);
        let out = if ma.is_some() || mb.is_some() {
            // A set meets what any member meets. The members are never
            // sets (`token_class_names`), and the provisional answer, the
            // conservative one, would end the expansion if one were.
            self.contest_cache.borrow_mut().insert(key.clone(), true);
            let xs: Vec<String> = ma.cloned().unwrap_or_else(|| vec![a.to_string()]);
            let ys: Vec<String> = mb.cloned().unwrap_or_else(|| vec![b.to_string()]);
            xs.iter()
                .any(|x| ys.iter().any(|y| self.heads_contest(x, y)))
        } else if let (Some((la, sa)), Some((lb, sb))) = (la, lb) {
            let (short, long) = if la.chars().count() <= lb.chars().count() {
                (la, lb)
            } else {
                (lb, la)
            };
            let is_prefix = if *sa && *sb {
                long.starts_with(short.as_str())
            } else {
                folded_prefix(short, long)
            };
            // Two whole-word keywords under `word_keywords`: the shorter's
            // boundary guard refuses the longer wherever the longer goes
            // on with a word character (`option` off `optional`), and
            // admits it wherever it goes on with anything else (`a` on
            // `a-b`).
            is_prefix
                && !(self.is_word_literal(la) && self.is_word_literal(lb) && {
                    let lr: Vec<char> = long.chars().collect();
                    let n = short.chars().count();
                    n < lr.len() && is_word_char(lr[n])
                })
        } else {
            // A character class, or an atom of one, against anything: by
            // coverage, when the coverage is exact. An engine token has no
            // coverage of its own, and meets what its matcher can take
            // (`engine_token_meets`).
            !self.regex_head_is_exact(a)
                || !self.regex_head_is_exact(b)
                || self.tokens_overlap(a, b)
                || self.engine_token_meets(a, b)
                || self.engine_token_meets(b, a)
        };
        // A provisional answer that is not kept goes again.
        if keep {
            self.contest_cache.borrow_mut().insert(key, out);
        } else {
            self.contest_cache.borrow_mut().shift_remove(&key);
        }
        out
    }

    /// Three of the engine's own matchers can take text another head
    /// claims, and under negotiated lexing the parser asks them to:
    /// `relex` runs only the matchers that can produce the token an
    /// alternative wants. The number matcher takes a leading digit, sign
    /// or point, the string matcher a leading quote, and the text matcher
    /// any text that no fixed token claims, a number's or a string's
    /// included; a fixed literal it defers to. Measured against the
    /// four-token dispatch this replaced, these are exactly the pairs it
    /// kept apart that a one-token dispatch would not. `#VL` is not among
    /// them: an emitted grammar lexes no values, so nothing is ever cut as
    /// one. Mirrors the TypeScript `engineTokenMeets`.
    fn engine_token_meets(&self, eng: &str, other: &str) -> bool {
        const NUMBER_START: [CharRange; 3] = [(0x2B, 0x2B), (0x2D, 0x2E), (0x30, 0x39)];
        const QUOTE_START: [CharRange; 3] = [(0x22, 0x22), (0x27, 0x27), (0x60, 0x60)];
        let starts: &[CharRange] = match eng {
            "#TX" => {
                return other == "#NR" || other == "#ST" || self.match_tokens.contains_key(other);
            }
            "#NR" => &NUMBER_START,
            "#ST" => &QUOTE_START,
            _ => return false,
        };
        self.token_ranges_of(other)
            .is_some_and(|r| char_ranges_overlap(starts, &r))
    }

    fn is_word_literal(&self, lit: &str) -> bool {
        self.word_keywords && ends_with_word_char(lit)
    }

    /// Whether a regex-backed head's first character can be read off its
    /// pattern: one atom or one class, alone or repeated with `+`, whose
    /// coverage `pattern_char_ranges` can name. Anything else (`a|b`
    /// begins with b too, `a?b` with b, `.` with anything, `\d` with a
    /// digit and `\n` with a character `pattern_char_ranges` declines to
    /// name) may meet any head, and the dispatcher must treat it so.
    /// Mirrors the TypeScript `regexHeadIsExact`.
    fn regex_head_is_exact(&self, tok: &str) -> bool {
        let Some(re) = self.match_tokens.get(tok) else {
            return true;
        };
        // A case-insensitive matcher folds case, and the coverage is
        // folded for ASCII only (`fold_case_ranges`): a head that reaches
        // beyond ASCII meets whatever Unicode folding lets it (`(?i)[Σ]`
        // takes `Ï‚`), which the coverage does not say. That holds for a
        // case-insensitive literal as much as for a pattern.
        if re.flags.contains('i') {
            match self.token_ranges_of(tok) {
                Some(r) if r.iter().all(|(_, hi)| *hi <= 0x7F) => {}
                _ => return false,
            }
        }
        // A literal, fixed or guarded (`^option\b`), covers its first
        // character exactly whatever follows it in the matcher.
        if self.literal_by_token.contains_key(tok) {
            return true;
        }
        let mut src = re
            .source
            .strip_prefix('^')
            .unwrap_or(&re.source)
            .to_string();
        if let Some(inner) = src.strip_prefix("(?:").and_then(|s| s.strip_suffix(')')) {
            src = inner.to_string();
        }
        let Some(end) = crate::ranges::regex_head_atom_end(&src) else {
            return false;
        };
        // `\u{61}` is the code point `a` only under the `u` or `v` flag;
        // without either it is `u` repeated 61 times, which is not what
        // `pattern_char_ranges` reads it as.
        let head: String = src.chars().take(end).collect();
        if !re.flags.contains('u') && !re.flags.contains('v') && head.contains("\\u{") {
            return false;
        }
        let rest: String = src.chars().skip(end).collect();
        (rest.is_empty() || rest == "+") && self.token_ranges_of(tok).is_some()
    }

    /// What a literal head covers: a literal its first character; a token
    /// class's set what its literal members cover, since an engine token
    /// among them (`#TX`) meets no character class here, as it would not
    /// as a head of its own. Mirrors the TypeScript `literalHeadRangesOf`.
    fn literal_head_ranges_of(&self, tok: &str) -> Option<Vec<CharRange>> {
        let Some(members) = self.class_members.get(tok) else {
            return self.token_ranges_of(tok);
        };
        let mut out: Option<Vec<CharRange>> = None;
        for m in members {
            if let Some(r) = self.token_ranges_of(m) {
                out.get_or_insert_with(Vec::new).extend(r);
            }
        }
        out
    }
}

/// Whether one case-insensitive literal is a prefix of the other under
/// the matcher's own folding. Lowercase alone is not that relation:
/// `(?i)Σ` takes `ς` and `(?i)ς` takes `Σ`, while lowercase maps `Σ` to
/// `σ` and leaves `ς` alone. Folding both ways over-approximates the
/// matcher (a contest declared where the matcher would not meet) and
/// never under-approximates it, which is the safe direction here.
fn folded_prefix(short: &str, long: &str) -> bool {
    long.to_lowercase().starts_with(&short.to_lowercase())
        || long.to_uppercase().starts_with(&short.to_uppercase())
}

fn is_word_char(c: char) -> bool {
    c == '_' || c.is_ascii_alphanumeric()
}

/// Allocates unique `@`-prefixed ref names for the tree-building and
/// probe-control actions in closure mode, or emits engine `$`-builtin
/// refs plus `k` config in builtins mode. Each emitter writes `a` (and
/// `k`) onto the alternate exactly where the canonical compiler's
/// `Object.assign` or spread would.
struct RefRegistry {
    refs: IndexMap<String, RefAction>,
    counter: usize,
    use_builtins: bool,
    emit_marks: bool,
}

impl RefRegistry {
    fn register(&mut self, action: RefAction) -> String {
        let name = format!("@bnf_a{}", self.counter);
        self.counter += 1;
        self.refs.insert(name.clone(), action);
        name
    }

    fn node(&mut self, alt: &mut AltSpec, init: bool, rule: &str, kind: NodeKind, nterms: usize) {
        if self.use_builtins {
            alt.set("a", "@node$");
            alt.set(
                "k",
                json!({"node$": {"init": init, "rule": rule, "kind": kind.as_str(), "nterms": nterms}}),
            );
        } else {
            let name = self.register(RefAction::Node {
                init,
                rule: rule.to_string(),
                kind,
                nterms,
            });
            alt.set("a", name);
        }
    }

    fn capture(&mut self, alt: &mut AltSpec, rule: &str, kind: NodeKind) {
        if self.use_builtins {
            alt.set("a", "@capture$");
            alt.set(
                "k",
                json!({"capture$": {"rule": rule, "kind": kind.as_str()}}),
            );
        } else {
            let name = self.register(RefAction::Capture {
                rule: rule.to_string(),
                kind,
            });
            alt.set("a", name);
        }
    }

    fn bubble(&mut self, alt: &mut AltSpec) {
        if self.use_builtins {
            alt.set("a", "@bubble$");
        } else {
            let name = self.register(RefAction::Bubble);
            alt.set("a", name);
        }
    }

    fn fold(&mut self, alt: &mut AltSpec, c_n: Option<usize>) {
        if self.use_builtins {
            alt.set("a", "@fold$");
            let cfg = match c_n {
                Some(n) => json!({"cN": n}),
                None => json!({}),
            };
            alt.set("k", json!({"fold$": cfg}));
        } else {
            let name = self.register(RefAction::Fold {
                c_n: c_n.unwrap_or(0),
            });
            alt.set("a", name);
        }
    }
}

/// A run of terminal tokens followed by at most one rule reference.
#[derive(Debug, Clone, Default)]
struct Segment {
    terms: Vec<String>,
    reference: Option<String>,
    /// Counter mutations the pushing alt carries, from the reference's
    /// suffix-debt annotation.
    debt: Option<IndexMap<String, i64>>,
}

/// One emitted open alternate together with the IR alternative it came
/// from (`None` for a synthesised guard or a FOLLOW re-issue).
#[derive(Debug, Clone)]
struct Entry {
    o: AltSpec,
    alt: Option<Sequence>,
}

/// An alternate placed by the keyword-shadow reordering: an entry, or a
/// guard synthesised from one. The two are treated alike from here on.
struct Placed {
    o: AltSpec,
    rank: f64,
    seq: usize,
}

struct Emitter<'a> {
    grammar: &'a Grammar,
    tag: String,
    tokens: Tokens,
    known_rules: IndexSet<String>,
    first_sets: FirstSets,
    nullable: Nullable,
    follow_sets: FollowSets,
    follow_pairs: FollowPairs,
    contest: ContestCtx,
    refs: RefRegistry,
    value_plan: IndexMap<String, Vec<bool>>,
    array_helpers: IndexSet<String>,
    value_rules: IndexSet<String>,
    prov: Option<IndexMap<String, String>>,
    rule_spec: IndexMap<String, Option<RuleSpec>>,
    /// The token names a literal head can be: every literal's token and
    /// every token class's set. Collected once, when the token tables are
    /// complete: rebuilt for every production, as it was, it made the
    /// keyword-shadow ordering quadratic in the size of the grammar.
    literal_heads: IndexSet<String>,
    /// The token names a character class can be, collected once likewise.
    class_heads: IndexSet<String>,
    /// What this compile writes, against `MAX_EMIT_UNITS`.
    budget: EmitBudget,
    /// What the alternates of the rule `emit_production` is building have
    /// been charged as they were made; its commit charges the rest.
    pre: Cell<usize>,
}

/// Compile a grammar IR into a tabnas `GrammarSpec`.
///
/// The grammar is not modified: every pass works on a copy. Diagnostics
/// are prefixed with `opts.tag` (default `bnf`), the notation the grammar
/// was written in.
pub fn emit_grammar_spec(
    grammar: &ir::Grammar,
    opts: &ConvertOptions,
) -> Result<GrammarSpec, EmitError> {
    // Diagnostics name the notation the grammar was written in, not this
    // package. Set BEFORE any pass that can raise one.
    let tag = opts.tag.clone().unwrap_or_else(|| "bnf".to_string());
    set_diag_name(&tag);

    // What this compile writes, against `MAX_EMIT_UNITS`.
    let budget = EmitBudget::new();

    // Before the grammar is even copied: copying it recurses through the
    // element tree too, so the shape has to be refused first.
    check_element_depth(grammar)?;

    // The working copy every pass below rebuilds, its elements shared
    // between the sequences that hold them (see `crate::shared`).
    let mut grammar = Grammar::from_ir(grammar);

    // Before ANY rewrite: annotations describe the grammar the AUTHOR
    // wrote, and the passes below are what make that shape unrecoverable.
    let plan = plan_value_annotations(&grammar)?;

    // Drop informational prose definitions first, so the names they
    // document fall through to the built-in tokens, and so a leading
    // prose line is never mistaken for the start rule.
    resolve_prose_terminals(&mut grammar)?;

    // Capture the `<remove>` directives before the rewrite passes: each
    // returns a fresh grammar carrying only productions.
    let remove_names = grammar.remove.clone();
    let clear_all = grammar.clear_all;

    let start = match &opts.start {
        Some(s) => s.clone(),
        None => match grammar.productions.first() {
            Some(p) => p.name.clone(),
            None => {
                return Err(EmitError::new(format!(
                    "{}: grammar has no productions to start from (a removal-only grammar \
                     needs an explicit start rule)",
                    diag_name()
                )))
            }
        },
    };
    let word_keywords = opts.word_keywords;

    // Whether the empty input is in the language, decided HERE because
    // the engine short-circuits `''` before the parse loop starts.
    // Computed on the grammar as written.
    let accepts_empty = nullable_rules(&grammar.productions).contains(&start);

    // Turn single-literal productions into named lexer tokens, then
    // resolve bare built-in token names to token terminals, both before
    // any structural pass sees them as rule references.
    let lifted_literals = lift_literal_tokens(&mut grammar, &start);
    normalize_builtin_tokens(&mut grammar);

    // The token classes, read before any rewrite: elimination would
    // otherwise inline each one into every rule it leads, which is the
    // multiplier the option exists to remove.
    let class_names: IndexSet<String> = if opts.token_classes {
        token_class_names(&grammar)
    } else {
        IndexSet::new()
    };

    // Each rewrite returns a new grammar and leaves the one it read alone.
    // That one is dropped as soon as the next exists: a binding shadowed
    // by the next pass's would live to the end of the function, and the
    // sequences would be held once per pass rather than twice at most.
    let eliminated = eliminate_left_recursion_keeping(&grammar, &class_names)?;
    drop(grammar);
    eliminated.validate_repetitions()?;
    let grammar = eliminated.into_grammar();
    let next = rewrite_probe_dispatches(&grammar, &budget)?;
    drop(grammar);
    // Left factoring runs after the probe rewriter and before
    // tail-repeat detection and desugaring.
    let grammar = left_factor(&next)?;
    drop(next);
    let grammar = rewrite_tail_repeats(grammar, &start);
    validate_repetitions(&grammar)?;
    let next = desugar(&grammar);
    drop(grammar);
    let mut grammar = next;

    // Both are named AFTER desugar, because both are keyed by the rule
    // names the emitter will actually see.
    let array_helpers = plan_array_helpers(&grammar, &plan.collect);
    let value_rules: IndexSet<String> = grammar
        .productions
        .iter()
        .filter(|p| p.value.is_some())
        .map(|p| p.name.clone())
        .collect();

    // Allocate a fixed token for each unique literal, and a match token
    // for each unique regex terminal.
    let mut tokens = Tokens::default();
    let mut used_names: IndexSet<String> = IndexSet::new();
    // The token classes take their names first (`#ident` for the class
    // `ident`): the substitution pass has already written token elements
    // under those names, so nothing allocated below may take one. The
    // members are filled in once the tokens they are exist.
    let mut class_set_names: IndexMap<String, String> = IndexMap::new();
    for prod in &grammar.productions {
        if class_names.contains(&prod.name) {
            let name = alloc_token_name(&prod.name, &mut used_names, Some(&prod.name));
            class_set_names.insert(prod.name.clone(), name);
        }
    }
    let mut fixed_tokens: IndexMap<String, Option<String>> = IndexMap::new();
    let mut match_tokens: IndexMap<String, MatchToken> = IndexMap::new();
    let mut token_sets: IndexMap<String, Vec<String>> = IndexMap::new();
    let mut set_ranges: IndexMap<String, Vec<CharRange>> = IndexMap::new();

    // Gather every terminal first. Probe helpers store their vocab as
    // elements rather than in `alts`, and a tail repeat's separator is
    // stashed off `alts` too, so walk those as well. The lifted literals
    // are seeded up front: their productions no longer exist. Walked
    // where they stand, three times, rather than gathered: the sequences
    // hold an element per occurrence, and a grammar whose substitutions
    // repeat a sequence in every rule it leads holds the square of its
    // size in occurrences.
    let terminals = || {
        lifted_literals
            .iter()
            .chain(grammar.productions.iter().flat_map(|prod| {
                prod.alts
                    .iter()
                    .flatten()
                    .map(|el| &**el)
                    .chain(prod.probe_helper.iter().flat_map(|ph| &ph.vocab_elements))
                    .chain(prod.tail_repeat.iter().flat_map(|tr| &tr.sep))
            }))
    };

    // Which character classes contest a position with another, and the
    // shared partition they are laid over: computed before anything is
    // allocated.
    let mut classes = class_analysis(terminals());

    // Terminals carrying a lifted production name are allocated first,
    // so the name wins even when the same literal also appears inline in
    // an earlier rule.
    let named = terminals().filter(|el| {
        matches!(
            &el.kind,
            Kind::Term {
                token_name: Some(_),
                ..
            }
        )
    });
    for el in named.chain(terminals()) {
        match &el.kind {
            Kind::Term {
                literal,
                case_sensitive,
                token_name,
            } => {
                let key = term_key_of(el);
                if !tokens.literals.contains_key(&key) {
                    let name = alloc_token_name(literal, &mut used_names, token_name.as_deref());
                    tokens.literals.insert(key, name.clone());
                    emit_literal_token(
                        literal,
                        *case_sensitive,
                        &name,
                        &mut fixed_tokens,
                        &mut match_tokens,
                        word_keywords,
                    )?;
                }
            }
            Kind::Regex { pattern, flags } => {
                let key = regex_key(pattern, flags);
                if !tokens.regex_tokens.contains_key(&key) {
                    // Allocated HERE, in terminal order, rather than in a
                    // pass of their own: allocation order is tin order,
                    // and tin order is what the lexer walks when it picks
                    // between the matchers a slot expects.
                    emit_class_token(
                        pattern,
                        flags,
                        &key,
                        &mut classes,
                        &mut tokens,
                        &mut token_sets,
                        &mut set_ranges,
                        &mut match_tokens,
                        &mut used_names,
                        el.sp,
                        &budget,
                    )?;
                }
            }
            _ => {}
        }
    }

    let known_rules: IndexSet<String> =
        grammar.productions.iter().map(|p| p.name.clone()).collect();

    let mut contest = ContestCtx {
        fixed_tokens: fixed_tokens.clone(),
        match_tokens: match_tokens.clone(),
        set_ranges,
        class_sets: IndexMap::new(),
        class_members: IndexMap::new(),
        token_sets: IndexMap::new(),
        literal_by_token: IndexMap::new(),
        word_keywords,
        range_cache: RefCell::new(IndexMap::new()),
        overlap_cache: RefCell::new(IndexMap::new()),
        contest_cache: RefCell::new(IndexMap::new()),
    };
    for (key, name) in &tokens.literals {
        contest
            .literal_by_token
            .insert(name.clone(), (key[3..].to_string(), key.starts_with("cs:")));
    }

    // The token classes as engine token sets (`ConvertOptions::token_classes`):
    // one set per class, under the name allocated above, holding the
    // tokens its alternatives are. Filled after the tokens, since the
    // members must exist, and before FIRST, whose sets name them.
    for prod in &grammar.productions {
        let Some(name) = class_set_names.get(&prod.name).cloned() else {
            continue;
        };
        let mut members: Vec<String> = Vec::new();
        budget.begin_rule(origin_of(prod), prod.sp, &STEP_TOKEN_CLASS);
        for alt in &prod.alts {
            let tok = tokens.name(&alt[0]);
            if !members.contains(&tok) {
                budget.charge(1)?;
                members.push(tok);
            }
        }
        token_sets.insert(name.trim_start_matches('#').to_string(), members.clone());
        contest.class_sets.insert(prod.name.clone(), name.clone());
        // The class covers what its members cover, when that is known for
        // every member; an engine token among them (`#TX`) leaves it
        // unknown, as it is for that token alone.
        let mut covered: Vec<CharRange> = Vec::new();
        let mut known = true;
        for m in &members {
            match contest.token_ranges_of(m) {
                Some(r) => covered.extend(r),
                None => {
                    known = false;
                    break;
                }
            }
        }
        if known {
            contest.set_ranges.insert(name.clone(), covered);
        }
        contest.class_members.insert(name, members);
    }
    contest.token_sets = token_sets.clone();

    let (first_sets, nullable) =
        compute_first_sets(&grammar, &tokens, &contest.class_sets, &budget)?;
    let follow_sets =
        compute_follow_sets(&grammar, &tokens, &first_sets, &nullable, &start, &budget)?;
    let follow_pairs = compute_follow_pairs(
        &grammar,
        &tokens,
        &first_sets,
        &nullable,
        &follow_sets,
        &budget,
    )?;

    // Settle the contested left-recursion tail loops flagged during
    // elimination, now that FIRST sets can say whether the competition
    // is real. Only annotates; nothing computed above depends on it.
    resolve_suffix_debts(&mut grammar, &tokens, &first_sets, &nullable, &|a, b| {
        contest.tokens_overlap(a, b)
    });

    let refs = RefRegistry {
        refs: IndexMap::new(),
        counter: 0,
        use_builtins: opts.builtins,
        emit_marks: opts.marks,
    };

    // Nothing allocates a token from here on, so the head sets are final.
    let literal_heads: IndexSet<String> = tokens
        .literals
        .values()
        .chain(contest.class_sets.values())
        .cloned()
        .collect();
    let class_heads: IndexSet<String> = tokens.regex_tokens.values().cloned().collect();

    let mut emitter = Emitter {
        grammar: &grammar,
        tag: tag.clone(),
        tokens,
        known_rules,
        first_sets,
        nullable,
        follow_sets,
        follow_pairs,
        contest,
        refs,
        value_plan: plan.plan,
        array_helpers,
        value_rules,
        prov: if opts.provenance {
            Some(IndexMap::new())
        } else {
            None
        },
        rule_spec: IndexMap::new(),
        literal_heads,
        class_heads,
        budget,
        pre: Cell::new(0),
    };

    let grammar_ref: &Grammar = emitter.grammar;
    for prod in &grammar_ref.productions {
        // Productions synthesised by the rewrite passes are emitted under
        // their own names; record where each came from.
        if origin_of(prod) != prod.name {
            emitter.record_prov(&prod.name, origin_of(prod));
        }
        // A refusal names the rule the author wrote.
        emitter
            .budget
            .begin_rule(origin_of(prod), prod.sp, &STEP_ALTERNATES);
        if prod.probe_helper.is_some() {
            emitter.emit_probe_helper(prod)?;
            continue;
        }
        if prod.probe_dispatch.is_some() {
            emitter.emit_probe_dispatch(prod)?;
            continue;
        }
        emitter.emit_production(prod)?;
    }

    // Wrap the user-visible start rule in a synthetic rule that
    // explicitly consumes #ZZ, so trailing content cannot slip past. The
    // IR reserves no names, so fall back to a numbered variant when the
    // grammar has a production of its own called `__start__`.
    let mut start_wrapper = "__start__".to_string();
    if emitter.known_rules.contains(&start_wrapper) {
        let mut n = 2;
        while emitter.known_rules.contains(&format!("__start{n}__")) {
            n += 1;
        }
        start_wrapper = format!("__start{n}__");
    }
    // The wrapper stands in for the start rule, so that is what it is
    // named after.
    emitter.record_prov(&start_wrapper, &start);

    let mut open = AltSpec::new();
    open.set("p", start.as_str());
    open.set("g", tag.as_str());
    // Return the start rule's AST node directly: the wrapper exists only
    // to ensure end-of-source gets consumed. End of source is the one
    // anchor every grammar has.
    let mut close = AltSpec::new();
    close.set("s", "#ZZ");
    emitter.refs.bubble(&mut close);
    close.set("g", sync_g(&tag, "end"));
    emitter.budget.begin_rule(&start, None, &STEP_ALTERNATES);
    emitter.commit_rule(
        &start_wrapper,
        RuleSpec {
            open: vec![open],
            close: Some(vec![close]),
        },
        0,
    )?;

    let mut options: Map<String, Value> = Map::new();
    let mut fixed_map = Map::new();
    for (name, src) in &fixed_tokens {
        fixed_map.insert(name.clone(), src.as_ref().map_or(Value::Null, |s| json!(s)));
    }
    options.insert("fixed".into(), json!({ "token": fixed_map }));
    options.insert("rule".into(), json!({ "start": start_wrapper }));
    options.insert("lex".into(), json!({ "empty": accepts_empty }));
    if !match_tokens.is_empty() {
        let mut match_map = Map::new();
        for (name, tok) in &match_tokens {
            match_map.insert(name.clone(), json!(tok.serialized()));
        }
        options.insert("match".into(), json!({ "token": match_map }));
    }
    // One group per character class that spans several atoms of the
    // partition.
    if !token_sets.is_empty() {
        let mut sets = Map::new();
        for (name, members) in &token_sets {
            sets.insert(name.clone(), json!(members));
        }
        options.insert("tokenSet".into(), Value::Object(sets));
    }

    let Emitter {
        refs,
        prov,
        mut rule_spec,
        budget,
        ..
    } = emitter;

    let mut spec = GrammarSpec {
        refs: refs.refs,
        options,
        rule: IndexMap::new(),
        meta: None,
        clear: false,
    };

    // Engine-ignored tool metadata: the map from each generated rule
    // name to the author-written production it came from, sorted so a
    // serialised grammar is byte-stable.
    if let Some(prov) = prov {
        if !prov.is_empty() {
            let mut names: Vec<&String> = prov.keys().collect();
            names.sort_by_key(|k| k.encode_utf16().collect::<Vec<u16>>());
            let mut provenance = Map::new();
            for name in names {
                provenance.insert(name.clone(), json!(prov[name]));
            }
            spec.meta = Some(json!({ "provenance": provenance }));
        }
    }

    // `<remove>` directives: `<all> = <remove>` maps to the engine's
    // `clear`; a named removal drops both the rule and the fixed token of
    // that name.
    if clear_all {
        spec.clear = true;
    }
    // Each name writes two entries, a rule and a fixed token, and each is
    // charged before it is written (`MAX_EMIT_UNITS`).
    if !remove_names.is_empty() {
        budget.begin(Subject::Removals(remove_names.len()), None, &STEP_REMOVE);
    }
    for name in &remove_names {
        budget.charge(1)?;
        rule_spec.insert(name.clone(), None);
        budget.charge(1)?;
        if let Some(Value::Object(fixed)) = spec.options.get_mut("fixed") {
            if let Some(Value::Object(token)) = fixed.get_mut("token") {
                token.insert(format!("#{name}"), Value::Null);
            }
        }
    }
    spec.rule = rule_spec;

    Ok(spec)
}

/// Allocate the lexer token for a string-literal terminal. A
/// case-sensitive literal is normally a fixed token and a
/// case-insensitive one an anchored `i`-flagged regex. When
/// `word_keywords` is set and the literal ends in a word character, it is
/// emitted as a regex with a trailing `\b` guard so the keyword matches
/// only as a whole word.
fn emit_literal_token(
    literal: &str,
    case_sensitive: Option<bool>,
    name: &str,
    fixed_tokens: &mut IndexMap<String, Option<String>>,
    match_tokens: &mut IndexMap<String, MatchToken>,
    word_keywords: bool,
) -> Result<(), EmitError> {
    let boundary = if word_keywords && ends_with_word_char(literal) {
        "\\b"
    } else {
        ""
    };
    let sensitive = is_effectively_case_sensitive(literal, case_sensitive);
    if sensitive && boundary.is_empty() {
        fixed_tokens.insert(name.to_string(), Some(literal.to_string()));
        return Ok(());
    }
    // Insensitive literal, or a word-keyword needing a boundary guard:
    // emit as an anchored regex, eager so the lexer fires it even when
    // the current rule's token column does not list its tin.
    let flags = if sensitive { "" } else { "i" };
    let source = js_regex_source(&format!("^{}{}", escape_regexp(literal), boundary));
    let flags = check_regex(&source, flags, name)?;
    match_tokens.insert(
        name.to_string(),
        MatchToken {
            source,
            flags,
            eager: true,
        },
    );
    Ok(())
}

/// The flags `new RegExp` accepts, in the order `RegExp.prototype.flags`
/// reports them back.
const REGEX_FLAGS: &str = "dgimsuvy";

/// Check a flag string the way the canonical `RegExp` constructor does —
/// every character a flag it knows, none of them repeated, `u` and `v`
/// never together — and return it in the order that constructor reports,
/// which is the order the canonical compiler serialises rather than the
/// order the front-end wrote (`new RegExp('a', 'yu').flags` is `uy`).
///
/// Flags the engine's `regex` crate does not act on are still accepted:
/// `d`, `g` and `y` change nothing about what the emitted matcher
/// matches, and refusing them would reject IR TypeScript emits happily.
/// `v` is accepted for the same reason, though the Rust engine refuses
/// it when the spec is installed; that refusal is the engine's, and
/// `DIVERGENCE.md` records it.
fn canonical_regex_flags(flags: &str, name: &str) -> Result<String, EmitError> {
    let refuse = |detail: String| {
        EmitError::new(format!(
            "{}: invalid regular expression flags for token {}: {}",
            diag_name(),
            name,
            detail
        ))
    };
    let mut seen = String::new();
    for flag in flags.chars() {
        if !REGEX_FLAGS.contains(flag) {
            return Err(refuse(format!("unknown flag '{flag}' in \"{flags}\"")));
        }
        if seen.contains(flag) {
            return Err(refuse(format!("duplicate flag '{flag}' in \"{flags}\"")));
        }
        seen.push(flag);
    }
    if seen.contains('u') && seen.contains('v') {
        return Err(refuse(format!("flags \"{flags}\" set both u and v")));
    }
    Ok(REGEX_FLAGS.chars().filter(|f| seen.contains(*f)).collect())
}

/// The matcher must compile in the engine's regex dialect: refuse at
/// emit time with the token named, rather than at install time with a
/// grammar the author did not write. Returns the flags to emit, in the
/// canonical order. The flag string is checked FIRST, as `new RegExp`
/// checks it, so a grammar wrong in both ways is refused for the same
/// reason in either runtime.
fn check_regex(source: &str, flags: &str, name: &str) -> Result<String, EmitError> {
    let flags = canonical_regex_flags(flags, name)?;
    let mut builder = regex::RegexBuilder::new(source);
    builder.case_insensitive(flags.contains('i'));
    builder.build().map_err(|err| {
        EmitError::new(format!(
            "{}: invalid regular expression for token {}: {}",
            diag_name(),
            name,
            err
        ))
    })?;
    Ok(flags)
}

/// Allocate the lexer token(s) for one character class, at the point the
/// class is first encountered. Uncontested: one match token. Contested:
/// the class is laid over the shared partition; each atom it covers gets
/// its own match token (minted here if this is the first class to need
/// it), and the class becomes a token SET over them, under the name it
/// would have had anyway, so nothing that consumes `regex_tokens` has to
/// know the difference.
#[allow(clippy::too_many_arguments)]
fn emit_class_token(
    pattern: &str,
    flags: &str,
    key: &str,
    classes: &mut crate::ranges::ClassAnalysis,
    tokens: &mut Tokens,
    token_sets: &mut IndexMap<String, Vec<String>>,
    set_ranges: &mut IndexMap<String, Vec<CharRange>>,
    match_tokens: &mut IndexMap<String, MatchToken>,
    used_names: &mut IndexSet<String>,
    // Where the class was written, for a refusal.
    sp: Option<SrcSpan>,
    budget: &EmitBudget,
) -> Result<(), EmitError> {
    // A class fires at ANY lookahead position, not only at the slots the
    // current rule's collated token column names, which is what makes
    // the runtimes accept the same strings.
    let eager = |pattern: &str, flags: &str, name: &str| -> Result<MatchToken, EmitError> {
        let source = js_regex_source(&format!("^{}", anchorable(pattern)));
        let flags = check_regex(&source, flags, name)?;
        Ok(MatchToken {
            source,
            flags,
            eager: true,
        })
    };

    let name = alloc_token_name(&format!("rx_{pattern}"), used_names, None);
    tokens.regex_tokens.insert(key.to_string(), name.clone());

    // Compiled whether or not the partition replaces it, so a pattern the
    // engine refuses is refused whether or not another class overlaps it.
    // Laid over the partition unchecked, `[z-a]` beside `[a-z]` became an
    // empty set and the grammar was accepted (tabnas/bnf#75 review).
    let own = eager(pattern, flags, &name)?;
    if !classes.contested.contains(key) {
        match_tokens.insert(name.clone(), own);
        return Ok(());
    }

    let code_points = flags.contains(['u', 'v']);
    let mine = classes.coverage[key].clone();
    let mut members: Vec<String> = Vec::new();
    // Each member is charged as it is listed (`MAX_EMIT_UNITS`).
    budget.begin(Subject::Class(pattern.to_string()), sp, &STEP_TOKEN_SET);
    let atoms = classes.atoms.clone();
    for span in atoms {
        if !mine.iter().any(|&(a, b)| a <= span.0 && span.1 <= b) {
            continue;
        }
        let span_key = format!("{}-{}", span.0, span.1);
        let atom = match classes.atom_tokens.get(&span_key) {
            Some(atom) => atom.clone(),
            None => {
                let (atom_pattern, unicode) = class_pattern(span.0, span.1, code_points);
                // `rxa_`, not `rx_`: an atom is synthetic, and a name
                // minted from `rx_` collides with the natural name of any
                // class spelling the same span.
                let atom = alloc_token_name(&format!("rxa_{atom_pattern}"), used_names, None);
                match_tokens.insert(
                    atom.clone(),
                    eager(&atom_pattern, if unicode { "u" } else { "" }, &atom)?,
                );
                classes.atom_tokens.insert(span_key, atom.clone());
                atom
            }
        };
        budget.charge(1)?;
        members.push(atom);
    }

    // A one-member set rather than pointing `regex_tokens` straight at
    // the atom: the class keeps its own name whatever the partition does
    // underneath it. Keyed WITHOUT the leading `#`, which is how the
    // engine looks a set up.
    token_sets.insert(name.trim_start_matches('#').to_string(), members);
    set_ranges.insert(name, code_unit_reach(&mine, flags));
    Ok(())
}

/// Break an alternative into segments. Each segment is a (possibly
/// empty) run of terminal tokens followed by at most one rule reference.
fn segmentize<E: AsElement>(alt: &[E], tokens: &Tokens) -> Vec<Segment> {
    let mut segs: Vec<Segment> = Vec::new();
    let mut current = Segment::default();
    for el in alt {
        let el = el.element();
        match &el.kind {
            Kind::Term { .. } | Kind::Regex { .. } | Kind::Token { .. } => {
                current.terms.push(tokens.name(el));
            }
            Kind::Ref { name, debt } => {
                current.reference = Some(name.clone());
                if let Some(d) = debt {
                    current.debt = Some(d.clone());
                }
                segs.push(std::mem::take(&mut current));
            }
            _ => panic!(
                "{}: internal — unexpected element kind '{}' in emitter",
                diag_name(),
                crate::analysis::kind_name(el)
            ),
        }
    }
    if !current.terms.is_empty() || segs.is_empty() {
        segs.push(current);
    }
    segs
}

/// A stable, human-predictable mark for an alternative: its leading
/// discriminator, the first matched token name (sans `#`), the pushed
/// rule name, or `_` for the empty alt.
fn alt_discriminator(alt: &[Rc<Element>], tokens: &Tokens) -> String {
    let Some(el) = alt.first() else {
        return "_".into();
    };
    let strip = |name: String| {
        let s = name.trim_start_matches('#').to_string();
        if s.is_empty() {
            "_".to_string()
        } else {
            s
        }
    };
    match &el.kind {
        Kind::Term { .. } | Kind::Regex { .. } => strip(tokens.of(el).unwrap_or_default()),
        Kind::Token { name } => strip(name.clone()),
        Kind::Ref { name, .. } => name.clone(),
        _ => "_".into(),
    }
}

/// Assign a unique mark per source alternative, by position. Collisions
/// get a `~N` suffix.
fn assign_marks(alts: &[Sequence], tokens: &Tokens) -> Vec<String> {
    let mut seen: IndexMap<String, usize> = IndexMap::new();
    alts.iter()
        .map(|alt| {
            let base = alt_discriminator(alt, tokens);
            let n = seen.get(&base).copied().unwrap_or(0) + 1;
            seen.insert(base.clone(), n);
            if n == 1 {
                base
            } else {
                format!("{base}~{n}")
            }
        })
        .collect()
}

/// The item a repeat loop repeats: its alternatives are `[[item, self],
/// []]`, as `desugar` mints them. Anything else is a compiler defect, not
/// a grammar the author could have written, so it is refused as one.
fn loop_item_of(prod: &Production) -> Result<Element, EmitError> {
    let alts = &prod.alts;
    let body = alts.iter().find(|alt| !alt.is_empty());
    let shaped = alts.len() == 2
        && alts.iter().any(Vec::is_empty)
        && body.is_some_and(|body| {
            body.len() == 2
                && matches!(&body[1].kind, Kind::Ref { name, .. } if *name == prod.name)
                && !matches!(&body[0].kind, Kind::Ref { debt: Some(_), .. })
        });
    match body {
        Some(body) if shaped => Ok(Element::clone(&body[0])),
        _ => Err(EmitError::new(format!(
            "{}: internal — repeat loop '{}' is not `item self / (empty)`",
            diag_name(),
            prod.name
        ))),
    }
}

fn debt_to_n(debt: &IndexMap<String, i64>) -> Map<String, Value> {
    let mut n = Map::new();
    for (k, v) in debt {
        n.insert(k.clone(), json!(v));
    }
    n
}

/// Install the value builders on an alt of a rule that BUILDS A VALUE,
/// dropping the tree builders it was emitted with. No actions at all
/// means NO `a`, not an empty list.
fn use_value_actions(spec: &mut AltSpec, actions: &[&str], cfg: Option<Map<String, Value>>) {
    spec.set_actions(actions);
    if let Some(k) = spec.k_mut() {
        // Builtins mode names its tree config; closure mode carries none.
        k.remove("node$");
        k.remove("capture$");
    }
    if let Some(cfg) = cfg {
        let mut k = spec.k().cloned().unwrap_or_default();
        for (key, value) in cfg {
            k.insert(key, value);
        }
        spec.set("k", Value::Object(k));
    }
    if spec.k().is_some_and(Map::is_empty) {
        spec.remove("k");
    }
}

/// Put the array builder on the close of a link INSIDE an annotated
/// array. No element (a separator, or a push of another collecting
/// helper) drops the tree builders and adds nothing; a rule that builds
/// a value of its own nests whole; anything else resolves to its text.
fn push_element(spec: &mut AltSpec, elem: Option<&str>, value_rules: &IndexSet<String>) {
    match elem {
        None => use_value_actions(spec, &[], None),
        Some(elem) => {
            let cfg = if value_rules.contains(elem) {
                None
            } else {
                let mut m = Map::new();
                m.insert("push$".into(), json!({"src": true}));
                Some(m)
            };
            use_value_actions(spec, &["@push$"], cfg);
        }
    }
}

/// `{ ...base, s, b }`: a copy of an alternate re-keyed on a token
/// sequence and pushing `b` of them back.
fn peek_copy(base: &AltSpec, s: String, b: usize) -> AltSpec {
    let mut g = base.clone();
    g.set("s", s);
    g.set("b", b);
    g
}

impl Emitter<'_> {
    fn record_prov(&mut self, name: &str, origin: &str) {
        if let Some(prov) = &mut self.prov {
            prov.insert(name.to_string(), origin.to_string());
        }
    }

    /// Charge an alternate of the rule `emit_production` is building as it
    /// is made (`MAX_EMIT_UNITS`), adding it to what that rule's commit
    /// will count as charged already.
    fn made(&self, o: AltSpec) -> Result<AltSpec, EmitError> {
        let n = alt_units(&o);
        self.budget.charge(n)?;
        self.pre.set(self.pre.get() + n);
        Ok(o)
    }

    /// Write a rule into the compiled grammar, charging what it holds
    /// beyond the `pre` units already charged for its alternates as they
    /// were made.
    fn commit_rule(&mut self, name: &str, rs: RuleSpec, pre: usize) -> Result<(), EmitError> {
        let units = rule_units(&rs);
        assert!(
            units >= pre,
            "{}: internal — rule '{name}' holds {units} units, fewer than the {pre} \
             charged for its alternates",
            diag_name()
        );
        self.budget.charge(units - pre)?;
        self.rule_spec.insert(name.to_string(), Some(rs));
        Ok(())
    }

    /// `{ g, s?, p?, n?, a, k? }`: the alternate for one segment.
    fn segment_to_alt(
        &mut self,
        seg: &Segment,
        init_node: bool,
        rule_name: &str,
        kind: NodeKind,
    ) -> AltSpec {
        let mut spec = AltSpec::with_tag(&self.tag);
        if !seg.terms.is_empty() {
            spec.set("s", seg.terms.join(" "));
        }
        if let Some(r) = &seg.reference {
            spec.set("p", r.as_str());
        }
        // Suffix-debt bookkeeping rides on the alt that does the push,
        // so the child inherits the updated counter.
        if let Some(debt) = &seg.debt {
            spec.set("n", Value::Object(debt_to_n(debt)));
        }
        // Default tree-building: accumulate each matched terminal's
        // source text into the node. Head alts also allocate a fresh node.
        let nterms = seg.terms.len();
        if nterms > 0 || init_node {
            self.refs
                .node(&mut spec, init_node, rule_name, kind, nterms);
        }
        spec
    }

    /// `{ r?, a, k?, g }`: a close alternate that captures the returned
    /// child, and replaces itself with `r` when given.
    fn capture_close(&mut self, rule_name: &str, kind: NodeKind, r: Option<&str>) -> AltSpec {
        let mut close = AltSpec::new();
        if let Some(r) = r {
            close.set("r", r);
        }
        self.refs.capture(&mut close, rule_name, kind);
        close.set("g", self.tag.as_str());
        close
    }

    fn validate_refs(&self, alt: &[Rc<Element>], rule_name: &str) -> Result<(), EmitError> {
        for el in alt {
            if let Kind::Ref { name, .. } = &el.kind {
                if !self.known_rules.contains(name) {
                    return Err(EmitError::at(
                        format!(
                            "{}: rule '{}' references unknown rule '{}'",
                            diag_name(),
                            rule_name,
                            name
                        ),
                        rule_name,
                        el.sp,
                    ));
                }
            }
        }
        Ok(())
    }

    /// A self-looping rule that matches any one of the vocab tokens and
    /// restarts; a final empty-alt fallback ensures the rule NEVER
    /// fails, the property the probe pattern relies on.
    fn emit_probe_helper(&mut self, prod: &Production) -> Result<(), EmitError> {
        let elems = &prod
            .probe_helper
            .as_ref()
            .expect("probe helper")
            .vocab_elements;
        let mut opens: Vec<AltSpec> = Vec::new();
        for el in elems {
            if let Some(tok) = self.tokens.of(el) {
                let mut o = AltSpec::new();
                o.set("s", tok);
                o.set("r", prod.name.as_str());
                o.set("g", self.tag.as_str());
                opens.push(o);
            }
        }
        // Empty fallback: pops without consuming anything. Must be last.
        opens.push(AltSpec::with_tag(&self.tag));
        // Charged with the list it is made from (`rewrite_probe_dispatches`).
        self.commit_rule(
            &prod.name,
            RuleSpec {
                open: opens,
                close: None,
            },
            probe_rule_units(elems.len()),
        )
    }

    /// The three-phase retry pattern: mark and probe on phase 0, decide
    /// and rewind on its close, commit to a branch on phases 1 and 2.
    fn emit_probe_dispatch(&mut self, prod: &Production) -> Result<(), EmitError> {
        let pd = prod.probe_dispatch.clone().expect("probe dispatch");
        let Some(disambiguator_token) = self.tokens.of(&pd.disambiguator) else {
            return Err(EmitError::new(format!(
                "{}: probe-dispatch rule '{}' has unresolvable disambiguator (kind={})",
                diag_name(),
                prod.name,
                crate::analysis::kind_name(&pd.disambiguator)
            )));
        };
        let tag = self.tag.clone();

        // `bubble` lifts the committed child's node up: pure tree-building.
        // Registered first, as the canonical compiler does, so closure-mode
        // ref names come out in the same order.
        let mut bubble = AltSpec::new();
        self.refs.bubble(&mut bubble);
        bubble.set("g", tag.as_str());

        if self.refs.use_builtins {
            // Function-free dispatcher: control logic is engine
            // `$`-builtins, the disambiguator token rides in `k` config.
            let mut open0 = AltSpec::new();
            open0.set("c", "@probePhase0$");
            open0.set("a", "@probeInit$");
            open0.set("p", pd.probe_rule.as_str());
            open0.set("k", json!({ "pd_d": disambiguator_token }));
            open0.set("g", tag.as_str());
            let mut open1 = AltSpec::new();
            open1.set("c", "@probePhase1$");
            open1.set("p", pd.with_branch.as_str());
            open1.set("g", tag.as_str());
            let mut open2 = AltSpec::new();
            open2.set("c", "@probePhase2$");
            open2.set("p", pd.no_branch.as_str());
            open2.set("g", tag.as_str());
            let mut close0 = AltSpec::new();
            close0.set("c", "@probePhase0$");
            close0.set("a", "@probeDecide$");
            close0.set("r", prod.name.as_str());
            close0.set("g", tag.as_str());
            return self.commit_rule(
                &prod.name,
                RuleSpec {
                    open: vec![open0, open1, open2],
                    close: Some(vec![close0, bubble]),
                },
                0,
            );
        }

        let init_mark = self.refs.register(RefAction::ProbeInit);
        let decide = self.refs.register(RefAction::ProbeDecide {
            disambiguator: disambiguator_token,
        });
        // Phase 0, first pass: mark and probe.
        let phase0 = self.refs.register(RefAction::ProbePhase(0));
        let mut open0 = AltSpec::new();
        open0.set("c", phase0);
        open0.set("a", init_mark);
        open0.set("p", pd.probe_rule.as_str());
        open0.set("g", tag.as_str());
        // Phase 1, the disambiguator was seen: commit to X D Y.
        let phase1 = self.refs.register(RefAction::ProbePhase(1));
        let mut open1 = AltSpec::new();
        open1.set("c", phase1);
        open1.set("p", pd.with_branch.as_str());
        open1.set("g", tag.as_str());
        // Phase 2, the disambiguator was not seen: commit to Y alone.
        let phase2 = self.refs.register(RefAction::ProbePhase(2));
        let mut open2 = AltSpec::new();
        open2.set("c", phase2);
        open2.set("p", pd.no_branch.as_str());
        open2.set("g", tag.as_str());
        // Phase 0 close: decide the phase from the peek, rewind, retry.
        let close_phase0 = self.refs.register(RefAction::ProbePhase(0));
        let mut close0 = AltSpec::new();
        close0.set("c", close_phase0);
        close0.set("a", decide);
        close0.set("r", prod.name.as_str());
        close0.set("g", tag.as_str());
        self.commit_rule(
            &prod.name,
            RuleSpec {
                open: vec![open0, open1, open2],
                close: Some(vec![close0, bubble]),
            },
            0,
        )
    }

    /// A production marked by the tail-repeat rewrite: the same shape a
    /// hand-written tabnas grammar uses for `X = a [ b X ]`. Every
    /// iteration folds itself into the parent.
    fn emit_tail_repeat(&mut self, prod: &Production) -> Result<(), EmitError> {
        let prod_kind = prod.node_kind;
        let prefix_alt = &prod.alts[0];
        let sep = &prod.tail_repeat.as_ref().expect("tail repeat").sep;

        // All-terminal sequences, so each segmentizes to exactly one
        // ref-free segment.
        let prefix_seg = segmentize(prefix_alt, &self.tokens).remove(0);
        let sep_seg = segmentize(sep, &self.tokens).remove(0);

        let marks = if prod_kind == NodeKind::User && self.refs.emit_marks {
            Some(assign_marks(
                &[
                    prefix_alt.clone(),
                    sep.iter().map(AsElement::share).collect(),
                ],
                &self.tokens,
            ))
        } else {
            None
        };

        let mut open = self.segment_to_alt(&prefix_seg, true, &prod.name, prod_kind);
        if let Some(m) = &marks {
            open.m = Some(m[0].clone());
        }

        // The separator continuation of a repetition is the single most
        // useful resync point a list grammar has.
        let mut repeat = AltSpec::new();
        repeat.set("s", sep_seg.terms.join(" "));
        repeat.set("r", prod.name.as_str());
        self.refs.fold(&mut repeat, Some(sep_seg.terms.len()));
        repeat.set("g", sync_g(&self.tag, "comma"));
        if let Some(m) = &marks {
            repeat.m = Some(m[1].clone());
        }

        let mut end = AltSpec::new();
        self.refs.fold(&mut end, None);
        end.set("g", self.tag.as_str());
        if marks.is_some() {
            end.m = Some("_".into());
        }

        self.commit_rule(
            &prod.name,
            RuleSpec {
                open: vec![open],
                close: Some(vec![repeat, end]),
            },
            0,
        )
    }

    /// FOLLOWâ‚‚ exit guards for a CONTESTED repetition, one whose repeated
    /// element covers a follow token at the character level. The
    /// 2-token guard writes the decision down: exit exactly when the
    /// follow token is followed by something only the exit path can
    /// accept.
    ///
    /// Each guard is charged as it is made (`MAX_EMIT_UNITS`).
    fn pair_exit_guards(
        &self,
        prod: &Production,
        base: &AltSpec,
    ) -> Result<Vec<AltSpec>, EmitError> {
        if !prod.repeat_helper {
            return Ok(Vec::new());
        }
        let Some(pairs) = self.follow_pairs.get(&prod.name) else {
            return Ok(Vec::new());
        };
        if pairs.is_empty() {
            return Ok(Vec::new());
        }
        let empty = IndexSet::new();
        let cont_first = self.first_sets.get(&prod.name).unwrap_or(&empty);
        let mut out = Vec::new();
        let mut seen: IndexSet<String> = IndexSet::new();
        for (t, us) in pairs {
            if us.is_empty() {
                continue;
            }
            if self.contest.token_ranges_of(t).is_none() {
                continue;
            }
            let contested = cont_first
                .iter()
                .any(|f| f != t && self.contest.tokens_overlap(t, f));
            if !contested {
                continue;
            }
            for u in us {
                let s = format!("{t} {u}");
                if !seen.insert(s.clone()) {
                    continue;
                }
                out.push(self.made(peek_copy(base, s, 2))?);
            }
        }
        Ok(out)
    }

    /// The 2-token guards for one literal-headed dispatch entry: the
    /// keyword plus a token only the keyword alternative can follow it
    /// with. `None` when no guard can be justified, and then no
    /// reordering happens either. The paths it enumerates are held while
    /// it runs (`MAX_EMIT_UNITS`), and each guard is charged as it is made.
    fn synth_keyword_guards(
        &self,
        prod: &Production,
        o: &AltSpec,
        alt: &[Rc<Element>],
        f: &str,
        consumed: i64,
    ) -> Result<Option<Vec<AltSpec>>, EmitError> {
        // The paths are held until they have been read (`MAX_EMIT_UNITS`).
        let base = self.budget.held();
        let paths = alt_prefixes_raw(
            alt,
            self.grammar,
            &self.tokens,
            2,
            &IndexSet::new(),
            None,
            Some(&self.contest.class_sets),
            &self.budget,
        )?;
        let mut seconds: IndexSet<String> = IndexSet::new();
        let mut known = true;
        for p in &paths {
            if p.tokens.first().map(|t| &**t) != Some(f) {
                continue;
            }
            if p.tokens.len() >= 2 {
                seconds.insert(p.tokens[1].to_string());
                continue;
            }
            // The literal can end the alternative: the second token is
            // whatever may follow the production. An unknown FOLLOW means
            // no guard.
            match self.follow_sets.get(&prod.name) {
                Some(fol) if !fol.is_empty() => seconds.extend(fol.iter().cloned()),
                _ => {
                    known = false;
                    break;
                }
            }
        }
        drop(paths);
        self.budget.restore(base);
        if !known {
            return Ok(None);
        }
        if seconds.is_empty() || seconds.len() > 16 {
            return Ok(None);
        }
        let mut guards = Vec::with_capacity(seconds.len());
        for u in &seconds {
            guards.push(self.made(peek_copy(
                o,
                format!("{f} {u}"),
                (2 - consumed).max(0) as usize,
            ))?);
        }
        Ok(Some(guards))
    }

    /// Keyword-shadow reordering. Every literal-headed dispatch entry
    /// contested by a class-headed entry gets 2-token guards placed ahead
    /// of the first contesting class entry, while its 1-token original
    /// drops behind the class entries so it can no longer steal; entries
    /// that already carry multi-token prefixes simply move ahead.
    fn reorder_keyword_shadow(
        &self,
        prod: &Production,
        entries: &[Entry],
    ) -> Result<Vec<Placed>, EmitError> {
        // A token class's set is a literal head here (`literal_heads`):
        // its members are literals and engine tokens, never a character
        // class (`token_class_names`), and with the option off those
        // members are literal heads this ordering places, each one.

        // Head token and lookahead length, resolved ONCE per entry.
        let n = entries.len();
        let mut heads: Vec<Option<String>> = Vec::with_capacity(n);
        let mut s_lens: Vec<usize> = Vec::with_capacity(n);
        for e in entries {
            match e.o.s() {
                Some(s) if !s.is_empty() => {
                    heads.push(Some(s.split(' ').next().unwrap_or("").to_string()));
                    s_lens.push(1 + s.matches(' ').count());
                }
                _ => {
                    heads.push(None);
                    s_lens.push(0);
                }
            }
        }

        // Class-headed entries, with their character coverage resolved once.
        let mut class_idx: Vec<usize> = Vec::new();
        let mut class_ranges: Vec<Vec<CharRange>> = Vec::new();
        for (i, head) in heads.iter().enumerate() {
            let Some(f) = head else { continue };
            if !self.class_heads.contains(f) {
                continue;
            }
            let Some(r) = self.contest.token_ranges_of(f) else {
                continue;
            };
            class_idx.push(i);
            class_ranges.push(r);
        }
        if class_idx.is_empty() {
            return Ok(entries
                .iter()
                .enumerate()
                .map(|(i, e)| Placed {
                    o: e.o.clone(),
                    rank: i as f64,
                    seq: i,
                })
                .collect());
        }

        let mut placed: Vec<Placed> = Vec::new();
        let mut seq = 0usize;
        let mut put = |o: AltSpec, rank: f64| {
            placed.push(Placed { o, rank, seq });
            seq += 1;
        };

        // Which class entries a given literal head contests, decided once
        // per distinct head token. It keeps no more answers than the memo
        // limit (`MAX_MEMO_ENTRIES`), and a head past it is answered as it
        // comes.
        let mut contests_by_head: IndexMap<String, Vec<bool>> = IndexMap::new();
        let mut kept = 0usize;

        for (i, e) in entries.iter().enumerate() {
            let f = heads[i].as_deref();
            let fr = match f {
                Some(f) if self.literal_heads.contains(f) => self.contest.literal_head_ranges_of(f),
                _ => None,
            };

            // First and last contesting class entry, in one pass.
            let mut first_c: Option<usize> = None;
            let mut last_c: Option<usize> = None;
            if let (Some(fr), Some(_)) = (&fr, &e.alt) {
                let f = f.expect("a literal head is present");
                if !contests_by_head.contains_key(f) && kept + class_idx.len() <= memo_limit() {
                    contests_by_head.insert(
                        f.to_string(),
                        class_ranges
                            .iter()
                            .map(|cr| char_ranges_overlap(fr, cr))
                            .collect(),
                    );
                    kept += class_idx.len();
                }
                let hits = contests_by_head.get(f);
                for (k, c) in class_idx.iter().enumerate() {
                    let hit = match hits {
                        Some(hits) => hits[k],
                        None => char_ranges_overlap(fr, &class_ranges[k]),
                    };
                    if !hit {
                        continue;
                    }
                    // Same descent target either way: order is moot.
                    if descent_of(&e.o).is_some() && descent_of(&entries[*c].o) == descent_of(&e.o)
                    {
                        continue;
                    }
                    if first_c.is_none() {
                        first_c = Some(*c);
                    }
                    last_c = Some(*c);
                }
            }

            let Some(first_c) = first_c else {
                put(e.o.clone(), i as f64);
                continue;
            };
            let front = first_c as f64 - 0.5;
            let back = last_c.unwrap_or(first_c) as f64 + 0.5;

            if s_lens[i] >= 2 {
                // Already carries its own lookahead: just outrank the class.
                put(e.o.clone(), (i as f64).min(front));
                continue;
            }

            let consumed = 1 - e.o.b().map_or(0, |b| b as i64);
            let guards = if consumed == 0 || consumed == 1 {
                self.synth_keyword_guards(
                    prod,
                    &e.o,
                    e.alt.as_deref().expect("checked above"),
                    f.expect("checked above"),
                    consumed,
                )?
            } else {
                None
            };
            let Some(guards) = guards else {
                put(e.o.clone(), i as f64);
                continue;
            };
            for g in guards {
                put(g, (i as f64).min(front));
            }
            put(e.o.clone(), (i as f64).max(back));
        }

        placed.sort_by(|a, b| {
            a.rank
                .partial_cmp(&b.rank)
                .unwrap_or(std::cmp::Ordering::Equal)
                .then(a.seq.cmp(&b.seq))
        });
        Ok(placed)
    }

    /// Specificity ordering among contested class heads: among entries
    /// whose class heads overlap at the character level and whose
    /// descents differ, longer lookahead goes first (maximal munch), then
    /// the longer alternative. Entries are permuted among their own
    /// slots so everything else stays put.
    fn specificity_permute(&self, entries: &mut [Entry]) {
        let n = entries.len();
        let mut s_lens: Vec<usize> = vec![0; n];
        let mut heads: Vec<Option<String>> = vec![None; n];
        for (i, e) in entries.iter().enumerate() {
            let Some(s) = e.o.s().filter(|s| !s.is_empty()) else {
                continue;
            };
            s_lens[i] = 1 + s.matches(' ').count();
            if e.alt.is_none() {
                continue;
            }
            let f = s.split(' ').next().unwrap_or("").to_string();
            if self.class_heads.contains(&f) {
                heads[i] = Some(f);
            }
        }
        let ranges: Vec<Option<Vec<CharRange>>> = heads
            .iter()
            .map(|h| h.as_deref().and_then(|f| self.contest.token_ranges_of(f)))
            .collect();
        let mut idxs: Vec<usize> = Vec::new();
        for i in 0..n {
            let Some(ri) = &ranges[i] else { continue };
            for (j, rj) in ranges.iter().enumerate() {
                if j == i {
                    continue;
                }
                let Some(rj) = rj else { continue };
                // Same descent target: the order between them is moot.
                // Only when a descent EXISTS, though.
                let to = descent_of(&entries[i].o);
                if to.is_some() && descent_of(&entries[j].o) == to {
                    continue;
                }
                if char_ranges_overlap(ri, rj) {
                    idxs.push(i);
                    break;
                }
            }
        }
        if idxs.len() < 2 {
            return;
        }
        // How much the alternative behind an entry can consume in total:
        // the longer alternative is the more specific one.
        let spans: IndexMap<usize, f64> = idxs
            .iter()
            .map(|&i| {
                let span = match &entries[i].alt {
                    None => 0.0,
                    Some(alt) => match seq_token_span(alt, self.grammar) {
                        Some(n) => n as f64,
                        None => 1e9,
                    },
                };
                (i, span)
            })
            .collect();
        let mut order = idxs.clone();
        order.sort_by(|&a, &b| {
            s_lens[b].cmp(&s_lens[a]).then(
                spans[&b]
                    .partial_cmp(&spans[&a])
                    .unwrap_or(std::cmp::Ordering::Equal),
            )
        });
        let picked: Vec<Entry> = order.iter().map(|&i| entries[i].clone()).collect();
        for (k, slot) in idxs.iter().enumerate() {
            entries[*slot] = picked[k].clone();
        }
    }

    /// True for a repetition helper whose content can start with a token
    /// its FOLLOW also contains.
    fn contested_by_follow(&self, prod: &Production, alt: &[Rc<Element>]) -> bool {
        if !prod.repeat_helper {
            return false;
        }
        let Some(mine) = first_of_alt(alt, &self.tokens, &self.first_sets, &self.nullable) else {
            return false;
        };
        let empty = IndexSet::new();
        let fol = self.follow_sets.get(&prod.name).unwrap_or(&empty);
        mine.iter().any(|t| {
            fol.iter()
                .any(|f| f == t || self.contest.tokens_overlap(t, f))
        })
    }

    /// True when this alternative's first tokens overlap another
    /// alternative's at the character level with a different descent.
    fn alt_head_contested(&self, idx: usize, all: &[Sequence]) -> bool {
        let Some(mine) = first_of_alt(&all[idx], &self.tokens, &self.first_sets, &self.nullable)
        else {
            return false;
        };
        for (j, other) in all.iter().enumerate() {
            if j == idx || other.is_empty() {
                continue;
            }
            let Some(theirs) = first_of_alt(other, &self.tokens, &self.first_sets, &self.nullable)
            else {
                continue;
            };
            for t in &mine {
                for u in &theirs {
                    if self.contest.tokens_overlap(t, u) {
                        return true;
                    }
                }
            }
        }
        false
    }

    /// Can two alternates be handed the SAME token? Deliberately narrower
    /// than [`alt_head_contested`](Self::alt_head_contested): two
    /// different class tokens can still be handed the same token,
    /// because a class that spans several atoms is a set.
    fn alt_head_shares_token(&self, idx: usize, all: &[Sequence]) -> bool {
        let Some(mine) = first_of_alt(&all[idx], &self.tokens, &self.first_sets, &self.nullable)
        else {
            return false;
        };
        for (j, other) in all.iter().enumerate() {
            if j == idx || other.is_empty() {
                continue;
            }
            let Some(theirs) = first_of_alt(other, &self.tokens, &self.first_sets, &self.nullable)
            else {
                continue;
            };
            for t in &mine {
                for u in &theirs {
                    if t == u {
                        return true;
                    }
                    if self.class_heads.contains(t)
                        && self.class_heads.contains(u)
                        && self.contest.tokens_overlap(t, u)
                    {
                        return true;
                    }
                }
            }
        }
        false
    }

    /// Suffix-debt guard for a contested left-recursion tail loop: a
    /// branch that would eat a token an enclosing frame still owes may
    /// only run while the debt is zero. Only the branches whose head
    /// token is contested are guarded, and never the exit peeks or the
    /// bare fallback.
    fn apply_debt_guard(prod: &Production, list: &mut [Entry]) {
        let (Some(guard), Some(owed)) = (&prod.debt_guard, &prod.debt_owed) else {
            return;
        };
        let owed: IndexSet<&String> = owed.iter().collect();
        // Scalar shorthand for `$eq`, the one spelling shape-identical in
        // every runtime.
        let c = json!({ format!("n.{guard}"): 0 });
        for e in list.iter_mut() {
            if e.alt.as_ref().is_none_or(Vec::is_empty) {
                continue;
            }
            // Entries are keyed by the token sequence they peek, so the
            // head token says which branch this is.
            if let Some(s) = e.o.s() {
                let head = s.split(' ').next().unwrap_or("").to_string();
                if !owed.contains(&head) {
                    continue;
                }
            }
            e.o.set("c", c.clone());
        }
    }

    fn emit_production(&mut self, prod: &Production) -> Result<(), EmitError> {
        // This rule stands inside an annotated array: it inherits that
        // array from its parent and pushes into it, instead of building a
        // node.
        let array_elem = self.array_helpers.contains(&prod.name);
        let tag = self.tag.clone();
        // Every alternate this rule's own open list will hold is charged
        // as it is made (`made`); the rule's commit charges the rest.
        self.pre.set(0);

        for alt in &prod.alts {
            self.validate_refs(alt, &prod.name)?;
        }

        if prod.tail_repeat.is_some() {
            self.emit_tail_repeat(prod)?;
            return Ok(());
        }

        // A repeat loop (`Production::repeat_loop`). Its alternatives are
        // `[[item, self], []]`, and every decision is made from them as
        // they stand, exactly as the right-recursive helper always was:
        // the continue alternative is dispatched on the prefixes of
        // `item self`, the exit on FOLLOW and FOLLOWâ‚‚, the debt guard on
        // the item's head. What changes is what taking the continue
        // alternative DOES: it replaces rather than pushes. See
        // `emit_repeat_loop`.
        let loop_item: Option<Element> = if prod.repeat_loop {
            Some(loop_item_of(prod)?)
        } else {
            None
        };

        let all_simple = prod.alts.iter().all(is_single_segment);
        let prod_kind = prod.node_kind;

        // A collecting helper with several alternatives shares ONE close
        // alt here, and the alternatives need not agree. The dispatcher
        // path gives each alternative its own rule, and so its own close.
        let split_alts = array_elem && prod.alts.len() > 1 && !prod.repeat_helper;

        if all_simple && prod.value.is_none() && !split_alts {
            // Every alternative collapses to one tabnas alt. Empty alts
            // are sorted to the end so first-match-wins cannot let them
            // short-circuit non-empty alternatives.
            let mut ordered: Vec<Sequence> = prod
                .alts
                .iter()
                .filter(|a| !a.is_empty())
                .cloned()
                .collect();
            ordered.extend(prod.alts.iter().filter(|a| a.is_empty()).cloned());

            let marks = if prod_kind == NodeKind::User && self.refs.emit_marks {
                Some(assign_marks(&ordered, &self.tokens))
            } else {
                None
            };
            let needs_peek = ordered.len() > 1;
            let mut entries: Vec<Entry> = Vec::new();
            for (idx, alt) in ordered.iter().enumerate() {
                let segs = segmentize(alt, &self.tokens);
                let seg = segs[0].clone();
                let is_ref_only = !alt.is_empty()
                    && alt.iter().all(|el| el.is_ref())
                    && seg.terms.is_empty()
                    && seg.reference.is_some();
                let mark = marks.as_ref().map(|m| m[idx].clone());

                // Ref-only alternatives have no terminal to discriminate
                // on, so guard them with FIRST-set peeks when the
                // production has more than one alt.
                if needs_peek && is_ref_only {
                    if let Some(first_tokens) =
                        first_of_alt(alt, &self.tokens, &self.first_sets, &self.nullable)
                    {
                        let mut node_fields = AltSpec::new();
                        self.refs
                            .node(&mut node_fields, true, &prod.name, prod_kind, 0);
                        // A contested head cannot be decided by one
                        // token: fan out to K-token prefixes (bounded,
                        // deduped; bail to the 1-token peek if the fan-out
                        // is degenerate).
                        let mut paths: Option<Vec<Vec<String>>> = None;
                        // What `alt_prefixes` returns stays held until the
                        // entries made from it are written (`MAX_EMIT_UNITS`).
                        let peek_base = self.budget.held();
                        if self.alt_head_contested(idx, &ordered)
                            || self.contested_by_follow(prod, alt)
                        {
                            let pfx: Vec<Vec<String>> = alt_prefixes(
                                alt,
                                self.grammar,
                                &self.tokens,
                                LOOKAHEAD_K,
                                Some(&self.contest.class_sets),
                                &self.budget,
                            )?
                            .into_iter()
                            .filter(|p| !p.is_empty())
                            .collect();
                            if !pfx.is_empty() && pfx.len() <= 64 {
                                paths = Some(pfx);
                            }
                        }
                        // `{ s, b, p, n?, a, k?, g }`, with the same
                        // suffix-debt bookkeeping `segment_to_alt` carries.
                        let debt = seg.debt.as_ref().map(debt_to_n);
                        let peeks: Vec<(String, usize)> = match paths {
                            Some(paths) => paths
                                .into_iter()
                                .map(|p| {
                                    let b = p.len();
                                    (p.join(" "), b)
                                })
                                .collect(),
                            None => first_tokens.iter().map(|tok| (tok.clone(), 1)).collect(),
                        };
                        for (s, b) in peeks {
                            let mut o = AltSpec::new();
                            o.set("s", s);
                            o.set("b", b);
                            o.set("p", seg.reference.clone().unwrap_or_default());
                            if let Some(n) = &debt {
                                o.set("n", Value::Object(n.clone()));
                            }
                            o.assign_from(&node_fields);
                            o.set("g", tag.as_str());
                            o.m = mark.clone();
                            entries.push(Entry {
                                o: self.made(o)?,
                                alt: Some(alt.clone()),
                            });
                        }
                        self.budget.restore(peek_base);
                        continue;
                    }
                }
                // A loop's item, when it reaches this path, is one
                // terminal: the continue alternative matches it into the
                // node the loop's entry allocated and re-enters the loop
                // at once (`r:`), and neither alternative allocates a
                // node.
                let mut o = if loop_item.is_none() {
                    self.segment_to_alt(&seg, true, &prod.name, prod_kind)
                } else if !alt.is_empty() {
                    // `{ g, s, r, ...acts }`
                    let bare = Segment {
                        terms: seg.terms.clone(),
                        reference: None,
                        debt: None,
                    };
                    let mut acts = self.segment_to_alt(&bare, false, &prod.name, prod_kind);
                    let mut o = AltSpec::new();
                    if let Some(g) = acts.remove("g") {
                        o.set("g", g);
                    }
                    if let Some(s) = acts.remove("s") {
                        o.set("s", s);
                    }
                    o.set("r", prod.name.as_str());
                    o.assign_from(&acts);
                    o
                } else {
                    self.segment_to_alt(&seg, false, &prod.name, prod_kind)
                };
                o.m = mark;
                // The terminating alternative of a repetition helper
                // names no token, so the lexer is never asked to produce
                // whatever follows the repetition. Re-issue that
                // alternative once per FOLLOW token, peeking and pushing
                // straight back. The bare alternative stays last.
                if alt.is_empty() && prod.repeat_helper {
                    let fol: Vec<String> = self
                        .follow_sets
                        .get(&prod.name)
                        .map(|s| s.iter().cloned().collect())
                        .unwrap_or_default();
                    for tok in fol {
                        entries.push(Entry {
                            o: self.made(peek_copy(&o, tok, 1))?,
                            alt: None,
                        });
                    }
                    // Contested repetitions additionally get FOLLOWâ‚‚
                    // guards, at the FRONT so they outrank the continue
                    // alternatives.
                    let guards: Vec<Entry> = self
                        .pair_exit_guards(prod, &o)?
                        .into_iter()
                        .map(|g| Entry { o: g, alt: None })
                        .collect();
                    entries.splice(0..0, guards);
                }

                // `terms… ref` against a sibling that stops on the same
                // head: name the reference's FIRST token in `s` and push
                // it straight back, so the shorter sibling stays
                // reachable. These entries REPLACE the one-token form.
                let ref_peek: Option<Vec<String>> = match &seg.reference {
                    Some(r)
                        if needs_peek
                            && !seg.terms.is_empty()
                            && !self.nullable.contains(r)
                            && self.alt_head_shares_token(idx, &ordered) =>
                    {
                        Some(
                            self.first_sets
                                .get(r)
                                .map(|s| s.iter().cloned().collect())
                                .unwrap_or_default(),
                        )
                    }
                    _ => None,
                };
                if let Some(peek) = ref_peek {
                    if !peek.is_empty() && peek.len() <= 64 {
                        for tok in peek {
                            let mut terms = seg.terms.clone();
                            terms.push(tok);
                            entries.push(Entry {
                                o: self.made(peek_copy(&o, terms.join(" "), 1))?,
                                alt: Some(alt.clone()),
                            });
                        }
                        continue;
                    }
                }

                entries.push(Entry {
                    o: self.made(o)?,
                    alt: if alt.is_empty() {
                        None
                    } else {
                        Some(alt.clone())
                    },
                });
            }

            Self::apply_debt_guard(prod, &mut entries);
            self.specificity_permute(&mut entries);
            let placed = self.reorder_keyword_shadow(prod, &entries)?;

            // A loop has no close: the entry goes first, and the
            // continue alternative re-enters the loop itself. Inside an
            // `; @array` every placed entry is stripped of its value
            // actions, the keyword guards the reordering copied off the
            // entries included: the canonical strips the entries before
            // it copies them, so a guard carries what its entry carries.
            if loop_item.is_some() {
                let mut opens: Vec<AltSpec> = Vec::with_capacity(placed.len() + 1);
                for p in placed {
                    let mut o = p.o;
                    if array_elem {
                        use_value_actions(&mut o, &[], None);
                    }
                    opens.push(o);
                }
                opens.insert(0, self.loop_entry(prod, array_elem));
                let pre = self.pre.get();
                return self.commit_rule(
                    &prod.name,
                    RuleSpec {
                        open: opens,
                        close: None,
                    },
                    pre,
                );
            }

            // If any alt has a push, the close state must capture the
            // returned child.
            let mut close: Option<Vec<AltSpec>> = None;
            if prod.alts.iter().any(|alt| alt.iter().any(|el| el.is_ref())) {
                let mut c = self.capture_close(&prod.name, prod_kind, None);
                if marks.is_some() {
                    c.m = Some("_".into());
                }
                close = Some(vec![c]);
            }
            let mut opens: Vec<AltSpec> = Vec::with_capacity(placed.len());
            for p in placed {
                let mut o = p.o;
                // Every placed entry, the keyword guards the reordering
                // copied off the entries included (see the loop above).
                if array_elem {
                    use_value_actions(&mut o, &[], None);
                }
                opens.push(o);
            }
            if array_elem {
                // At most one distinct pushed rule is an ELEMENT here.
                let elem: Option<String> = ordered
                    .iter()
                    .filter_map(|alt| {
                        segmentize(alt, &self.tokens)
                            .first()
                            .and_then(|s| s.reference.clone())
                    })
                    .find(|r| !self.array_helpers.contains(r));
                if let Some(close) = &mut close {
                    for c in close.iter_mut() {
                        push_element(c, elem.as_deref(), &self.value_rules);
                    }
                }
            }
            let pre = self.pre.get();
            return self.commit_rule(&prod.name, RuleSpec { open: opens, close }, pre);
        }

        if prod.alts.len() == 1 {
            // Single-alt, multi-segment: chain rules directly on the
            // production.
            let origin = origin_of(prod).to_string();
            let nested = self.value_plan.get(&origin).cloned();
            self.emit_chain(
                &prod.name,
                &prod.alts[0],
                prod_kind,
                Some(&origin),
                prod.value.as_ref(),
                nested.as_deref(),
                prod.sp,
                array_elem,
            )?;
            return Ok(());
        }

        // A value annotation names one member per pushing segment, which
        // only has one reading when the production HAS one alternative.
        if prod.value.is_some() {
            return Err(EmitError::new(format!(
                "{}: rule '{}' has a value annotation and {} alternatives. A value \
                 annotation names the parts of ONE alternative; with more than one it \
                 is ambiguous which alternative's parts are named. Split the rule, or \
                 annotate the alternatives' own rules.",
                diag_name(),
                origin_of(prod),
                prod.alts.len()
            )));
        }

        // Multi-alt with at least one multi-segment alternative: emit a
        // dispatcher. Each alt becomes its own chained impl rule
        // (`<prodname>$alt<i>`); the main rule's open peeks the first
        // token and pushes the matching impl rule.
        let mut dispatch_entries: Vec<Entry> = Vec::new();
        let mut empty_alt_seen = false;
        let mut nullable_impls: Vec<(String, AltSpec, Option<String>)> = Vec::new();
        let dispatch_marks = if prod_kind == NodeKind::User && self.refs.emit_marks {
            Some(assign_marks(&prod.alts, &self.tokens))
        } else {
            None
        };
        let origin = origin_of(prod).to_string();

        // The ways out of this choice, for the contest check: a choice with
        // an empty alternative (or one that derives ε) can end on any token
        // that may follow it, so a content head the lexer could also read
        // as a follow token has to look further before it commits.
        let mut exit_paths: Vec<Vec<String>> = Vec::new();
        let any_epsilon = prod.alts.iter().any(|alt| {
            alt.is_empty()
                || first_of_alt(alt, &self.tokens, &self.first_sets, &self.nullable).is_none()
        });
        if any_epsilon {
            if let Some(fol) = self.follow_sets.get(&prod.name) {
                for t in fol {
                    exit_paths.push(vec![t.clone()]);
                }
            }
            if let Some(pairs) = self.follow_pairs.get(&prod.name) {
                for (t, us) in pairs {
                    for u in us {
                        exit_paths.push(vec![t.clone(), u.clone()]);
                    }
                }
            }
        }
        // What `dispatch_prefixes` returns stays held until every entry made
        // from it is written (`MAX_EMIT_UNITS`).
        let dispatch_base = self.budget.held();
        let dispatch = {
            let contest = &self.contest;
            dispatch_prefixes(
                &prod.alts,
                self.grammar,
                &self.tokens,
                LOOKAHEAD_K,
                &|a, b| contest.heads_contest(a, b),
                &exit_paths,
                &contest.class_sets,
                &self.budget,
            )?
        };

        for (i, alt) in prod.alts.iter().enumerate() {
            let impl_name = format!("{}$alt{}", prod.name, i);
            let mark = dispatch_marks.as_ref().map(|m| m[i].clone());
            if alt.is_empty() {
                // Empty alt acts as fallback, handled after the loop.
                empty_alt_seen = true;
                continue;
            }
            // One impl rule per alternative of a multi-segment dispatch:
            // the author wrote one rule with alternatives, not N rules. A
            // loop's continue alternative is `item self`, and its rule is
            // the iteration: see `emit_repeat_loop`.
            self.record_prov(&impl_name, &origin);

            if let Some(item) = &loop_item {
                self.emit_repeat_loop(prod, &impl_name, item, array_elem)?;
            } else {
                self.emit_chain(
                    &impl_name,
                    alt,
                    NodeKind::Helper,
                    Some(&origin),
                    None,
                    None,
                    None,
                    array_elem,
                )?;
            }

            // The dispatcher itself is a user (or helper) rule: it must
            // allocate its own AST node on every dispatch alt. A loop
            // hands over to its iteration in the same frame, and the
            // iteration accumulates into the node the loop's entry
            // allocated, so it allocates nothing.
            let via = if loop_item.is_none() { "p" } else { "r" };
            let mut init_dispatch_fields = AltSpec::new();
            if loop_item.is_none() {
                self.refs
                    .node(&mut init_dispatch_fields, true, &prod.name, prod_kind, 0);
            }

            // One dispatch entry per prefix this alternative needs to be
            // told apart from its rivals: its first token where that
            // decides, and deeper prefixes only under a head another
            // alternative (or the way out of the choice) shares. See
            // `dispatch_prefixes`. The entry pushes the alternative's own
            // rule, which parses it whole, so the trees are those of the
            // K-token fan-out this replaced.
            //
            // An alternative that can derive ε has no prefix for that
            // derivation. Remember it: it is re-issued as FOLLOW-guarded
            // entries plus a bare fallback, after every content entry.
            //
            // Not for a loop. An iteration whose item matched nothing
            // makes no progress, and a loop that took one would take the
            // next the same way, in the same frame, until the engine's
            // step budget ran out: a star of something that can match
            // nothing (`*[x]`) means a star of what it matches when it
            // does, and the loop's exit is its empty derivation.
            if dispatch[i].nullable && loop_item.is_none() {
                nullable_impls.push((
                    impl_name.clone(),
                    init_dispatch_fields.clone(),
                    mark.clone(),
                ));
            }
            let usable: Vec<Vec<String>> = dispatch[i].prefixes.clone();
            // `{ s, b, p, a, k?, g }`, or `{ s, b, r, g }` for a loop.
            let entry = |s: String, b: usize| {
                let mut o = AltSpec::new();
                o.set("s", s);
                o.set("b", b);
                o.set(via, impl_name.as_str());
                o.assign_from(&init_dispatch_fields);
                o.set("g", tag.as_str());
                o.m = mark.clone();
                o
            };
            if !usable.is_empty() {
                for p in usable {
                    dispatch_entries.push(Entry {
                        o: self.made(entry(p.join(" "), p.len()))?,
                        alt: Some(alt.clone()),
                    });
                }
            } else {
                let Some(first_tokens) =
                    first_of_alt(alt, &self.tokens, &self.first_sets, &self.nullable)
                else {
                    return Err(EmitError::at(
                        format!(
                            "{}: rule '{}' alternative {} is nullable but is not the only \
                             empty alt; FIRST set is ambiguous",
                            diag_name(),
                            prod.name,
                            i
                        ),
                        &prod.name,
                        prod.sp,
                    ));
                };
                for tok in &first_tokens {
                    dispatch_entries.push(Entry {
                        o: self.made(entry(tok.clone(), 1))?,
                        alt: Some(alt.clone()),
                    });
                }
            }
        }
        drop(dispatch);
        self.budget.restore(dispatch_base);

        // Re-issue each nullable alternative's ε-derivation: FOLLOW peeks
        // first, then one unguarded fallback that pushes the impl with
        // nothing consumed.
        let fol: Vec<String> = self
            .follow_sets
            .get(&prod.name)
            .map(|s| s.iter().cloned().collect())
            .unwrap_or_default();
        for (impl_name, fields, mark) in &nullable_impls {
            for tok in &fol {
                let mut o = AltSpec::new();
                o.set("s", tok.as_str());
                o.set("b", 1usize);
                o.set("p", impl_name.as_str());
                o.assign_from(fields);
                o.set("g", tag.as_str());
                o.m = mark.clone();
                dispatch_entries.push(Entry {
                    o: self.made(o)?,
                    alt: None,
                });
            }
            let mut o = AltSpec::new();
            o.set("p", impl_name.as_str());
            o.assign_from(fields);
            o.set("g", tag.as_str());
            o.m = mark.clone();
            dispatch_entries.push(Entry {
                o: self.made(o)?,
                alt: None,
            });
        }

        if empty_alt_seen {
            // Fallback: matches any token (or none), pops immediately
            // with an empty tree. A loop's exit ends the loop in the node
            // it inherited.
            let mut o = AltSpec::new();
            if loop_item.is_none() {
                self.refs.node(&mut o, true, &prod.name, prod_kind, 0);
            }
            o.set("g", tag.as_str());
            if dispatch_marks.is_some() {
                o.m = Some("_".into());
            }
            // Same FOLLOW guard as the single-segment path above.
            if prod.repeat_helper {
                for tok in &fol {
                    dispatch_entries.push(Entry {
                        o: self.made(peek_copy(&o, tok.clone(), 1))?,
                        alt: None,
                    });
                }
                let guards: Vec<Entry> = self
                    .pair_exit_guards(prod, &o)?
                    .into_iter()
                    .map(|g| Entry { o: g, alt: None })
                    .collect();
                dispatch_entries.splice(0..0, guards);
            }
            dispatch_entries.push(Entry {
                o: self.made(o)?,
                alt: None,
            });
        }

        // The impl rule this dispatches to inherits the array and fills
        // it directly, so the dispatcher allocates and captures nothing.
        if array_elem {
            for e in dispatch_entries.iter_mut() {
                use_value_actions(&mut e.o, &[], None);
            }
        }
        Self::apply_debt_guard(prod, &mut dispatch_entries);
        self.specificity_permute(&mut dispatch_entries);
        let mut opens: Vec<AltSpec> = self
            .reorder_keyword_shadow(prod, &dispatch_entries)?
            .into_iter()
            .map(|p| p.o)
            .collect();
        // A loop ends by exiting: nothing it did in its open is left to
        // capture, because the iteration captures its own item. So it has
        // no close, and registers no capture for one.
        if loop_item.is_some() {
            opens.insert(0, self.loop_entry(prod, array_elem));
            let pre = self.pre.get();
            return self.commit_rule(
                &prod.name,
                RuleSpec {
                    open: opens,
                    close: None,
                },
                pre,
            );
        }
        // Merge the chosen impl's result up into the dispatcher's node,
        // tagged with the user rule name.
        let mut disp_close = self.capture_close(&prod.name, prod_kind, None);
        if dispatch_marks.is_some() {
            disp_close.m = Some("_".into());
        }
        if array_elem {
            use_value_actions(&mut disp_close, &[], None);
        }
        let pre = self.pre.get();
        self.commit_rule(
            &prod.name,
            RuleSpec {
                open: opens,
                close: Some(vec![disp_close]),
            },
            pre,
        )
    }

    /// A repeat loop's entry, its first open alternative:
    /// `{ c: {n.rep: 0}, n: {rep: 1}, r: H, a, k?, g }`. On the way in
    /// (the counter still 0) it allocates the node every iteration
    /// accumulates into and re-enters the loop, counted. Inside an
    /// `; @array` the loop fills the array it inherits, so its entry
    /// allocates nothing and only counts.
    fn loop_entry(&mut self, prod: &Production, array_elem: bool) -> AltSpec {
        let mut o = AltSpec::new();
        o.set("c", json!({ format!("n.{LOOP_COUNTER}"): 0 }));
        o.set("n", json!({ LOOP_COUNTER: 1 }));
        o.set("r", prod.name.as_str());
        self.refs.node(&mut o, true, &prod.name, prod.node_kind, 0);
        o.set("g", self.tag.as_str());
        if array_elem {
            use_value_actions(&mut o, &[], None);
        }
        o
    }

    /// Emit a repeat loop's iteration: the rule the loop's continue
    /// alternative hands over to, which takes one item and comes back.
    ///
    /// ```text
    /// H             open   {c: {n.rep: 0}, n: {rep: 1}, r: H}   the entry: allocate
    ///                      {s: <prefix>, b: <n>, r: H$alt0} …    continue (dispatch)
    ///                      {s: <follow>, b: 1} … {}              exit
    /// H$alt0        open   {p: item, n: {rep: 0}}                push the item
    ///               close  {r: H$alt0$step1, n: {rep: 1}}        capture it
    /// H$alt0$step1  open   {r: H}                                back to the loop
    /// ```
    ///
    /// Every one of those is the frame the loop was pushed into: `H`
    /// hands over by replacement, the iteration replaces itself with its
    /// step and the step with `H`. The item is the only push, so rule
    /// depth over the whole repetition is what one item needs. The names
    /// are the ones the continue alternative `item H` always compiled to
    /// (`$alt0` pushing the item, `$step1` its self-reference), and only
    /// the self-reference has changed, from a push to a replace.
    ///
    /// A loop whose item is a terminal needs none of this: its continue
    /// alternative matches the item and re-enters the loop directly
    /// (`{s: item, r: H}`).
    ///
    /// The entry consumes nothing and names the loop itself, so for what
    /// the grammar recognises it does nothing: it allocates and counts. A
    /// reader that renders a spec back to a notation and ignores
    /// conditions has to skip it, or it reads as the loop being one of its
    /// own alternatives (`H = [ H / H$alt0 ]`), a cycle that recognises
    /// less once recompiled.
    fn emit_repeat_loop(
        &mut self,
        lp: &Production,
        name: &str,
        item: &Element,
        array_elem: bool,
    ) -> Result<(), EmitError> {
        let Kind::Ref {
            name: item_name, ..
        } = &item.kind
        else {
            return Err(EmitError::new(format!(
                "{}: internal — repeat loop '{}' dispatches a terminal item through an \
                 iteration rule",
                diag_name(),
                lp.name
            )));
        };
        let step = format!("{name}$step1");
        self.record_prov(&step, origin_of(lp));
        let tag = self.tag.clone();
        let mut take = AltSpec::new();
        take.set("p", item_name.as_str());
        take.set("n", json!({ LOOP_COUNTER: 0 }));
        take.set("g", tag.as_str());
        let mut back = AltSpec::new();
        back.set("r", step.as_str());
        back.set("n", json!({ LOOP_COUNTER: 1 }));
        self.refs.capture(&mut back, name, NodeKind::Helper);
        back.set("g", tag.as_str());
        // Inside an `; @array` the item is an element, unless it is a
        // helper that fills the same array itself.
        if array_elem {
            let elem = if self.array_helpers.contains(item_name) {
                None
            } else {
                Some(item_name.as_str())
            };
            push_element(&mut back, elem, &self.value_rules);
        }
        self.commit_rule(
            name,
            RuleSpec {
                open: vec![take],
                close: Some(vec![back]),
            },
            0,
        )?;
        let mut again = AltSpec::new();
        again.set("r", lp.name.as_str());
        again.set("g", tag.as_str());
        self.commit_rule(
            &step,
            RuleSpec {
                open: vec![again],
                close: None,
            },
            0,
        )
    }

    /// Emit a (possibly single-step) chain of rules for one alt under the
    /// given head rule name. Segment 0 goes into `head_name`; later
    /// segments get synthetic `<head_name>$stepN` continuations, always
    /// helpers, which inherit and accumulate into the head's node via
    /// `r:` replacement.
    #[allow(clippy::too_many_arguments)]
    fn emit_chain(
        &mut self,
        head_name: &str,
        alt: &[Rc<Element>],
        head_kind: NodeKind,
        origin: Option<&str>,
        value: Option<&ValueAnnotation>,
        // One flag per pushing part of `alt`: does that part's own rule
        // build a value, and so nest whole rather than resolve to text?
        nested: Option<&[bool]>,
        sp: Option<SrcSpan>,
        // This chain is a helper INSIDE an annotated array: it inherits
        // that array rather than allocating a node.
        array_elem: bool,
    ) -> Result<(), EmitError> {
        let tag = self.tag.clone();
        let segs = segmentize(alt, &self.tokens);
        let chain_name = |i: usize| -> String {
            if i == 0 {
                head_name.to_string()
            } else {
                format!("{head_name}$step{i}")
            }
        };

        // Value building rides on the segments that PUSH: those are the
        // parts that produce a member.
        let member_segs: Vec<bool> = if value.is_some() {
            segs.iter().map(|s| s.reference.is_some()).collect()
        } else {
            Vec::new()
        };
        let member_at = |i: usize| -> Option<usize> {
            if member_segs.get(i).copied().unwrap_or(false) {
                Some(member_segs[..i].iter().filter(|m| **m).count())
            } else {
                None
            }
        };
        let diag_rule = origin.unwrap_or(head_name);

        if let Some(v) = value {
            // An unknown kind must not fall through as an object.
            if v.kind != "object" && v.kind != "array" {
                return Err(EmitError::at(
                    format!(
                        "{}: rule '{}' has a value annotation of unknown kind '{}'. A rule \
                         builds an 'object' or an 'array'.",
                        diag_name(),
                        diag_rule,
                        v.kind
                    ),
                    diag_rule,
                    sp,
                ));
            }
            let pushes = member_segs.iter().filter(|m| **m).count();
            // One name per pushing segment, or the names line up with
            // the wrong parts.
            if v.kind == "object" {
                let named = v.members.len();
                if named != pushes {
                    return Err(EmitError::at(
                        format!(
                            "{}: rule '{}' names {} member{} but builds {}. A value \
                             annotation names one member per part that produces a value. A \
                             part made only of literals produces none — and note that a \
                             part whose own rule is a single terminal stops being a part \
                             here in two ways: as a LEADING part it is folded into this \
                             rule by left-recursion elimination, and anywhere else it \
                             becomes a named lexer token. Giving that rule a body that is \
                             not a bare terminal (a repetition, a group, or more than one \
                             element) keeps it nameable.",
                            diag_name(),
                            diag_rule,
                            named,
                            if named == 1 { "" } else { "s" },
                            pushes
                        ),
                        diag_rule,
                        sp,
                    ));
                }
            }
            // The same count, checked against the PLAN rather than the
            // names, because an array has no names.
            if let Some(nested) = nested {
                if nested.len() != pushes {
                    return Err(EmitError::at(
                        format!(
                            "{}: rule '{}' has a value annotation for {} part{} but builds \
                             {}. A rewrite pass changed how many parts of this rule produce \
                             a value, so the annotation no longer describes it. A part \
                             whose own rule is a single literal is the usual cause: it \
                             becomes a lexer token here and stops being a part at all. Give \
                             that rule a body that is not a bare terminal.",
                            diag_name(),
                            diag_rule,
                            nested.len(),
                            if nested.len() == 1 { "" } else { "s" },
                            pushes
                        ),
                        diag_rule,
                        sp,
                    ));
                }
            }
        }

        for (i, seg) in segs.iter().enumerate() {
            let name = chain_name(i);
            let kind = if i == 0 { head_kind } else { NodeKind::Helper };
            // Only the head of the chain initialises the node object;
            // later steps inherit and continue to accumulate into it.
            let mut head_alt = self.segment_to_alt(seg, i == 0, &name, kind);
            // Single-alt user rule: the head alt is user-addressable.
            if i == 0 && head_kind == NodeKind::User && self.refs.emit_marks {
                head_alt.m = Some(alt_discriminator(alt, &self.tokens));
            }

            // Step rules exist only because the alternative had more than
            // one segment; nothing in the author's grammar is named after
            // them.
            if i > 0 {
                if let Some(origin) = origin {
                    self.record_prov(&name, origin);
                }
            }

            let is_last = i == segs.len() - 1;
            let mut close: Option<Vec<AltSpec>> = None;
            if !is_last {
                // After the push returns, capture the child's node and
                // replace with the next step rule.
                let next = chain_name(i + 1);
                close = Some(vec![self.capture_close(&name, kind, Some(&next))]);
            } else if seg.reference.is_some() {
                // Last step with a push: capture the final child before
                // popping.
                close = Some(vec![self.capture_close(&name, kind, None)]);
            }

            if array_elem {
                use_value_actions(&mut head_alt, &[], None);
                let elem: Option<String> = seg
                    .reference
                    .as_ref()
                    .filter(|r| !self.array_helpers.contains(*r))
                    .cloned();
                if let Some(close) = &mut close {
                    for c in close.iter_mut() {
                        push_element(c, elem.as_deref(), &self.value_rules);
                    }
                }
            }

            if let Some(v) = value {
                let is_array = v.kind == "array";
                let m = member_at(i);
                let member_name: Option<&String> = m.and_then(|m| v.members.get(m));

                // Open side: the container is allocated once, on the
                // head; every pushing link names the member it fills.
                let mut open_acts: Vec<&str> = Vec::new();
                let mut open_cfg: Map<String, Value> = Map::new();
                if i == 0 {
                    open_acts.push(if is_array { "@array$" } else { "@object$" });
                }
                if !is_array {
                    if let Some(member_name) = member_name {
                        // The key is a CONSTANT: the author named this part.
                        open_acts.push("@key$");
                        open_cfg.insert("key$".into(), json!({ "lit": member_name }));
                    }
                }
                // Unconditional: EVERY link of a value rule must lose its
                // tree builders, not just the ones that gain value
                // builders.
                use_value_actions(&mut head_alt, &open_acts, Some(open_cfg));

                // Close side: a member that builds its OWN value is
                // assigned whole, so it nests; anything else resolves to
                // its source text. A part that is sugar under an array
                // fills the array itself, so this link only sheds its
                // tree builders.
                let fills = is_array
                    && seg
                        .reference
                        .as_ref()
                        .is_some_and(|r| self.array_helpers.contains(r));
                match m {
                    Some(m) if !fills => {
                        let is_nested = nested.is_some_and(|n| n.get(m).copied().unwrap_or(false));
                        let act = if is_array { "@push$" } else { "@setval$" };
                        let cfg = if is_nested {
                            None
                        } else {
                            let mut c = Map::new();
                            c.insert(
                                if is_array { "push$" } else { "setval$" }.into(),
                                json!({ "src": true }),
                            );
                            Some(c)
                        };
                        let close = close.get_or_insert_with(|| vec![AltSpec::with_tag(&tag)]);
                        for c in close.iter_mut() {
                            use_value_actions(c, &[act], cfg.clone());
                        }
                    }
                    _ => {
                        // A link that pushes nothing contributes no
                        // member, but its close still carries a tree
                        // capture for a node this rule no longer has.
                        if let Some(close) = &mut close {
                            for c in close.iter_mut() {
                                use_value_actions(c, &[], None);
                            }
                        }
                    }
                }
            }
            self.commit_rule(
                &name,
                RuleSpec {
                    open: vec![head_alt],
                    close,
                },
                0,
            )?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn term(lit: &str) -> Element {
        Element::term(lit)
    }
    fn reference(name: &str) -> Element {
        Element::reference(name)
    }
    fn at(s: usize, e: usize, r: usize, c: usize) -> SrcSpan {
        SrcSpan::at(s, e, r, c)
    }

    // A production is REBUILT by several passes, so a new field is
    // silently lost unless every one of them carries it across. The
    // grammar is shaped so that each rebuilding pass has a spanned
    // production to mangle:
    //
    //   doc   probe dispatch     rewrite_probe_dispatches' rebuild
    //   expr  direct left rec.   eliminate_direct_left_rec's star return
    //   lead  leading ref        substitute_leading_ref
    //   triv  trivial self-ref   eliminate_direct_left_rec's seeds-only return
    //   all                      the working copy, desugar
    //
    // Every one of them must come out the far end still knowing where the
    // author wrote it. Mirrors go/bnf_test.go
    // TestProductionSpansSurviveTheRewritePasses.
    #[test]
    fn production_spans_survive_the_rewrite_passes() {
        let want: IndexMap<&str, SrcSpan> = IndexMap::from([
            ("doc", at(0, 24, 1, 1)),
            ("x", at(24, 40, 2, 1)),
            ("y", at(40, 56, 3, 1)),
            ("expr", at(56, 80, 4, 1)),
            ("lead", at(80, 96, 5, 1)),
            ("triv", at(96, 112, 6, 1)),
        ]);
        let spanned = |name: &str, alts: Vec<ir::Sequence>| ir::Production {
            sp: Some(want[name]),
            ..ir::Production::new(name, alts)
        };
        let opt_group = Element::opt(Element::group(vec![vec![reference("x"), term("@")]]));
        let g = ir::Grammar::new(vec![
            // The optional prefix shares vocabulary with the tail, so the
            // probe rewriter rebuilds `doc`.
            spanned("doc", vec![vec![opt_group, reference("y")]]),
            spanned("x", vec![vec![term("a")], vec![term("b")]]),
            spanned("y", vec![vec![term("a")], vec![term("c")]]),
            spanned(
                "expr",
                vec![
                    vec![reference("expr"), term("+"), reference("x")],
                    vec![reference("x")],
                ],
            ),
            // A leading reference Paull's substitution inlines.
            spanned("lead", vec![vec![reference("expr"), term("!")]]),
            // A trivial self-reference, dropped rather than eliminated.
            spanned("triv", vec![vec![reference("triv")], vec![term("z")]]),
        ]);

        // The rewrite pipeline emit_grammar_spec runs, in its order.
        let start = "doc";
        let mut out = Grammar::from_ir(&g);
        resolve_prose_terminals(&mut out).expect("prose");
        lift_literal_tokens(&mut out, start);
        normalize_builtin_tokens(&mut out);
        let out = eliminate_left_recursion_keeping(&out, &IndexSet::new())
            .expect("left recursion")
            .into_grammar();
        let out = rewrite_probe_dispatches(&out, &EmitBudget::new()).expect("probe");
        let out = left_factor(&out).expect("factor");
        let out = rewrite_tail_repeats(out, start);
        let out = desugar(&out);

        for (name, sp) in &want {
            let p = out
                .find(name)
                .unwrap_or_else(|| panic!("rule {name:?} did not survive the rewrite passes"));
            assert_eq!(
                p.sp,
                Some(*sp),
                "rule {name:?}: a rebuild site dropped its span"
            );
        }
        // The probe rewriter must actually have fired, or `doc` proves
        // nothing about its rebuild site.
        assert!(
            out.productions.iter().any(|p| p.probe_dispatch.is_some()),
            "no probe dispatcher was synthesised"
        );
        // Synthesised productions locate themselves by origin, not by a
        // span the author never wrote.
        for p in &out.productions {
            if p.origin.is_some() {
                assert!(
                    p.sp.is_none(),
                    "synthesised rule {:?} carries a span",
                    p.name
                );
            }
        }
        // The caller's own IR is untouched.
        for p in &g.productions {
            assert_eq!(p.sp, Some(want[p.name.as_str()]));
        }
    }

    // The memos of token pairs keep no more than `MAX_MEMO_ENTRIES`, and
    // past it a pair is answered without being kept, which changes no
    // answer: each spec below is the same with the limit lifted and with a
    // memo that keeps nothing. Mirrors ts/test/emit-limit.test.js.
    fn pure_text(g: &ir::Grammar) -> String {
        let opts = ConvertOptions {
            builtins: true,
            ..ConvertOptions::tag("x")
        };
        let spec = emit_grammar_spec(g, &opts).expect("the grammar compiles");
        let pure = crate::spec::to_pure_spec(&spec).expect("a pure spec");
        crate::spec::to_jsonic(
            &pure,
            crate::spec::JsonicOptions {
                strict: true,
                indent: None,
            },
        )
    }

    fn same_under_any_memo_limit(g: &ir::Grammar) {
        let kept = pure_text(g);
        let was = crate::budget::set_memo_limit(usize::MAX);
        let unlimited = pure_text(g);
        crate::budget::set_memo_limit(0);
        let none = pure_text(g);
        crate::budget::set_memo_limit(was);
        assert!(unlimited == kept, "the spec differs with no limit");
        assert!(none == kept, "the spec differs keeping nothing");
    }

    fn sens(lit: &str) -> Element {
        Element::term_cs(lit, true)
    }

    #[test]
    fn the_memo_limit_changes_no_output_when_a_rule_asks_more_pairs_than_it_keeps() {
        // A rule of 400 two-segment alternatives with distinct heads goes to
        // the dispatcher, whose contested-head scan asks 79,800 pairs, past
        // the 65,536 kept.
        let a = ir::Production::new(
            "A",
            (0..400)
                .map(|i| vec![sens(&format!("k{i:06}")), reference("B"), sens("e")])
                .collect(),
        );
        let b = ir::Production::new("B", vec![vec![sens("b")], vec![sens("c")]]);
        same_under_any_memo_limit(&ir::Grammar::new(vec![a, b]));
    }

    #[test]
    fn the_memo_limit_changes_no_output_when_the_keyword_shadow_ordering_passes_it() {
        // 300 literal heads against 300 class heads, every pair overlapping:
        // 90,000 answers.
        let mut alts: Vec<ir::Sequence> = (0..300)
            .map(|i| vec![sens(&format!("a{i}")), reference("B")])
            .collect();
        alts.extend((0..300u32).map(|i| {
            let pattern = format!("[a-{}]", char::from_u32(0x101 + i).expect("a code point"));
            vec![Element::regex(pattern, "u"), reference("B")]
        }));
        let a = ir::Production::new("A", alts);
        let b = ir::Production::new("B", vec![vec![sens("b")]]);
        same_under_any_memo_limit(&ir::Grammar::new(vec![a, b]));
    }
}