tabnas-expr 0.6.3

Pratt expression-operator plugin for the tabnas parsing engine, over the jsonic base grammar
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
/* Copyright (c) 2021-2026 Richard Rodger and other contributors, MIT License */

//! Pratt expression-operator plugin for the
//! [tabnas](https://github.com/tabnas/parser) parser engine, layered on the
//! [jsonic](https://github.com/tabnas/jsonic) relaxed-JSON base grammar.
//!
//! The algorithm is Pratt parsing, and draws heavily from the explanation
//! written by Aleksey Kladov at
//! <https://matklad.github.io/2020/04/13/simple-but-powerful-pratt-parsing.html>.
//! See [`prattify`] for the core.
//!
//! Expressions parse into LISP-style S-expressions: an array whose first
//! element describes the operator and whose remaining elements are the
//! operand terms, so `1+2*3` becomes `["+", 1, ["*", 2, 3]]` once the
//! operator descriptions are reduced to their source text. A caller
//! supplied evaluator can reduce the tree to a value during the parse.
//!
//! TypeScript is canonical: `ts/src/expr.ts` defines the behaviour, the
//! option names, the defaults and the order of alternates. The shared
//! fixtures in `test/spec/*.tsv` are the parity contract across
//! TypeScript, Go and Rust.
//!
//! ```
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let value = tabnas_expr::parse("a:1+2*3")?;
//!     assert_eq!(tabnas_expr::simplify(&value).to_string(),
//!                r#"{"a":["+",1,["*",2,3]]}"#);
//!     Ok(())
//! }
//! ```
//!
//! # Folding a finished tree
//!
//! A key operator ([`OpDef::key()`]) is an operation spelled as a map, a
//! `$ref` say, recognised by the map's shape when [`fold`] walks a
//! finished document and reduces each occurrence through a resolver, with
//! the rest of the tree in reach through its [`Site`]. One fold can reduce
//! the token operators too, on the live expression nodes inside
//! [`parse_scope`]; a realized operator array is plain data to it.
//!
//! # Untrusted input
//!
//! A parsed expression is data, never instructions. This plugin reads
//! expression text of unknown provenance and returns S-expressions for a
//! caller supplied evaluator to reduce, and that hand-off is where hostile
//! input could become execution. Treat every operand and operator as
//! untrusted text, and never let a document select which evaluator or
//! operator implementation runs.

// The engine's error type is large by design (it carries the whole
// rendered report), and the engine allows this lint at its own crate root
// for the same reason.
#![allow(clippy::result_large_err)]

use std::cell::{Cell, RefCell};
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::rc::Rc;
use std::sync::{Arc, OnceLock};

use indexmap::IndexMap;

use tabnas::{
    AltMatch, AltSpec, Context, ListRef, Plugin, PluginError, Rule, RuleSnapshot, RuleSpec, Tabnas,
    TabnasError, Tin, Token, Value, TIN_CA, TIN_CB, TIN_CL, TIN_CS, TIN_NR, TIN_OB, TIN_OS, TIN_ST,
    TIN_TX, TIN_VL, TIN_ZZ,
};

/// VERSION is this crate's version. It MUST equal `ts/package.json`
/// "version" and the `version` field in `rs/Cargo.toml`: the release
/// orchestrator rewrites all of them, and `tests/version_test.rs` fails
/// the build if they drift. Mirrors `VERSION` in `ts/src/expr.ts` and
/// `const VERSION` in `go/expr.go`.
pub const VERSION: &str = "0.6.3";

/// The name this plugin registers under.
pub const PLUGIN_NAME: &str = "Expr";

/// The README's Rust examples run as doctests, so a stale one fails the
/// gate rather than misleading the reader. Its `toml` and `bash` fences
/// are skipped; rustdoc runs only the `rust` ones.
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
mod readme_examples {}

/// The error a failed parse produces, re-exported so callers need not
/// depend on the engine crate directly.
pub use tabnas::TabnasError as ExprError;

// The tree layer: key operators and the fold over a finished tree.
mod tree;

pub use tree::{
    fold, key_op_of, make_key_map, FoldCycle, FoldDynamic, FoldEntry, FoldError, FoldEvaluate,
    FoldHit, FoldOptions, FoldReport, Inherit, KeyMap, Load, Path, Positions, Recognise, Seg, Site,
    FOLD_CYCLE, FOLD_DEPTH, FOLD_INHERIT, FOLD_KEY, FOLD_MAX_STACK, FOLD_OPTION,
};

/// JavaScript's `Number.MIN_SAFE_INTEGER`, the binding power an operator
/// with no declared `left` takes: it binds loosest on the left.
pub const MIN_SAFE_INTEGER: i64 = -9_007_199_254_740_991;

/// JavaScript's `Number.MAX_SAFE_INTEGER`, the binding power an operator
/// with no declared `right` takes: it binds tightest on the right.
pub const MAX_SAFE_INTEGER: i64 = 9_007_199_254_740_991;

// ---------------------------------------------------------------------------
// Operator model
// ---------------------------------------------------------------------------

/// Paren preval configuration: whether a value may precede the opening
/// paren (`foo(1)`, `a[1]`), whether one is required, and which values are
/// allowed to.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PrevalDef {
    pub active: bool,
    pub required: bool,
    pub allow: Option<Vec<String>>,
}

/// A paren operator's content: whether it may be empty, and whether it is
/// a list of terms separated by commas.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ContentDef {
    /// The content may not be empty: `()` is refused, while a call that
    /// admits none stays `f()`.
    pub required: bool,
    /// The content is a list of terms separated by commas, as a call's
    /// arguments are, and each is a term of the operator (`f(a, b)` is
    /// `[f, a, b]` under a call), so an infix operator on `,` does not
    /// apply directly inside it.
    pub separated: bool,
}

/// A cast's test of a group's content: whether the group before an
/// operand, `(int)` in `(int)a`, is a cast. It sees the content as the
/// parse built it, an expression node or a value. The Rust spelling of the
/// canonical `accept`.
#[derive(Clone)]
pub struct Accept(Arc<dyn Fn(&Value) -> bool + Send + Sync>);

impl Accept {
    /// Wrap a test of a group's content.
    pub fn new(test: impl Fn(&Value) -> bool + Send + Sync + 'static) -> Self {
        Accept(Arc::new(test))
    }

    /// Whether the test accepts this content.
    pub fn accepts(&self, term: &Value) -> bool {
        (self.0)(term)
    }
}

impl fmt::Debug for Accept {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("Accept(<function>)")
    }
}

/// Two tests are equal when they are the same function.
impl PartialEq for Accept {
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.0, &other.0)
    }
}

/// One entry of the `op` option map: the definition of an operator.
///
/// `src` carries one source string for a prefix, suffix or infix
/// operator and two for a ternary (`["?", ":"]`); a paren operator uses
/// `osrc` and `csrc` instead. A key operator's `src` is the member name
/// that marks a site, `$ref` say.
#[derive(Debug, Clone, PartialEq)]
pub struct OpDef {
    pub src: Vec<String>,
    pub osrc: String,
    pub csrc: String,
    pub left: Option<i64>,
    pub right: Option<i64>,
    pub prefix: bool,
    pub suffix: bool,
    pub infix: bool,
    pub ternary: bool,
    pub paren: bool,
    pub preval: Option<PrevalDef>,
    /// Custom operator data, handed back to an evaluator as `op.use`.
    pub use_data: Value,
    /// A STRUCTURAL operator: an occurrence is a map that owns the member
    /// named by `src`, recognised by its shape when a tree is folded
    /// ([`fold`]), never by a token. No fixed token is registered for it,
    /// so the base grammar keeps the key position, and no binding power
    /// applies: its two terms are fixed by the shape, the member's value
    /// and the map of the other members.
    pub key: bool,
    /// A key operator a fold recognises and reports but never evaluates,
    /// such as `$dynamicRef`, whose meaning depends on a scope the parser
    /// does not have. Its map folds as a plain map.
    pub dynamic: bool,
    /// A paren operator's content: see [`ContentDef`].
    pub content: ContentDef,
    /// An infix operator on `,` that gives way to the separator: wherever
    /// an enclosing context separates on `,` (a list, a map, or a paren
    /// whose content is separated) the comma separates, and only elsewhere
    /// is it this operator. A group is such an elsewhere, even inside a
    /// call.
    pub separator: bool,
    /// A CAST: a prefix operator whose token is a group (`(int)` in
    /// `(int)a`) that `accept` accepts. `osrc` and `csrc` name the group,
    /// which a paren operator of the table on the same opener and closer
    /// parses; `right` is the cast's binding power, as a prefix's; `src`,
    /// by default `osrc` and `csrc` together, is what [`simplify`] writes.
    /// The operation's terms are the group's content and the operand. A
    /// group `accept` refuses stays a group, or a call, and a cast without
    /// `accept` accepts nothing.
    pub cast: bool,
    /// A cast's test of the group's content: see [`Accept`].
    pub accept: Option<Accept>,
}

impl Default for OpDef {
    fn default() -> Self {
        OpDef {
            src: Vec::new(),
            osrc: String::new(),
            csrc: String::new(),
            left: None,
            right: None,
            prefix: false,
            suffix: false,
            infix: false,
            ternary: false,
            paren: false,
            preval: None,
            use_data: Value::Undefined,
            key: false,
            dynamic: false,
            content: ContentDef::default(),
            separator: false,
            cast: false,
            accept: None,
        }
    }
}

impl OpDef {
    /// An infix operator with the given source and binding powers.
    pub fn infix(src: impl Into<String>, left: i64, right: i64) -> Self {
        OpDef {
            src: vec![src.into()],
            infix: true,
            left: Some(left),
            right: Some(right),
            ..Default::default()
        }
    }

    /// A prefix operator with the given source and right binding power.
    pub fn prefix(src: impl Into<String>, right: i64) -> Self {
        OpDef {
            src: vec![src.into()],
            prefix: true,
            right: Some(right),
            ..Default::default()
        }
    }

    /// A suffix operator with the given source and left binding power.
    pub fn suffix(src: impl Into<String>, left: i64) -> Self {
        OpDef {
            src: vec![src.into()],
            suffix: true,
            left: Some(left),
            ..Default::default()
        }
    }

    /// A ternary operator with its two source strings.
    ///
    /// A ternary with a binding power on its left (`with_left`) is placed
    /// as an infix operator is, its middle term between its two tokens and
    /// its last term an operand on its right (`with_right`): `x = a ? b : c`
    /// is `x = (a ? b : c)` where the ternary binds tighter than `=`, and an
    /// operator after the last term binds into it, or takes the whole
    /// ternary, by the same comparison. The middle term is a whole
    /// expression of its own, in which a comma is the comma operator even
    /// where the context separates on commas. A ternary with no `left`
    /// takes the whole expression before it, and the whole one after it.
    pub fn ternary(first: impl Into<String>, second: impl Into<String>) -> Self {
        OpDef {
            src: vec![first.into(), second.into()],
            ternary: true,
            ..Default::default()
        }
    }

    /// A paren operator with its opening and closing source strings.
    ///
    /// Two paren operators may share an opener: a group, whose preval is
    /// inactive, and a call or a subscript, whose preval is active. A value
    /// before the opener selects the preval operator and no value the
    /// group, so `(e)` and `e()` reach an evaluator as different
    /// operators. Of two of one kind on an opener the later declared
    /// applies, and an opener with no group uses an operator whose preval
    /// is active and not required for both forms. The default `plain` is
    /// left out of a table that has another paren operator on `(` and
    /// `)`, unless the options change it.
    pub fn paren(osrc: impl Into<String>, csrc: impl Into<String>) -> Self {
        OpDef {
            osrc: osrc.into(),
            csrc: csrc.into(),
            paren: true,
            ..Default::default()
        }
    }

    /// A key operator: a map that owns the member `src` is an occurrence
    /// of it when a tree is folded.
    pub fn key(src: impl Into<String>) -> Self {
        OpDef {
            src: vec![src.into()],
            key: true,
            ..Default::default()
        }
    }

    /// A dynamic key operator: recognised and reported by a fold, never
    /// evaluated.
    pub fn dynamic_key(src: impl Into<String>) -> Self {
        OpDef {
            dynamic: true,
            ..OpDef::key(src)
        }
    }

    /// A cast on the group `osrc` `csrc`, with the binding power `right`,
    /// whose content `accept` tests: see [`OpDef::cast`](OpDef#structfield.cast).
    pub fn cast(
        osrc: impl Into<String>,
        csrc: impl Into<String>,
        right: i64,
        accept: impl Fn(&Value) -> bool + Send + Sync + 'static,
    ) -> Self {
        OpDef {
            osrc: osrc.into(),
            csrc: csrc.into(),
            right: Some(right),
            cast: true,
            accept: Some(Accept::new(accept)),
            ..Default::default()
        }
    }

    /// Give a paren operator a preval configuration.
    pub fn with_preval(mut self, preval: PrevalDef) -> Self {
        self.preval = Some(preval);
        self
    }

    /// Give a preval paren a binding power, compared like a suffix's with
    /// the operator whose operand precedes it: where the paren binds no
    /// tighter, it takes that operator's expression (`a.b[1]` is
    /// `(a.b)[1]`). Unset, the paren binds to the value just before it.
    pub fn with_left(mut self, left: i64) -> Self {
        self.left = Some(left);
        self
    }

    /// Give an operator its right binding power: a ternary's, which with a
    /// left one (`with_left`) places it as an infix operator is (see
    /// [`OpDef::ternary`]).
    pub fn with_right(mut self, right: i64) -> Self {
        self.right = Some(right);
        self
    }

    /// Give a paren operator a content configuration: see [`ContentDef`].
    pub fn with_content(mut self, content: ContentDef) -> Self {
        self.content = content;
        self
    }

    /// Make an infix operator on `,` give way to separators: see
    /// [`OpDef::separator`](OpDef#structfield.separator).
    pub fn with_separator(mut self) -> Self {
        self.separator = true;
        self
    }

    /// Attach custom operator data, handed back to an evaluator.
    pub fn with_use(mut self, use_data: Value) -> Self {
        self.use_data = use_data;
        self
    }
}

/// The full operator description carried by a parsed expression and handed
/// to an evaluator.
#[derive(Debug, Clone, PartialEq)]
pub struct Op {
    pub name: String,
    pub src: String,
    pub left: i64,
    pub right: i64,
    pub use_data: Value,
    pub prefix: bool,
    pub suffix: bool,
    pub infix: bool,
    pub ternary: bool,
    pub paren: bool,
    pub terms: usize,
    pub tkn: String,
    pub tin: Tin,
    pub osrc: String,
    pub csrc: String,
    pub otkn: String,
    pub otin: Tin,
    pub ctkn: String,
    pub ctin: Tin,
    pub preval: PrevalDef,
    /// Which of a ternary's two source strings this operator is, as the
    /// canonical `use.ternary.opI`. `None` for every other operator.
    pub ternary_index: Option<usize>,
    /// A key operator, recognised by a map's shape when a tree is folded:
    /// see [`OpDef::key()`] and [`fold`].
    pub key: bool,
    /// A key operator a fold reports and never evaluates: see
    /// [`OpDef::dynamic`].
    pub dynamic: bool,
    /// A paren operator's content: see [`ContentDef`].
    pub content: ContentDef,
    /// An infix operator on `,` that gives way to separators: see
    /// [`OpDef::separator`](OpDef#structfield.separator).
    pub separator: bool,
    /// A cast, whose token is a group: see
    /// [`OpDef::cast`](OpDef#structfield.cast).
    pub cast: bool,
    /// A cast's test of the group's content.
    pub accept: Option<Accept>,
}

impl Default for Op {
    fn default() -> Self {
        Op {
            name: String::new(),
            src: String::new(),
            left: MIN_SAFE_INTEGER,
            right: MAX_SAFE_INTEGER,
            use_data: Value::Undefined,
            prefix: false,
            suffix: false,
            infix: false,
            ternary: false,
            paren: false,
            terms: 0,
            tkn: String::new(),
            tin: -1,
            osrc: String::new(),
            csrc: String::new(),
            otkn: String::new(),
            otin: -1,
            ctkn: String::new(),
            ctin: -1,
            preval: PrevalDef::default(),
            ternary_index: None,
            key: false,
            dynamic: false,
            content: ContentDef::default(),
            separator: false,
            cast: false,
            accept: None,
        }
    }
}

impl Op {
    /// The serialized operator description, with the canonical lower-case
    /// key names. `token` is the occurrence's own token, so it is supplied
    /// separately rather than carried on the shared description.
    fn to_value(&self, token: Option<&Token>) -> Value {
        let mut map: IndexMap<String, Value> = IndexMap::new();
        map.insert("src".into(), Value::String(self.src.clone()));
        map.insert("left".into(), number(self.left));
        map.insert("right".into(), number(self.right));
        map.insert("name".into(), Value::String(self.name.clone()));
        map.insert("infix".into(), Value::Bool(self.infix));
        map.insert("prefix".into(), Value::Bool(self.prefix));
        map.insert("suffix".into(), Value::Bool(self.suffix));
        map.insert("ternary".into(), Value::Bool(self.ternary));
        map.insert("tkn".into(), Value::String(self.tkn.clone()));
        map.insert("tin".into(), Value::Number(f64::from(self.tin)));
        map.insert("terms".into(), Value::Number(self.terms as f64));
        map.insert("use".into(), self.use_value());
        map.insert("paren".into(), Value::Bool(self.paren));
        map.insert("osrc".into(), Value::String(self.osrc.clone()));
        map.insert("csrc".into(), Value::String(self.csrc.clone()));
        map.insert("otkn".into(), Value::String(self.otkn.clone()));
        map.insert("ctkn".into(), Value::String(self.ctkn.clone()));
        map.insert("otin".into(), Value::Number(f64::from(self.otin)));
        map.insert("ctin".into(), Value::Number(f64::from(self.ctin)));
        map.insert("preval".into(), self.preval_value());
        // In the canonical key order: TypeScript's operator builder lists
        // `content`, `separator` and `cast` after `preval`, then `key` and
        // `dynamic`, and `token` last. A cast's `accept` is a function,
        // which JSON leaves out.
        let mut content: IndexMap<String, Value> = IndexMap::new();
        content.insert("required".into(), Value::Bool(self.content.required));
        content.insert("separated".into(), Value::Bool(self.content.separated));
        map.insert("content".into(), Value::object(content));
        map.insert("separator".into(), Value::Bool(self.separator));
        map.insert("cast".into(), Value::Bool(self.cast));
        map.insert("key".into(), Value::Bool(self.key));
        map.insert("dynamic".into(), Value::Bool(self.dynamic));
        map.insert("token".into(), token_value(token));
        Value::object(map)
    }

    fn use_value(&self) -> Value {
        let mut used: IndexMap<String, Value> = match &self.use_data {
            Value::Object(entries) => (**entries).clone(),
            _ => IndexMap::new(),
        };
        if let Some(index) = self.ternary_index {
            let mut ternary: IndexMap<String, Value> = IndexMap::new();
            ternary.insert("opI".into(), Value::Number(index as f64));
            used.insert("ternary".into(), Value::object(ternary));
        }
        Value::object(used)
    }

    fn preval_value(&self) -> Value {
        let mut preval: IndexMap<String, Value> = IndexMap::new();
        preval.insert("active".into(), Value::Bool(self.preval.active));
        preval.insert("required".into(), Value::Bool(self.preval.required));
        if let Some(allow) = &self.preval.allow {
            preval.insert(
                "allow".into(),
                Value::array(allow.iter().cloned().map(Value::String).collect()),
            );
        }
        Value::object(preval)
    }
}

/// A binding power as a `Value`. The powers are integers on a scale whose
/// ends are JavaScript's safe-integer bounds, and every one of them is
/// exactly representable as an `f64`.
fn number(value: i64) -> Value {
    Value::Number(value as f64)
}

/// The occurrence token an operator carries, under the canonical key
/// names, so that an evaluator can report where a term came from.
fn token_value(token: Option<&Token>) -> Value {
    let Some(token) = token else {
        return Value::object(IndexMap::new());
    };
    let mut map: IndexMap<String, Value> = IndexMap::new();
    map.insert("isToken".into(), Value::Bool(true));
    map.insert("name".into(), Value::String(token.name.as_str().into()));
    map.insert("tin".into(), Value::Number(f64::from(token.tin)));
    map.insert("src".into(), Value::String(token.src.as_str().into()));
    map.insert("len".into(), Value::Number(token.len as f64));
    map.insert("sI".into(), Value::Number(token.site.pos as f64));
    map.insert("rI".into(), Value::Number(token.site.ri as f64));
    map.insert("cI".into(), Value::Number(token.site.ci as f64));
    Value::object(map)
}

// ---------------------------------------------------------------------------
// Options
// ---------------------------------------------------------------------------

/// The site an evaluator is called from: the rule the reduction belongs to
/// and the live parse context, and neither when [`evaluation`] is called on
/// a finished tree.
///
/// The rule is a snapshot rather than the live rule, because the canonical
/// port hands the evaluator the PARENT of the rule that is closing, which
/// this engine exposes as a snapshot. Its state, its `u` flags and its node
/// cell are all reachable through it.
pub struct EvalSite<'a> {
    rule: Option<Rc<RuleSnapshot>>,
    context: Option<&'a mut Context>,
    token: Option<Token>,
}

impl<'a> EvalSite<'a> {
    /// A site with no live parse behind it.
    pub fn detached() -> Self {
        EvalSite {
            rule: None,
            context: None,
            token: None,
        }
    }

    /// A site inside a parse.
    pub fn new(rule: Option<Rc<RuleSnapshot>>, context: &'a mut Context) -> Self {
        EvalSite {
            rule,
            context: Some(context),
            token: None,
        }
    }

    /// The rule the reduction belongs to, when there is one.
    pub fn rule(&self) -> Option<&RuleSnapshot> {
        self.rule.as_deref()
    }

    /// The token this OCCURRENCE of the operator was matched from.
    ///
    /// The `Op` an evaluator receives is the shared description, one per
    /// entry in the operator table, so it cannot say which occurrence is
    /// being reduced. The canonical `makeOp` attaches the token to its
    /// copy of the description for exactly that reason; this port keeps
    /// the token beside the node instead, and hands it over here. The
    /// position is the engine's `Site` triple: `token.site.pos`, `.ri`
    /// (row) and `.ci` (column).
    ///
    /// It is `None` when the node was built without one, which is what
    /// [`prattify`] called directly produces.
    pub fn token(&self) -> Option<&Token> {
        self.token.as_ref()
    }

    /// The live parse context, when there is one.
    pub fn context(&mut self) -> Option<&mut Context> {
        self.context.as_deref_mut()
    }

    /// Whether the rule carries a `u` flag set to `true`. The
    /// `paren_preval` flag is what tells an evaluator that a paren
    /// operator's first term is the preceding value.
    pub fn flag(&self, name: &str) -> bool {
        self.rule
            .as_ref()
            .is_some_and(|rule| matches!(rule.u.get(name), Some(Value::Bool(true))))
    }

    /// Reborrow, so a recursive reduction passes the same site down. The
    /// token is not carried: it belongs to one occurrence, and the nested
    /// reduction sets the one it is reducing.
    fn reborrow(&mut self) -> EvalSite<'_> {
        EvalSite {
            rule: self.rule.clone(),
            context: self.context.as_deref_mut(),
            token: None,
        }
    }
}

/// Resolve the value of an operation. The Rust spelling of the canonical
/// `Evaluate` callback: it takes the operator and its already reduced
/// terms, and returns the value the expression stands for.
pub type Evaluate = Arc<dyn Fn(&mut EvalSite<'_>, &Op, &[Value]) -> Value + Send + Sync>;

/// Options for the plugin.
///
/// `op` is an insertion-ordered map, and the order matters: two operators
/// claiming the same source string resolve to the same token, and the
/// later entry wins, exactly as it does in the canonical TypeScript. A
/// `None` entry deletes an operator the defaults provide.
#[derive(Clone, Default)]
pub struct ExprOptions {
    pub op: IndexMap<String, Option<OpDef>>,
    pub evaluate: Option<Evaluate>,
    /// Values side by side, with nothing between them, inside an
    /// expression or a paren group make an implicit list, as jsonic makes
    /// one (`f(a b)` is a call of `[a, b]`). With `Some(false)` they are
    /// refused, with the engine's `unexpected`. A document's own implicit
    /// list, outside any expression, and the items of a list or a map are
    /// unchanged. `None` reads as `true`.
    pub juxtapose: Option<bool>,
    /// The value tokens of a host grammar that lexes its own (an
    /// identifier, a number), by name, beside jsonic's text, number, string
    /// and keyword values. With `juxtapose` false, one of them after a
    /// value or an expression is refused, with the engine's `unexpected`,
    /// wherever it stands: an expression never ends at one, and the rule
    /// the expression is in never sees it. The items of a list or a map
    /// are not exempt.
    pub values: Vec<String>,
    /// The most nodes one expression may hold, [`NODE_LIMIT`] when `None`.
    /// An expression past it is refused with the engine's `cancel` code.
    ///
    /// The limit keeps a realized tree shallow enough for the engine's
    /// recursive walks of a value (display, JSON, drop), which abort the
    /// process past the stack where TypeScript and Go fail or go on. A
    /// host that raises it reduces every expression with an evaluator into
    /// values of its own, whose depth it bounds itself, and never realizes
    /// or simplifies a tree past [`NODE_LIMIT`]: the parse, the placing of
    /// an operator and the evaluation walk no deeper on the call stack
    /// however large an expression grows.
    pub node_limit: Option<usize>,
}

impl fmt::Debug for ExprOptions {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ExprOptions")
            .field("op", &self.op)
            .field("evaluate", &self.evaluate.as_ref().map(|_| "<function>"))
            .field("juxtapose", &self.juxtapose)
            .field("values", &self.values)
            .field("node_limit", &self.node_limit)
            .finish()
    }
}

impl ExprOptions {
    /// Options carrying no operators of their own; the defaults still
    /// apply.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add or replace one operator definition.
    pub fn with_op(mut self, name: impl Into<String>, def: OpDef) -> Self {
        self.op.insert(name.into(), Some(def));
        self
    }

    /// Delete a default operator, the Rust spelling of `plain: null`.
    pub fn without_op(mut self, name: impl Into<String>) -> Self {
        self.op.insert(name.into(), None);
        self
    }

    /// Whether values side by side make an implicit list: see
    /// [`ExprOptions::juxtapose`].
    pub fn with_juxtapose(mut self, juxtapose: bool) -> Self {
        self.juxtapose = Some(juxtapose);
        self
    }

    /// Name a host grammar's own value tokens: see [`ExprOptions::values`].
    pub fn with_values<I, S>(mut self, values: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.values = values.into_iter().map(Into::into).collect();
        self
    }

    /// Set the most nodes one expression may hold: see
    /// [`ExprOptions::node_limit`].
    pub fn with_node_limit(mut self, limit: usize) -> Self {
        self.node_limit = Some(limit);
        self
    }

    /// Set the evaluator that reduces each expression as it closes.
    pub fn with_evaluate(
        mut self,
        evaluate: impl Fn(&mut EvalSite<'_>, &Op, &[Value]) -> Value + Send + Sync + 'static,
    ) -> Self {
        self.evaluate = Some(Arc::new(evaluate));
        self
    }

    /// Read the operator table, and `juxtapose`, out of a serialized option
    /// bag, as the engine hands it to a plugin. Unreadable entries are
    /// ignored, the way the canonical plugin ignores what it cannot use.
    pub fn from_value(options: &Value) -> Self {
        let mut resolved = ExprOptions::new();
        if let Some(Value::Bool(juxtapose)) = object_get(options, "juxtapose") {
            resolved.juxtapose = Some(*juxtapose);
        }
        if let Some(Value::Array(values)) = object_get(options, "values") {
            resolved.values = values
                .iter()
                .filter_map(|value| match value {
                    Value::String(name) => Some(name.clone()),
                    _ => None,
                })
                .collect();
        }
        let Some(op) = object_get(options, "op") else {
            return resolved;
        };
        let Value::Object(entries) = op else {
            return resolved;
        };
        for (name, def) in entries.iter() {
            match def {
                Value::Object(_) => {
                    resolved
                        .op
                        .insert(name.clone(), Some(op_def_from_value(def)));
                }
                // `plain: null` deletes a default operator.
                _ => {
                    resolved.op.insert(name.clone(), None);
                }
            }
        }
        resolved
    }
}

fn object_get<'a>(value: &'a Value, key: &str) -> Option<&'a Value> {
    match value {
        Value::Object(map) => map.get(key),
        Value::MapRef(map) => map.value.get(key),
        _ => None,
    }
}

fn value_bool(value: Option<&Value>) -> bool {
    matches!(value, Some(Value::Bool(true)))
}

fn value_i64(value: Option<&Value>) -> Option<i64> {
    match value {
        Some(Value::Number(number)) => Some(*number as i64),
        _ => None,
    }
}

fn value_string(value: Option<&Value>) -> String {
    match value {
        Some(Value::String(text)) => text.clone(),
        Some(Value::Text(text)) => text.string.clone(),
        _ => String::new(),
    }
}

fn op_def_from_value(def: &Value) -> OpDef {
    let mut out = OpDef {
        osrc: value_string(object_get(def, "osrc")),
        csrc: value_string(object_get(def, "csrc")),
        left: value_i64(object_get(def, "left")),
        right: value_i64(object_get(def, "right")),
        prefix: value_bool(object_get(def, "prefix")),
        suffix: value_bool(object_get(def, "suffix")),
        infix: value_bool(object_get(def, "infix")),
        ternary: value_bool(object_get(def, "ternary")),
        paren: value_bool(object_get(def, "paren")),
        use_data: object_get(def, "use").cloned().unwrap_or(Value::Undefined),
        key: value_bool(object_get(def, "key")),
        dynamic: value_bool(object_get(def, "dynamic")),
        separator: value_bool(object_get(def, "separator")),
        // A cast's `accept` is a function, which no serialized option bag
        // carries: give one with `OpDef::cast`.
        cast: value_bool(object_get(def, "cast")),
        ..Default::default()
    };
    if let Some(content) = object_get(def, "content") {
        out.content = ContentDef {
            required: value_bool(object_get(content, "required")),
            separated: value_bool(object_get(content, "separated")),
        };
    }
    match object_get(def, "src") {
        Some(Value::String(src)) => out.src = vec![src.clone()],
        Some(Value::Array(srcs)) => {
            out.src = srcs
                .iter()
                .map(|src| value_string(Some(src)))
                .collect::<Vec<_>>()
        }
        _ => {}
    }
    out.preval = match object_get(def, "preval") {
        None | Some(Value::Undefined) | Some(Value::Null) => None,
        Some(Value::Bool(active)) => Some(PrevalDef {
            active: *active,
            required: false,
            allow: None,
        }),
        Some(preval) => Some(PrevalDef {
            // True by default when a preval object is specified at all.
            active: match object_get(preval, "active") {
                None | Some(Value::Undefined) | Some(Value::Null) => true,
                Some(Value::Bool(active)) => *active,
                Some(_) => true,
            },
            required: value_bool(object_get(preval, "required")),
            allow: match object_get(preval, "allow") {
                Some(Value::Array(allow)) => Some(
                    allow
                        .iter()
                        .map(|entry| value_string(Some(entry)))
                        .collect::<Vec<_>>(),
                ),
                _ => None,
            },
        }),
    };
    out
}

// Default operator precedence: the "binding power" scale.
//
// Binding powers are compared only by ORDER, never by magnitude (every
// comparison in `prattify` is a `<` or `<=`): a higher number binds
// tighter. Associativity is set by left against right. Left below right is
// left-associative (`a-b-c` is `(a-b)-c`); left above right is
// right-associative. An unset left or right falls back to
// [`MIN_SAFE_INTEGER`] or [`MAX_SAFE_INTEGER`], which is why prefix
// operators give only `right` and parens give neither.
//
// The defaults occupy a compact low block on a base-1000000 ladder,
// leaving the whole range above the built-ins open for client operators.
// Tiers are 1000000 apart; the +100000 on `right` is the
// left-associativity offset, so a tier occupies a 100000-wide band inside
// its 1000000-wide slot and adjacent tiers can never overlap:
//
//    <1000000  looser client operators (assignment, ternary, logical)
//     1000000  sequence and comma
//     2000000  addition and subtraction                  built-in
//     3000000  multiplication, division, remainder       built-in
//     4000000  unary prefix                              built-in, tightest
//     5000000+ free for tighter client operators
/// The default operator table, as the plugin declares it to the engine.
pub fn defaults() -> Value {
    let mut ops: IndexMap<String, Value> = IndexMap::new();
    ops.insert("positive".into(), prefix_value("+", 4_000_000));
    ops.insert("negative".into(), prefix_value("-", 4_000_000));
    // NOTE: all of these are left-associative, as left is below right.
    // Example: 2+3+4 is (2+3)+4.
    ops.insert("addition".into(), infix_value("+", 2_000_000, 2_100_000));
    ops.insert("subtraction".into(), infix_value("-", 2_000_000, 2_100_000));
    ops.insert(
        "multiplication".into(),
        infix_value("*", 3_000_000, 3_100_000),
    );
    ops.insert("division".into(), infix_value("/", 3_000_000, 3_100_000));
    ops.insert("remainder".into(), infix_value("%", 3_000_000, 3_100_000));
    ops.insert("plain".into(), paren_value("(", ")"));

    let mut map: IndexMap<String, Value> = IndexMap::new();
    map.insert("op".into(), Value::object(ops));
    Value::object(map)
}

fn prefix_value(src: &str, right: i64) -> Value {
    let mut def: IndexMap<String, Value> = IndexMap::new();
    def.insert("prefix".into(), Value::Bool(true));
    def.insert("right".into(), number(right));
    def.insert("src".into(), Value::String(src.into()));
    Value::object(def)
}

fn infix_value(src: &str, left: i64, right: i64) -> Value {
    let mut def: IndexMap<String, Value> = IndexMap::new();
    def.insert("infix".into(), Value::Bool(true));
    def.insert("left".into(), number(left));
    def.insert("right".into(), number(right));
    def.insert("src".into(), Value::String(src.into()));
    Value::object(def)
}

fn paren_value(osrc: &str, csrc: &str) -> Value {
    let mut def: IndexMap<String, Value> = IndexMap::new();
    def.insert("paren".into(), Value::Bool(true));
    def.insert("osrc".into(), Value::String(osrc.into()));
    def.insert("csrc".into(), Value::String(csrc.into()));
    Value::object(def)
}

/// The default operator table as typed options.
fn default_ops() -> IndexMap<String, Option<OpDef>> {
    ExprOptions::from_value(&defaults()).op
}

/// Merge caller options over the defaults with the canonical semantics: a
/// name the defaults already carry is deep-merged and moves to the end of
/// the table, a new name is appended, and a `None` entry deletes.
fn resolve_options(options: &ExprOptions) -> IndexMap<String, Option<OpDef>> {
    let defaults = default_ops();
    let mut resolved = defaults.clone();
    for (name, def) in &options.op {
        resolved.shift_remove(name);
        match def {
            Some(def) => {
                resolved.insert(name.clone(), Some(def.clone()));
            }
            None => {
                resolved.insert(name.clone(), None);
            }
        }
    }

    // The default grouping paren yields to the table's own: `plain`, as
    // the defaults define it, is left out when another paren operator
    // opens with `(` and closes with `)`. Otherwise it would be that
    // opener's group beside a call the table declares there, which a
    // table that gave its call the group's job too (one paren operator
    // whose preval is active and not required) never asked for. A `plain`
    // the options change is theirs, and stays.
    if let Some(Some(plain)) = resolved.get("plain") {
        let claimed = Some(&Some(plain.clone())) == defaults.get("plain")
            && resolved.iter().any(|(name, def)| {
                "plain" != name
                    && def.as_ref().is_some_and(|def| {
                        def.paren && def.osrc == plain.osrc && def.csrc == plain.csrc
                    })
            });
        if claimed {
            resolved.shift_remove("plain");
        }
    }
    resolved
}

// ---------------------------------------------------------------------------
// The expression node arena
// ---------------------------------------------------------------------------
//
// The canonical algorithm rewrites expression nodes IN PLACE, so that every
// rule holding a node observes the rewrite: that is what keeps the overall
// AST intact while an expression is still being assembled. JavaScript gets
// that from array identity and the Go port buys it with a `*ListRef` box.
//
// The engine's `Value` is a copy-on-write tree with no interior mutability,
// so a rewrite through one holder would be invisible to the others. Nodes
// therefore live in a per-thread arena and the value that travels through
// the parse is a HANDLE: a `ListRef` carrying the node's identity under
// `meta.expr`. Cloning a handle shares the identity, which is exactly the
// property the algorithm needs, and [`realize`] turns a finished tree of
// handles into plain values at the parse boundary.
//
// A handle is a `ListRef` rather than a string because the base grammar's
// value coalescing asks whether a node is a container, and the canonical
// expression node -- a JavaScript array -- is one.

/// One expression node: the operator, the token that introduced this
/// occurrence, and the operand terms.
///
/// The operator is optional because the canonical port rewrites a
/// completed ternary into a one-element LIST in place, keeping the node's
/// identity so that every holder sees the list. A node with no operator is
/// exactly that: a plain array of its terms.
#[derive(Debug, Clone)]
struct ExprNode {
    op: Option<Arc<Op>>,
    token: Option<Token>,
    terms: Vec<Value>,
    /// The node at the top of the expression this one belongs to, or this
    /// node itself.
    ///
    /// The Pratt core only ever grows a tree DOWNWARD from its root: a
    /// looser operator rewrites the root node in place, keeping its
    /// identity, and a tighter one builds a new node under it. So the
    /// root a node was created under stays its root for the life of the
    /// expression, and recording it is what lets a rule holding a
    /// sub-expression hand the whole expression back.
    root: u64,
    /// How many nodes the expression under this root holds, counted only
    /// on a root. A tree is never deeper than it is large, so this bounds
    /// its depth: see [`NODE_LIMIT`].
    size: usize,
}

#[derive(Default)]
struct Arena {
    nodes: HashMap<u64, ExprNode>,
    next_id: u64,
    /// Parses currently running on this thread through this crate's own
    /// entry points. While one is in flight the arena must not be cleared.
    active: usize,
}

thread_local! {
    static ARENA: RefCell<Arena> = RefCell::new(Arena::default());
    /// The most nodes an expression of this parse has held. The parse
    /// budget reads it and cancels the parse once it passes the limit (see
    /// [`NODE_LIMIT`] and [`ExprOptions::node_limit`]).
    static LARGEST: Cell<usize> = const { Cell::new(0) };
}

/// The `meta` key a handle carries its node identity under.
const EXPR_META: &str = "expr";

/// The most nodes one expression may hold.
///
/// The engine walks a value with the CALL STACK to display it, convert it
/// to JSON or drop it, so a deeply nested result aborts the process rather
/// than failing: a flat sum of a few thousand terms builds a tree as deep
/// as it is long, and an abort is not something a caller can catch. An
/// expression past this size is refused with the engine's `cancel` code
/// instead, which is a recorded divergence (`../DIVERGENCE.md`):
/// TypeScript raises a JavaScript `RangeError` of its own a few thousand
/// terms later, and Go grows its stacks and keeps going. The number is
/// the one the jsonic base grammar already applies to nested containers,
/// so a document cannot nest deeper than this anyway.
pub const NODE_LIMIT: usize = 127;

/// The deepest rule stack a parse may reach.
///
/// [`NODE_LIMIT`] bounds an expression that is being BUILT, and an
/// unterminated one builds nothing: `((((` with no closer pushes a rule
/// frame per level and never reaches the limit, and the engine's cost per
/// step grows with the stack, so the parse turned quadratic. The base
/// grammar bounds its own nesting for the same reason, and the deepest
/// document it accepts, 127 nested containers, measures 378 frames, so
/// this one sits well above anything it lets through. Past it a parse is
/// refused with the engine's `cancel` code.
pub const RULE_LIMIT: usize = 1024;

/// Read a handle's node identity.
fn node_id(value: &Value) -> Option<u64> {
    let Value::ListRef(list) = value else {
        return None;
    };
    match list.meta.get(EXPR_META) {
        Some(Value::Number(id)) => Some(*id as u64),
        _ => None,
    }
}

/// Whether a value is an expression node, the port of the canonical
/// `isOp`.
pub fn is_op(value: &Value) -> bool {
    op_of(value).is_some()
}

/// The number of elements a node presents, the canonical `node.length`:
/// the operator plus its terms for an expression, and the terms alone for
/// a node rewritten into a plain list.
fn node_length(value: &Value) -> usize {
    if let Some(length) = with_node(value, |entry| {
        entry.terms.len() + usize::from(entry.op.is_some())
    }) {
        return length;
    }
    match value {
        Value::Array(entries) => entries.len(),
        Value::ListRef(list) => list.value.len(),
        _ => 0,
    }
}

fn is_op_kind(value: &Value, kind: fn(&Op) -> bool) -> bool {
    op_of(value).is_some_and(|op| kind(&op))
}

fn is_paren_op(value: &Value) -> bool {
    is_op_kind(value, |op| op.paren)
}

/// The operator heading an expression node.
pub fn op_of(value: &Value) -> Option<Arc<Op>> {
    let id = node_id(value)?;
    ARENA.with(|arena| {
        arena
            .borrow()
            .nodes
            .get(&id)
            .and_then(|node| node.op.clone())
    })
}

/// The operand terms of an expression node.
pub fn terms_of(value: &Value) -> Option<Vec<Value>> {
    let id = node_id(value)?;
    ARENA.with(|arena| arena.borrow().nodes.get(&id).map(|node| node.terms.clone()))
}

/// Allocate a node and return its handle. `under` is the expression the
/// node belongs to, when it is built inside one.
fn new_node_under(
    op: Option<Arc<Op>>,
    token: Option<Token>,
    terms: Vec<Value>,
    under: Option<&Value>,
) -> Value {
    let inherited = under.and_then(root_id);
    let terms_taken = terms.clone();
    let id = ARENA.with(|arena| {
        let mut arena = arena.borrow_mut();
        arena.next_id += 1;
        let id = arena.next_id;
        arena.nodes.insert(
            id,
            ExprNode {
                op,
                token,
                terms,
                root: inherited.unwrap_or(id),
                size: 1,
            },
        );
        id
    });
    let handle = handle_for(id);
    if under.is_some() {
        grow(&handle, 1);
    }
    adopt_all(&handle, &terms_taken);
    handle
}

fn new_node(op: Option<Arc<Op>>, token: Option<Token>, terms: Vec<Value>) -> Value {
    new_node_under(op, token, terms, None)
}

/// Count `count` more nodes against the expression `node` belongs to, and
/// record the size when it is the largest yet.
fn grow(node: &Value, count: usize) {
    let Some(root) = root_id(node) else {
        return;
    };
    let size = ARENA.with(|arena| {
        let mut arena = arena.borrow_mut();
        match arena.nodes.get_mut(&root) {
            Some(entry) => {
                entry.size += count;
                entry.size
            }
            None => 0,
        }
    });
    LARGEST.with(|largest| {
        if size > largest.get() {
            largest.set(size);
        }
    });
}

/// The size of the expression a node belongs to.
fn expression_size(node: &Value) -> usize {
    let Some(root) = root_id(node) else {
        return 0;
    };
    ARENA.with(|arena| {
        arena
            .borrow()
            .nodes
            .get(&root)
            .map_or(0, |entry| entry.size)
    })
}

/// Account for a term taken into an expression. A term that is itself an
/// expression brings its whole tree with it, unless it already belongs to
/// this one.
fn adopt(container: &Value, term: &Value) {
    let (Some(into), Some(from)) = (root_id(container), root_id(term)) else {
        return;
    };
    if into == from {
        return;
    }
    grow(container, expression_size(term));
}

fn adopt_all(container: &Value, terms: &[Value]) {
    for term in terms {
        adopt(container, term);
    }
}

/// The handle for a node identity. Two handles carrying the same identity
/// are the same node, whichever one a rule is holding.
fn handle_for(id: u64) -> Value {
    let mut meta: IndexMap<String, Value> = IndexMap::new();
    meta.insert(EXPR_META.into(), Value::Number(id as f64));
    Value::ListRef(Arc::new(ListRef {
        value: Vec::new(),
        implicit: false,
        child: None,
        meta,
    }))
}

/// The identity of the expression a node belongs to.
fn root_id(value: &Value) -> Option<u64> {
    let id = node_id(value)?;
    ARENA.with(|arena| arena.borrow().nodes.get(&id).map(|node| node.root))
}

/// The whole expression a node belongs to.
fn root_node(value: &Value) -> Value {
    match root_id(value) {
        Some(id) => handle_for(id),
        None => value.clone(),
    }
}

fn with_node<R>(value: &Value, read: impl FnOnce(&ExprNode) -> R) -> Option<R> {
    let id = node_id(value)?;
    ARENA.with(|arena| arena.borrow().nodes.get(&id).map(read))
}

fn with_node_mut<R>(value: &Value, write: impl FnOnce(&mut ExprNode) -> R) -> Option<R> {
    let id = node_id(value)?;
    ARENA.with(|arena| arena.borrow_mut().nodes.get_mut(&id).map(write))
}

/// The port of the canonical `updateExprNode`: rewrite a node in place,
/// keeping its identity, and truncate it to the supplied terms.
fn update_expr_node(node: &Value, op: Option<Arc<Op>>, token: Option<Token>, terms: Vec<Value>) {
    adopt_all(node, &terms);
    with_node_mut(node, |entry| {
        entry.op = op;
        entry.token = token;
        entry.terms = terms;
    });
}

/// The port of the canonical `dupNode`: a shallow copy, sharing the terms
/// with the original but carrying its own identity.
fn dup_node(node: &Value) -> Value {
    let Some((op, token, terms)) = with_node(node, |entry| {
        (entry.op.clone(), entry.token.clone(), entry.terms.clone())
    }) else {
        return node.clone();
    };
    new_node_under(op, token, terms, Some(node))
}

/// `expr[index]` where index 1 is the first term: absent slots read as
/// `Undefined`, as a sparse JavaScript array does.
fn term_at(node: &Value, index: usize) -> Value {
    with_node(node, |entry| {
        entry
            .terms
            .get(index.saturating_sub(1))
            .cloned()
            .unwrap_or(Value::Undefined)
    })
    .unwrap_or(Value::Undefined)
}

/// `expr[index] = value`, extending the node when the slot is past its
/// end, as assigning past a JavaScript array's length does.
fn set_term(node: &Value, index: usize, value: Value) {
    adopt(node, &value);
    with_node_mut(node, |entry| {
        let slot = index.saturating_sub(1);
        while entry.terms.len() <= slot {
            entry.terms.push(Value::Undefined);
        }
        entry.terms[slot] = value;
    });
}

/// `expr.push(value)`.
fn push_term(node: &Value, value: Value) {
    adopt(node, &value);
    with_node_mut(node, |entry| entry.terms.push(value));
}

/// The number of terms a node carries, the canonical `node.length - 1`.
fn term_count(node: &Value) -> usize {
    with_node(node, |entry| entry.terms.len()).unwrap_or(0)
}

/// Refuse a handle whose node the arena no longer holds.
///
/// A node leaves the arena only when a parse releases it wholesale, so a
/// handle that names a missing one is a value that outlived the scope its
/// nodes were live in: taken out of [`parse_scope`], or read straight off
/// [`Tabnas::parse`] and kept across the next parse on this thread. Node
/// identities never repeat, so the handle cannot have been captured by a
/// later parse either: the expression it headed is simply gone.
///
/// This is loud on purpose. Reporting the missing node as an empty array
/// let a walk finish and hand back a well-formed value that had silently
/// lost the whole expression, which is worse than either a correct answer
/// or no answer: nothing downstream could tell the two apart.
fn released_handle(id: u64) -> ! {
    panic!(
        "tabnas-expr: expression node {id} has been released. The value \
         holding this handle outlived its parse: realize it with \
         `tabnas_expr::realize` inside the `parse_scope` closure, or before \
         the next parse on this thread, and let the realized value escape \
         instead."
    )
}

/// Drop every node this thread's arena holds.
///
/// The arena is per-thread and is released when the outermost parse
/// through this crate's own entry points returns, or at the start of the
/// next parse on the thread when a caller drives the engine directly. Its
/// high-water mark is therefore one parse's expression nodes.
fn release_arena() {
    ARENA.with(|arena| {
        let mut arena = arena.borrow_mut();
        if 0 == arena.active {
            arena.nodes.clear();
            EVALUATED.with(|set| set.borrow_mut().clear());
            LARGEST.with(|largest| largest.set(0));
        }
    });
}

/// Hold the arena open for the duration of one parse, and release it when
/// the outermost one returns.
struct ArenaGuard;

impl ArenaGuard {
    fn enter() -> Self {
        ARENA.with(|arena| arena.borrow_mut().active += 1);
        LARGEST.with(|largest| largest.set(0));
        ArenaGuard
    }
}

impl Drop for ArenaGuard {
    fn drop(&mut self) {
        ARENA.with(|arena| {
            let mut arena = arena.borrow_mut();
            arena.active = arena.active.saturating_sub(1);
            if 0 == arena.active {
                arena.nodes.clear();
                EVALUATED.with(|set| set.borrow_mut().clear());
                LARGEST.with(|largest| largest.set(0));
            }
        });
    }
}

// ---------------------------------------------------------------------------
// Realizing and simplifying a parsed tree
// ---------------------------------------------------------------------------

/// Replace every expression handle in a parsed value with the plain array
/// the canonical port returns: the operator description followed by the
/// operand terms.
///
/// A parse through [`parse`], [`parse_with`] or [`parse_simplified`] is
/// realized already. A caller driving a [`Tabnas`] instance directly calls
/// this on the result.
pub fn realize(value: &Value) -> Value {
    let mut open: Vec<u64> = Vec::new();
    realize_seen(value, &mut open)
}

fn realize_seen(value: &Value, open: &mut Vec<u64>) -> Value {
    match value {
        Value::ListRef(list) => {
            let Some(id) = node_id(value) else {
                let mut out = (**list).clone();
                out.value = out
                    .value
                    .iter()
                    .map(|entry| realize_seen(entry, open))
                    .collect();
                return Value::ListRef(Arc::new(out));
            };
            // A rewrite can leave a node reachable from itself; the
            // canonical simplifier reports the same way rather than
            // recursing forever.
            if open.contains(&id) {
                return Value::String("[CIRCLE]".into());
            }
            let Some((op, token, terms)) = with_node(value, |entry| {
                (entry.op.clone(), entry.token.clone(), entry.terms.clone())
            }) else {
                released_handle(id)
            };
            open.push(id);
            let mut out = Vec::with_capacity(terms.len() + 1);
            if let Some(op) = &op {
                out.push(op.to_value(token.as_ref()));
            }
            for term in &terms {
                out.push(realize_seen(term, open));
            }
            open.pop();
            Value::array(out)
        }
        Value::Array(entries) => Value::array(
            entries
                .iter()
                .map(|entry| realize_seen(entry, open))
                .collect(),
        ),
        Value::Object(entries) => Value::object(
            entries
                .iter()
                .map(|(key, entry)| (key.clone(), realize_seen(entry, open)))
                .collect(),
        ),
        Value::MapRef(map) => {
            let mut out = (**map).clone();
            out.value = out
                .value
                .iter()
                .map(|(key, entry)| (key.clone(), realize_seen(entry, open)))
                .collect();
            Value::MapRef(Arc::new(out))
        }
        other => other.clone(),
    }
}

/// Reduce a parsed value to the S-expression form the shared fixtures
/// compare: every operator description becomes its source text, and a
/// term that was never filled is dropped.
///
/// This is the Rust spelling of the canonical `S` helper the TypeScript
/// suite uses and of the Go port's `Simplify`.
pub fn simplify(value: &Value) -> Value {
    let mut open: Vec<u64> = Vec::new();
    simplify_seen(value, &mut open)
}

fn simplify_seen(value: &Value, open: &mut Vec<u64>) -> Value {
    match value {
        Value::ListRef(list) => {
            let Some(id) = node_id(value) else {
                return Value::array(
                    list.value
                        .iter()
                        .map(|entry| simplify_seen(entry, open))
                        .collect(),
                );
            };
            if open.contains(&id) {
                return Value::String("[CIRCLE]".into());
            }
            let Some((op, terms)) =
                with_node(value, |entry| (entry.op.clone(), entry.terms.clone()))
            else {
                released_handle(id)
            };
            open.push(id);
            let mut out = Vec::with_capacity(terms.len() + 1);
            if let Some(op) = &op {
                // A paren operator's `src` is its opening source, so one
                // field covers both, as it does in the canonical port.
                out.push(Value::String(op.src.clone()));
            }
            for term in &terms {
                // An unfilled slot is `undefined` in the canonical port,
                // and the canonical simplifier filters those out.
                if term.is_undefined() {
                    continue;
                }
                out.push(simplify_seen(term, open));
            }
            open.pop();
            Value::array(out)
        }
        // A REALIZED expression: the operator description is an object
        // carrying its source text, which is what the canonical
        // simplifier reads (`x[0].src`).
        Value::Array(entries) if realized_source(entries.first()).is_some() => {
            let mut out = Vec::with_capacity(entries.len());
            out.push(Value::String(
                realized_source(entries.first()).unwrap_or_default(),
            ));
            for entry in entries.iter().skip(1) {
                if entry.is_undefined() {
                    continue;
                }
                out.push(simplify_seen(entry, open));
            }
            Value::array(out)
        }
        Value::Array(entries) => Value::array(
            entries
                .iter()
                .map(|entry| simplify_seen(entry, open))
                .collect(),
        ),
        Value::Object(entries) => Value::object(
            entries
                .iter()
                .map(|(key, entry)| (key.clone(), simplify_seen(entry, open)))
                .collect(),
        ),
        Value::MapRef(map) => Value::object(
            map.value
                .iter()
                .map(|(key, entry)| (key.clone(), simplify_seen(entry, open)))
                .collect(),
        ),
        Value::Text(text) => Value::String(text.string.clone()),
        other => other.clone(),
    }
}

/// The source text of a realized operator description, when a value is
/// one.
fn realized_source(value: Option<&Value>) -> Option<String> {
    match object_get(value?, "src") {
        Some(Value::String(src)) if !src.is_empty() => Some(src.clone()),
        _ => None,
    }
}

// ---------------------------------------------------------------------------
// The Pratt core
// ---------------------------------------------------------------------------

/// One occurrence of an operator: the shared description and the token
/// that introduced it. The canonical `makeOp` builds the same pair by
/// copying the description and attaching the token.
#[derive(Debug, Clone)]
pub struct OpRef {
    pub op: Arc<Op>,
    pub token: Option<Token>,
}

impl OpRef {
    /// An occurrence with no token behind it, for direct use of
    /// [`prattify`].
    pub fn new(op: Op) -> Self {
        OpRef {
            op: Arc::new(opify(op)),
            token: None,
        }
    }

    fn at(op: &Arc<Op>, token: Option<Token>) -> Self {
        OpRef {
            op: op.clone(),
            token,
        }
    }

    /// A fresh expression node headed by this operator.
    pub fn node(&self, terms: Vec<Value>) -> Value {
        new_node(Some(self.op.clone()), self.token.clone(), terms)
    }

    /// A fresh expression node built inside an existing expression.
    fn node_under(&self, terms: Vec<Value>, under: &Value) -> Value {
        new_node_under(
            Some(self.op.clone()),
            self.token.clone(),
            terms,
            Some(under),
        )
    }
}

/// Normalize an operator built by hand, filling the derived term count
/// when it is unset, as the parser's own operator builder does. The Rust
/// spelling of the canonical `testing.opify`.
pub fn opify(mut op: Op) -> Op {
    if 0 == op.terms {
        op.terms = if op.ternary {
            3
        } else if op.infix {
            2
        } else {
            1
        };
    }
    op
}

/// Place an operator that follows an expression and takes a term on each
/// side, by its binding powers: an infix operator, or a ternary with a
/// binding power, whose first term is as much of the expression as binds
/// tighter. Returns the node the operator heads, where its next term
/// belongs.
///
/// The drilling is a loop, one level of the expression's last terms at a
/// time, so a long right-leaning chain (`a=b=...=a`) does not grow the call
/// stack with its length.
fn place_infix(expr: &Value, op: &OpRef) -> Value {
    let new = &op.op;
    let mut expr = expr.clone();
    loop {
        let Some(expr_op) = op_of(&expr) else {
            return expr;
        };
        if expr_op.suffix || new.left <= expr_op.right {
            // The new operator is looser: it takes the whole expression
            // built so far as its first term.
            let prior = dup_node(&expr);
            update_expr_node(&expr, Some(new.clone()), op.token.clone(), vec![prior]);
            return expr;
        }
        // The new operator is tighter: it takes only the last term, or
        // drills into it while the operator heading it binds looser.
        let end = expr_op.terms;
        let last = term_at(&expr, end);
        if op_of(&last).is_some_and(|last_op| last_op.right < new.left) {
            expr = last;
            continue;
        }
        let out = op.node_under(vec![last], &expr);
        set_term(&expr, end, out.clone());
        return out;
    }
}

/// Embed a new operator into an expression tree, in place, according to
/// operator precedence.
///
/// The node keeps its identity, so every rule holding it observes the
/// rewrite: that is what preserves the referential integrity of the root
/// expression while it is still being assembled. The returned handle is
/// the sub-expression the new operator now heads, which is where its next
/// term belongs.
pub fn prattify(expr: &Value, op: &OpRef) -> Value {
    let out = expr.clone();
    let Some(expr_op) = op_of(expr) else {
        return out;
    };
    let new = &op.op;

    if new.infix {
        return place_infix(expr, op);
    }
    if new.prefix {
        let out = op.node_under(Vec::new(), expr);
        set_term(expr, expr_op.terms, out.clone());
        return out;
    }
    if new.suffix {
        if !expr_op.suffix && expr_op.right <= new.left {
            // NOTE: special case: a higher precedence suffix "drills"
            // into lower precedence prefixes, so `@@1!` is `@(@(1!))`
            // rather than `@((@1)!)`. The drilling is a loop, as
            // `place_infix`'s is.
            let mut at = expr.clone();
            loop {
                let end = op_of(&at).map_or(0, |at_op| at_op.terms);
                let last = term_at(&at, end);
                if op_of(&last).is_some_and(|last_op| last_op.prefix && last_op.right < new.left) {
                    at = last;
                    continue;
                }
                set_term(&at, end, op.node_under(vec![last], &at));
                break;
            }
        } else {
            let prior = dup_node(expr);
            update_expr_node(expr, Some(new.clone()), op.token.clone(), vec![prior]);
        }
    }

    out
}

/// Convert a prior rule's node into the start of a new expression, the
/// port of the canonical `prior`.
fn prior_expr(rule: &mut Rule, prior: Option<&Rc<RuleSnapshot>>, op: &OpRef) -> Value {
    let prior_value = prior.map_or(Value::Undefined, |prior| prior.node.borrow().clone());

    let node = if is_op(&prior_value) && !op.op.prefix {
        // Infix or suffix: the prior node is the genuine first term to
        // wrap (the `(1+2)` of `(1+2)+3`). Duplicate it so the in-place
        // rewrite below preserves referential integrity.
        let duplicate = dup_node(&prior_value);
        update_expr_node(
            &prior_value,
            Some(op.op.clone()),
            op.token.clone(),
            vec![duplicate],
        );
        prior_value
    } else {
        // A prefix operator never has a prior term, so any expression
        // sitting on the prior node here is a foreign parent-seed (a
        // ternary or paren wrapper the engine threaded down). Start
        // fresh rather than rewriting it.
        let terms = if op.op.prefix {
            Vec::new()
        } else {
            vec![prior_value]
        };
        let fresh = op.node(terms);
        if let Some(prior) = prior {
            // NOTE: nothing is written when there is no prior rule. The
            // canonical ports guard the same write, because a rule with
            // no parent would otherwise publish onto the no-rule
            // sentinel and leak the expression into every later parse.
            *prior.node.borrow_mut() = fresh.clone();
        }
        fresh
    };

    // Ensure the first term's rule contains the final expression.
    if let Some(prior) = prior {
        rule.parent_rule = Some(prior.clone());
        rule.parent_node = Some(prior.node.clone());
    }

    node
}

// ---------------------------------------------------------------------------
// Evaluation
// ---------------------------------------------------------------------------

/// Values an evaluator has already produced, by identity.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
enum EvalKey {
    Node(u64),
    Shared(usize, usize),
}

thread_local! {
    static EVALUATED: RefCell<HashSet<EvalKey>> = RefCell::new(HashSet::new());
}

fn eval_key(value: &Value) -> Option<EvalKey> {
    if let Some(id) = node_id(value) {
        return Some(EvalKey::Node(id));
    }
    match value {
        Value::Array(entries) if !entries.is_empty() => Some(EvalKey::Shared(
            Arc::as_ptr(entries) as usize,
            entries.len(),
        )),
        Value::Object(entries) if !entries.is_empty() => Some(EvalKey::Shared(
            Arc::as_ptr(entries) as usize,
            entries.len(),
        )),
        Value::ListRef(list) => Some(EvalKey::Shared(
            Arc::as_ptr(list) as usize,
            list.value.len(),
        )),
        Value::MapRef(map) => Some(EvalKey::Shared(Arc::as_ptr(map) as usize, map.value.len())),
        _ => None,
    }
}

fn evaluated_seen(value: &Value) -> bool {
    eval_key(value).is_some_and(|key| EVALUATED.with(|set| set.borrow().contains(&key)))
}

fn evaluated_mark(value: &Value) {
    if let Some(key) = eval_key(value) {
        EVALUATED.with(|set| {
            set.borrow_mut().insert(key);
        });
    }
}

/// What [`evaluation_with`] reduces besides expressions and implicit lists.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct EvaluationOptions {
    /// Reduce a map member by member into a NEW map of the same kind,
    /// which is what the eager `evaluate` option already does for an
    /// expression inside a map. Off by default: a map is then passed
    /// through as it is, as [`evaluation`] documents.
    pub objects: bool,
}

/// Reduce an expression tree with an evaluator, innermost first.
///
/// An implicit list is reduced a member at a time as its members close and
/// again as a whole once it is complete, so a value the evaluator has
/// already produced is returned untouched rather than reduced twice. That
/// record is per-thread and is cleared with the expression arena.
///
/// A map is passed through unchanged; [`evaluation_with`] can reduce it
/// member by member instead.
pub fn evaluation(site: &mut EvalSite<'_>, value: &Value, evaluate: &Evaluate) -> Value {
    evaluation_with(site, value, evaluate, EvaluationOptions::default())
}

/// [`evaluation`] with options: the port of the canonical
/// `evaluation(rule, ctx, expr, evaluate, { objects })`.
///
/// The walk is iterative, terms before the operation that holds them, so a
/// tree as deep as a long chain of operators (`a+a+...+a`) is reduced
/// without the call stack growing with it.
pub fn evaluation_with(
    site: &mut EvalSite<'_>,
    value: &Value,
    evaluate: &Evaluate,
    options: EvaluationOptions,
) -> Value {
    if let Some(out) = evaluation_leaf(value, options) {
        return out;
    }

    let mut stack: Vec<EvalFrame> = vec![EvalFrame::of(value)];
    loop {
        let top = stack.len() - 1;
        let next = {
            let frame = &stack[top];
            frame.members.get(frame.reduced.len()).cloned()
        };
        if let Some(member) = next {
            match evaluation_leaf(&member, options) {
                Some(out) => stack[top].reduced.push(out),
                None => stack.push(EvalFrame::of(&member)),
            }
            continue;
        }
        let frame = stack.pop().unwrap_or_else(|| EvalFrame::of(value));
        let out = frame.finish(site, evaluate);
        match stack.last_mut() {
            Some(parent) => parent.reduced.push(out),
            None => return out,
        }
    }
}

/// A value [`evaluation_with`] needs no walk for, reduced: nothing, a value
/// a reduction produced, or one that is neither an expression, an implicit
/// list nor (with `objects`) a map. `None` for a value whose members are
/// reduced first.
fn evaluation_leaf(value: &Value, options: EvaluationOptions) -> Option<Value> {
    if value.is_undefined() || matches!(value, Value::Null) {
        return Some(Value::Null);
    }
    if evaluated_seen(value) {
        return Some(value.clone());
    }
    let walked = is_op(value)
        || matches!(value, Value::Array(_))
        || (options.objects && matches!(value, Value::Object(_) | Value::MapRef(_)));
    (!walked).then(|| value.clone())
}

/// A node [`evaluation_with`] is reducing: its members, and their reduced
/// values so far.
struct EvalFrame {
    node: Value,
    /// The operator and its occurrence token, for an expression node.
    op: Option<(Arc<Op>, Option<Token>)>,
    /// A map's member names, in order, for a map.
    names: Vec<String>,
    members: Vec<Value>,
    reduced: Vec<Value>,
}

impl EvalFrame {
    fn of(node: &Value) -> Self {
        let mut frame = EvalFrame {
            node: node.clone(),
            op: None,
            names: Vec::new(),
            members: Vec::new(),
            reduced: Vec::new(),
        };
        if let Some((op, token, terms)) = with_node(node, |entry| {
            (entry.op.clone(), entry.token.clone(), entry.terms.clone())
        }) {
            frame.op = op.map(|op| (op, token));
            frame.members = terms;
            return frame;
        }
        match node {
            Value::Array(entries) => frame.members = entries.to_vec(),
            Value::Object(entries) => {
                frame.names = entries.keys().cloned().collect();
                frame.members = entries.values().cloned().collect();
            }
            Value::MapRef(map) => {
                frame.names = map.value.keys().cloned().collect();
                frame.members = map.value.values().cloned().collect();
            }
            _ => {}
        }
        frame
    }

    /// The node's reduced value, from its members' reduced values.
    fn finish(self, site: &mut EvalSite<'_>, evaluate: &Evaluate) -> Value {
        let EvalFrame {
            node,
            op,
            names,
            reduced,
            ..
        } = self;
        let out = if let Some((op, token)) = op {
            // The occurrence token travels on the site, not on the shared
            // description: `op` is one entry of the operator table and is
            // the same object for every occurrence. Restoring the previous
            // token keeps an outer reduction pointing at its own operator.
            let previous = std::mem::replace(&mut site.token, token);
            let reduction = evaluate(site, &op, &reduced);
            site.token = previous;
            reduction
        } else {
            match &node {
                // An implicit list is a plain array, not an expression node.
                // Reduce its members into a NEW array: this is a documented
                // entry point and the parse-once, evaluate-many workflow
                // needs a caller's tree to survive a reduction intact.
                Value::Array(_) => Value::array(reduced),
                // Into a NEW map of the same kind, members in their own
                // order.
                Value::MapRef(map) => {
                    let mut out = (**map).clone();
                    out.value = names.into_iter().zip(reduced).collect();
                    Value::MapRef(Arc::new(out))
                }
                Value::Object(_) => Value::object(names.into_iter().zip(reduced).collect()),
                // A node rewritten into a plain list of its terms is passed
                // through as it is.
                _ => node.clone(),
            }
        };

        // Only a value this reduction PRODUCED is marked. A node passed
        // through unchanged (a map, by default) is not, so a later
        // reduction with `objects` on still reaches the operators inside
        // it.
        if eval_key(&out) != eval_key(&node) {
            evaluated_mark(&out);
        }
        out
    }
}

// ---------------------------------------------------------------------------
// Grammar construction
// ---------------------------------------------------------------------------

/// Which of the four token-led operator families a map is built for.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Anyfix {
    Prefix,
    Suffix,
    Infix,
    Ternary,
}

impl Anyfix {
    fn name(self) -> &'static str {
        match self {
            Anyfix::Prefix => "prefix",
            Anyfix::Suffix => "suffix",
            Anyfix::Infix => "infix",
            Anyfix::Ternary => "ternary",
        }
    }

    fn selects(self, def: &OpDef) -> bool {
        match self {
            Anyfix::Prefix => def.prefix,
            Anyfix::Suffix => def.suffix,
            Anyfix::Infix => def.infix,
            Anyfix::Ternary => def.ternary,
        }
    }

    fn terms(self) -> usize {
        match self {
            Anyfix::Ternary => 3,
            Anyfix::Infix => 2,
            _ => 1,
        }
    }
}

/// Resolve the token identity for an operator source, preferring one this
/// INSTANCE already binds.
///
/// The canonical plugin looks a source up with `tabnas.fixed(src)`, an
/// instance lookup: a host grammar registers its punctuation as
/// instance-level fixed tokens, and binding an operator to a fresh
/// `#E<src>` identity instead would leave its alternate waiting on a token
/// the host lexer never emits.
fn operator_tin(parser: &mut Tabnas, src: &str) -> (Tin, String) {
    if let Some(tin) = parser.fixed(src) {
        let name = parser.token_name(tin);
        return (tin, name);
    }
    let name = format!("#E{src}");
    let tin = parser.token_with_source(name.clone(), src);
    (tin, name)
}

/// An operator definition's binding power, or the fallback when it is
/// unset.
///
/// The canonical `makeOpMap` writes `opdef.left || Number.MIN_SAFE_INTEGER`
/// and `opdef.right || Number.MAX_SAFE_INTEGER`. JavaScript's `||` is
/// falsy-based, so a power of ZERO is not a power of zero there: it falls
/// through to the fallback exactly as an absent one does. Keeping the zero
/// changes the tree a zero-power operator builds against one with a
/// negative power, which `../test/spec/binding-power-zero.tsv` pins.
fn binding_power(power: Option<i64>, unset: i64) -> i64 {
    match power {
        Some(0) | None => unset,
        Some(power) => power,
    }
}

/// Build one token-led operator map, the port of the canonical
/// `makeOpMap`.
fn make_op_map(
    parser: &mut Tabnas,
    ops: &IndexMap<String, Option<OpDef>>,
    anyfix: Anyfix,
) -> IndexMap<Tin, Arc<Op>> {
    let mut map: IndexMap<Tin, Arc<Op>> = IndexMap::new();
    for (name, def) in ops {
        let Some(def) = def else { continue };
        if !anyfix.selects(def) {
            continue;
        }
        let src = def.src.first().cloned().unwrap_or_default();
        let (tin, tkn) = operator_tin(parser, &src);

        let suffix = format!("-{}", anyfix.name());
        let op = Op {
            src: src.clone(),
            left: binding_power(def.left, MIN_SAFE_INTEGER),
            right: binding_power(def.right, MAX_SAFE_INTEGER),
            name: if name.ends_with(&suffix) {
                name.clone()
            } else {
                format!("{name}{suffix}")
            },
            infix: Anyfix::Infix == anyfix,
            prefix: Anyfix::Prefix == anyfix,
            suffix: Anyfix::Suffix == anyfix,
            ternary: Anyfix::Ternary == anyfix,
            tkn,
            tin,
            terms: anyfix.terms(),
            use_data: def.use_data.clone(),
            separator: Anyfix::Infix == anyfix && def.separator,
            ..Default::default()
        };

        if Anyfix::Ternary == anyfix {
            // A ternary has two source strings, and both resolve to the
            // same description apart from their token and their index.
            let second = def.src.get(1).cloned().unwrap_or_default();
            let (second_tin, second_tkn) = operator_tin(parser, &second);

            let mut first = op.clone();
            first.ternary_index = Some(0);
            map.insert(tin, Arc::new(first));

            let mut last = op;
            last.src = second;
            last.ternary_index = Some(1);
            last.tkn = second_tkn;
            last.tin = second_tin;
            map.insert(second_tin, Arc::new(last));
        } else {
            map.insert(tin, Arc::new(op));
        }
    }
    map
}

/// Build the paren operator map, the port of the canonical
/// `makeParenMap`.
/// The paren operators, in the table's order. Several may share an
/// opener; the plugin picks, per opener, the group and the preval one.
fn make_paren_ops(parser: &mut Tabnas, ops: &IndexMap<String, Option<OpDef>>) -> Vec<Arc<Op>> {
    let mut list: Vec<Arc<Op>> = Vec::new();
    for (name, def) in ops {
        let Some(def) = def else { continue };
        if !def.paren {
            continue;
        }
        let (otin, otkn) = operator_tin(parser, &def.osrc);
        let (ctin, ctkn) = operator_tin(parser, &def.csrc);
        let op = Op {
            name: format!("{name}-paren"),
            osrc: def.osrc.clone(),
            csrc: def.csrc.clone(),
            otkn,
            otin,
            ctkn,
            ctin,
            preval: def.preval.clone().unwrap_or_default(),
            paren: true,
            src: def.osrc.clone(),
            terms: 1,
            use_data: def.use_data.clone(),
            // A binding power on a preval paren: compared like a suffix's
            // with the operator whose operand precedes it (see
            // `binds_here`). Unset, the paren binds to the value just
            // before it.
            left: binding_power(def.left, MIN_SAFE_INTEGER),
            content: def.content,
            ..Default::default()
        };
        list.push(Arc::new(op));
    }
    list
}

/// The cast operators, by the opener of the group each is written with,
/// the port of the canonical `makeCastOps`.
fn make_cast_ops(
    parser: &mut Tabnas,
    ops: &IndexMap<String, Option<OpDef>>,
) -> IndexMap<Tin, Arc<Op>> {
    let mut map: IndexMap<Tin, Arc<Op>> = IndexMap::new();
    for (name, def) in ops {
        let Some(def) = def else { continue };
        if !def.cast {
            continue;
        }
        let (otin, otkn) = operator_tin(parser, &def.osrc);
        let (ctin, ctkn) = operator_tin(parser, &def.csrc);
        let op = Op {
            name: if name.ends_with("-cast") {
                name.clone()
            } else {
                format!("{name}-cast")
            },
            src: def
                .src
                .first()
                .cloned()
                .unwrap_or_else(|| format!("{}{}", def.osrc, def.csrc)),
            left: MIN_SAFE_INTEGER,
            right: binding_power(def.right, MAX_SAFE_INTEGER),
            use_data: def.use_data.clone(),
            // A prefix, whose first term, the group's content, is fixed
            // when it opens: prattify reads it as one.
            prefix: true,
            terms: 2,
            osrc: def.osrc.clone(),
            csrc: def.csrc.clone(),
            otkn,
            otin,
            ctkn,
            ctin,
            cast: true,
            accept: def.accept.clone(),
            ..Default::default()
        };
        map.insert(otin, Arc::new(op));
    }
    map
}

/// Everything the rule alternates read: the operator maps, the token
/// identities they match on, and the evaluator.
struct Grammar {
    prefix: IndexMap<Tin, Arc<Op>>,
    suffix: IndexMap<Tin, Arc<Op>>,
    infix: IndexMap<Tin, Arc<Op>>,
    ternary: IndexMap<Tin, Arc<Op>>,
    /// Every paren operator, in the table's order.
    parens: Vec<Arc<Op>>,
    /// Per opener, the operator a paren opens when no value precedes it.
    paren_plain: IndexMap<Tin, Arc<Op>>,
    /// Per opener, the operator a paren opens when a value precedes it.
    paren_preval: IndexMap<Tin, Arc<Op>>,
    tin_prefix: Vec<Tin>,
    tin_suffix: Vec<Tin>,
    tin_infix: Vec<Tin>,
    tin_tern0: Vec<Tin>,
    tin_tern1: Vec<Tin>,
    tin_open: Vec<Tin>,
    tin_close: Vec<Tin>,
    evaluate: Option<Evaluate>,
    /// Casts, by the opener of the group each is written with.
    cast: IndexMap<Tin, Arc<Op>>,
    /// The separators: jsonic's comma, and the token an infix operator on
    /// `,` uses, which a host lexer may emit in its place.
    tin_sep: Vec<Tin>,
    /// Some paren content is separated, or some infix operator on `,` is a
    /// separator, so some context separates on `,`.
    separating: bool,
    /// Some infix operator on `,` gives way to separators, so lists and
    /// maps separate on `,` too.
    has_separator: bool,
    /// Some paren operator's content is required.
    has_required: bool,
    /// Some preval paren has a binding power.
    has_bound: bool,
    /// Values side by side are refused (`juxtapose: false`).
    no_juxtapose: bool,
    /// The ternaries with a binding power, placed as an infix operator is
    /// (see [`OpDef::ternary`]), by their first and second tokens.
    tin_tern0b: Vec<Tin>,
    tin_tern1b: Vec<Tin>,
    /// A host grammar's own value tokens (see [`ExprOptions::values`]).
    host_values: Vec<Tin>,
}

/// The value tokens an expression term can start with, the canonical
/// `VAL = [TX, NR, ST, VL]`.
const VAL_TINS: [Tin; 4] = [TIN_TX, TIN_NR, TIN_ST, TIN_VL];

impl Grammar {
    fn has_prefix(&self) -> bool {
        !self.tin_prefix.is_empty()
    }

    fn has_infix(&self) -> bool {
        !self.tin_infix.is_empty()
    }

    fn has_suffix(&self) -> bool {
        !self.tin_suffix.is_empty()
    }

    fn has_ternary(&self) -> bool {
        !self.tin_tern0.is_empty() && !self.tin_tern1.is_empty()
    }

    fn has_paren(&self) -> bool {
        !self.tin_open.is_empty() && !self.tin_close.is_empty()
    }

    fn has_cast(&self) -> bool {
        !self.cast.is_empty()
    }

    fn has_bound_ternary(&self) -> bool {
        !self.tin_tern0b.is_empty() && !self.tin_tern1b.is_empty()
    }

    /// Whether a host grammar's value is refused where it stands: values
    /// side by side are refused, and the token is one of the host's.
    fn refuse_host_values(&self) -> bool {
        self.no_juxtapose && !self.host_values.is_empty()
    }

    fn host_value(&self, tin: Option<Tin>) -> bool {
        self.refuse_host_values() && tin.is_some_and(|tin| self.host_values.contains(&tin))
    }

    /// Whether a preval paren on this opener has a binding power, and so
    /// may be placed as a postfix of the expression before it.
    fn postfix_opener(&self, tin: Tin) -> bool {
        self.paren_preval.get(&tin).is_some_and(|op| bound(op))
    }

    /// Whether a token starts a value, where the one before has ended.
    fn starts_value(&self, tin: Tin) -> bool {
        VAL_TINS.contains(&tin)
            || self.host_values.contains(&tin)
            || TIN_OB == tin
            || TIN_OS == tin
            || self.tin_open.contains(&tin)
            || self.tin_prefix.contains(&tin)
    }

    /// The operator occurrence a matched token introduces, the port of the
    /// canonical `makeOp`.
    fn op_use(map: &IndexMap<Tin, Arc<Op>>, token: Option<&Token>) -> Option<OpRef> {
        let token = token?;
        map.get(&token.tin)
            .map(|op| OpRef::at(op, Some(token.clone())))
    }
}

// ---------------------------------------------------------------------------
// Rule helpers
// ---------------------------------------------------------------------------

/// A rule counter, absent reading as zero.
fn counter(rule: &Rule, name: &str) -> i32 {
    rule.n.get(name).copied().unwrap_or(0)
}

/// A rule-local number, absent reading as zero.
fn local_number(rule: &Rule, name: &str) -> i64 {
    match rule.u.get(name) {
        Some(Value::Number(number)) => *number as i64,
        _ => 0,
    }
}

fn set_local_number(rule: &mut Rule, name: &str, value: i64) {
    rule.u_mut()
        .insert(name.to_string(), Value::Number(value as f64));
}

/// Assign a rule's node: the Rust spelling of the canonical `r.node = v`.
///
/// A pushed or replaced rule SHARES its parent's node cell, so writing
/// through `rule.node.borrow_mut()` would overwrite the parent's node too.
/// Assigning installs a fresh cell instead.
fn set_node(rule: &mut Rule, value: Value) {
    rule.node = Rc::new(RefCell::new(value));
}

fn node_of(rule: &Rule) -> Value {
    rule.node.borrow().clone()
}

/// The `u` key an expr rule keeps its attachment point under, so that a
/// later rule reads the same node the canonical port would read off
/// `rule.node` even after the after-close has put the root back there.
const ATTACH: &str = "expr_attach";

/// The `u` key of a prefix built inside the tree of the expression its
/// parent is building, whose after-close leaves the evaluation to that
/// expression: evaluation follows the tree, from the root, once.
const INNER: &str = "expr_inner";

/// Publish an expression from an expr rule.
///
/// `rule.node` takes the ATTACHMENT POINT, where the operator's next term
/// belongs, exactly as the canonical port leaves it: the rules pushed from
/// here are seeded from it, and a chained prefix nests into it.
///
/// The ROOT goes to the rule's `u` bag, and the rule's after-close puts it
/// back on the node. The canonical port has no need for that, because it
/// reads the parse result off the FIRST rule of a replacement chain, which
/// the root reaches through `prior_expr`. This engine reads it off the
/// LAST, so a rule that kept only its attachment point would hand a
/// sub-expression back as the whole parse: `1+2*3` came back as
/// `["*",2,3]`.
fn publish_expr(rule: &mut Rule, attach: Value) {
    set_node(rule, attach.clone());
    rule.u_mut().insert(ATTACH.to_string(), attach);
}

/// Write a value through a rule's shared node cell.
fn publish(rule: &mut Rule, value: Value) {
    *rule.node.borrow_mut() = value;
}

/// The root of the expression this rule is building.
///
/// The rule the first term belongs to holds it: `prior_expr` writes the
/// new expression there, and the Pratt core rewrites that same node in
/// place however the tree grows, so its identity never moves. A rule with
/// no such prior holds the root itself.
fn expression_root(rule: &Rule) -> Value {
    root_node(&node_of(rule))
}

/// A linked rule's node as the canonical port would read it.
///
/// An expr rule keeps its ATTACHMENT POINT on `rule.node` there, and this
/// port puts the root back on the node once the rule has closed, so an
/// expr rule is read through its attachment point instead: `0!-1!*2!`
/// needs the trailing suffix to bind to `2`, which it only does when the
/// Pratt core is handed the sub-expression the last operator attached to.
fn linked_node(link: Option<&Rc<RuleSnapshot>>) -> Value {
    let Some(link) = link else {
        return Value::Undefined;
    };
    if let Some(attach) = link.u.get(ATTACH) {
        if is_op(attach) {
            return attach.clone();
        }
    }
    link.node.borrow().clone()
}

fn write_linked_node(link: Option<&Rc<RuleSnapshot>>, value: Value) {
    if let Some(link) = link {
        *link.node.borrow_mut() = value;
    }
}

fn counters(pairs: &[(&str, i32)]) -> HashMap<String, i32> {
    pairs
        .iter()
        .map(|(name, value)| ((*name).to_string(), *value))
        .collect()
}

fn locals(pairs: &[(&str, Value)]) -> HashMap<String, Value> {
    pairs
        .iter()
        .map(|(name, value)| ((*name).to_string(), value.clone()))
        .collect()
}

/// An alternate matching one token from the given set.
fn on(tins: &[Tin]) -> AltSpec {
    AltSpec {
        s: vec![tins.to_vec()],
        ..Default::default()
    }
}

/// An alternate matching two tokens in sequence.
fn on2(first: &[Tin], second: &[Tin]) -> AltSpec {
    AltSpec {
        s: vec![first.to_vec(), second.to_vec()],
        ..Default::default()
    }
}

/// An alternate with no token filter at all.
fn always() -> AltSpec {
    AltSpec::default()
}

fn group_has(tags: &str, tag: &str) -> bool {
    tags.split(',').any(|entry| entry.trim() == tag)
}

/// Add alternates the way the canonical `RuleSpec.open`/`close` do: the
/// whole list goes in FRONT of the alternates already there, keeping its
/// own order.
fn prepend_open_all(spec: &mut RuleSpec, alts: Vec<AltSpec>) {
    for alt in alts.into_iter().rev() {
        spec.prepend_open(alt);
    }
}

fn prepend_close_all(spec: &mut RuleSpec, alts: Vec<AltSpec>) {
    for alt in alts.into_iter().rev() {
        spec.prepend_close(alt);
    }
}

// ---------------------------------------------------------------------------
// The options of #105, every one off unless a table asks
// ---------------------------------------------------------------------------

/// The `u` key of an expr rule whose close found a group a cast accepts:
/// the next expr rule opens the cast.
const CAST_NEXT: &str = "expr_cast_next";

/// The `u` key of an expr rule whose close found a bound preval paren: the
/// next expr rule places it as a postfix.
const POSTFIX_NEXT: &str = "expr_postfix_next";

/// The `u` key under which a postfix's expr rule keeps the node the paren
/// heads, `[op, target]`, which the paren's content extends.
const POSTFIX: &str = "expr_postfix";

/// The `u` key of a paren rule opened with no value before it, a group,
/// which a cast may take as its token.
const PAREN_GROUP: &str = "expr_paren_group";

/// The `u` keys of a separated paren content: the terms collected at the
/// separators, and the separator's pass, which goes on to the next term.
const PAREN_ITEMS: &str = "expr_items";
const PAREN_MORE: &str = "expr_paren_more";

/// The `u` keys of an expr rule placing a ternary with a binding power: the
/// operator's name, the step (1 while its middle term is read, 2 while its
/// last term is, 3 once it is back), the counters its expression gets back
/// for the last term, and the node its middle term was read without.
const TERN_NAME: &str = "expr_tern_name";
const TERN_STEP: &str = "expr_tern_step";
const TERN_PAREN: &str = "expr_tern_paren";
const TERN_SEP: &str = "expr_tern_sep";
const TERN_TERNARY: &str = "expr_tern_ternary";
const TERN_NODE: &str = "expr_tern_node";

/// The `u` key of an expr rule that placed an infix operator, or a ternary
/// with a binding power, from the root of its expression: the operator's
/// `left`. Every node above the one the operator heads binds looser than
/// it: the placing descended through each of them.
const PLACED_LEFT: &str = "expr_placed_left";

fn placed(rule: &mut Rule, op: &Op) {
    rule.u_mut()
        .insert(PLACED_LEFT.to_string(), Value::Number(op.left as f64));
}

/// Where [`place_infix`] starts for an operator after the expression's
/// last term: the root of the expression, as the canonical port starts, or
/// the node the previous operator heads, where the placing from the root
/// arrives. It arrives there when the new operator binds at least as
/// tightly as the previous one on its left, since every node above that
/// node binds looser than the previous one, and the node itself binds
/// looser than the new one and is not a suffix's. The tree is the same
/// either way, node for node, and a chain of operators that each place
/// into the last term of the one before (`a=b=...=a`, a ternary's last
/// term holding the next ternary) is placed in time linear in its length,
/// where descending from the root at every operator was quadratic.
fn placing_start(rule: &Rule, root: &Value, op: &Op) -> Value {
    let from_previous = || -> Option<Value> {
        let prev = rule.prev_rule.as_ref()?;
        if "expr" != prev.name.as_ref() {
            return None;
        }
        let Some(Value::Number(left)) = prev.u.get(PLACED_LEFT) else {
            return None;
        };
        let attach = prev.u.get(ATTACH)?;
        let attach_op = op_of(attach)?;
        let arrives = (*left as i64) <= op.left
            && !attach_op.suffix
            && attach_op.right < op.left
            && root_id(attach).is_some()
            && root_id(attach) == root_id(root);
        arrives.then(|| attach.clone())
    };
    from_previous().unwrap_or_else(|| root.clone())
}

/// A preval paren with a binding power, `left`, binds like a suffix.
fn bound(op: &Op) -> bool {
    MIN_SAFE_INTEGER != op.left
}

/// A ternary operator with a binding power (see [`OpDef::ternary`]).
fn bound_ternary(op: &Op) -> bool {
    op.ternary && MIN_SAFE_INTEGER != op.left
}

/// A ternary operator with no binding power, whose rule builds its node
/// apart from the expression's own operators.
fn is_unbound_ternary_op(value: &Value) -> bool {
    is_op_kind(value, |op| op.ternary && !bound_ternary(op))
}

fn flag(u: &HashMap<String, Value>, name: &str) -> bool {
    matches!(u.get(name), Some(Value::Bool(true)))
}

/// The operator whose operand a val is, when its parent is an expr rule
/// building one: the operator the expr's node, its attachment point,
/// heads.
fn enclosing(rule: &Rule) -> Option<Arc<Op>> {
    let parent = rule.parent_rule.as_ref()?;
    if "expr" != parent.name.as_ref() {
        return None;
    }
    let node = linked_node(Some(parent));
    if is_unbound_ternary_op(&node) || is_paren_op(&node) {
        return None;
    }
    op_of(&node)
}

/// Whether a bound preval paren takes the value before it, compared as a
/// suffix is with the operator it would drill into (`a.b[1]` is
/// `(a.b)[1]` when `[` binds no tighter than `.`). A prefix built into an
/// enclosing tree (`expr_inner`) leaves the val holding that tree, not its
/// own value, so the enclosing expression places the paren instead.
fn binds_here(rule: &Rule, op: &Op) -> bool {
    if !bound(op) {
        return true;
    }
    if rule
        .child_rule
        .as_ref()
        .is_some_and(|child| flag(&child.u, INNER))
    {
        return false;
    }
    enclosing(rule).is_none_or(|encl| encl.right <= op.left)
}

/// Whether the paren this expr rule pushed closed the token of a cast: a
/// group (no value before it) on a cast's opener and closer, holding a
/// content the cast's `accept` accepts.
fn cast_here(grammar: &Grammar, rule: &Rule) -> bool {
    let Some(child) = rule.child_rule.as_ref() else {
        return false;
    };
    if "paren" != child.name.as_ref() || !flag(&child.u, PAREN_GROUP) {
        return false;
    }
    let Some(Value::String(name)) = child.u.get(PAREN_OP) else {
        return false;
    };
    let Some(group) = grammar.parens.iter().find(|op| &op.name == name) else {
        return false;
    };
    let Some(cast) = grammar.cast.get(&group.otin) else {
        return false;
    };
    let Some(accept) = &cast.accept else {
        return false;
    };
    let node = rule.child_value();
    cast.ctin == group.ctin && is_op(&node) && 2 == node_length(&node) && {
        let content = term_at(&node, 1);
        accept.accepts(&content)
    }
}

/// Whether this rule's context separates on `,`.
fn separated_here(rule: &Rule) -> bool {
    0 < counter(rule, "expr_sep")
}

/// Whether the paren this rule opened has a separated content.
fn separated_paren(grammar: &Grammar, rule: &Rule) -> bool {
    opened_paren(grammar, rule).is_some_and(|op| op.content.separated)
}

/// Collect a term of a separated paren content. The terms go into a node
/// of the arena of their own, pushed in place, which the rule's `u` names:
/// a list kept in `u` itself would be copied out and back at every
/// separator, since the rules pushed in between share `u`, and an argument
/// list would cost time quadratic in its length. The node is bookkeeping,
/// not part of the expression, so it counts against no expression's size.
fn collect_paren_item(rule: &mut Rule, term: Value) {
    let items = match rule.u.get(PAREN_ITEMS) {
        Some(items) if node_id(items).is_some() => items.clone(),
        _ => {
            let items = new_node(None, None, Vec::new());
            rule.u_mut().insert(PAREN_ITEMS.to_string(), items.clone());
            items
        }
    };
    with_node_mut(&items, |entry| entry.terms.push(term));
}

/// The terms a separated paren content collected at its separators.
fn paren_items(rule: &Rule) -> Vec<Value> {
    rule.u
        .get(PAREN_ITEMS)
        .and_then(terms_of)
        .unwrap_or_default()
}

/// The term a paren holds when it closes or meets a separator: its own
/// node, or the child's when it has none yet (see `close_paren`).
fn paren_term(rule: &Rule) -> Value {
    let node = node_of(rule);
    if node.is_undefined() {
        rule.child_node.clone()
    } else {
        node
    }
}

/// Place a bound preval paren after an expression, as [`prattify`] places
/// a suffix: drilling into the last term while the operator heading it
/// binds no tighter than the paren, and wrapping the rest, in place.
/// Returns the node the paren heads, `[op, target]`, which the paren's
/// content then extends.
fn prattify_postfix(expr: &Value, op: &OpRef) -> Value {
    let new = &op.op;
    let mut expr = expr.clone();
    loop {
        let Some(expr_op) = op_of(&expr) else {
            return op.node(vec![expr]);
        };
        if !expr_op.suffix && expr_op.right <= new.left {
            let end = expr_op.terms;
            let last = term_at(&expr, end);
            if op_of(&last).is_some_and(|last_op| last_op.prefix && last_op.right < new.left) {
                expr = last;
                continue;
            }
            let node = op.node_under(vec![last], &expr);
            set_term(&expr, end, node.clone());
            return node;
        }
        let prior = dup_node(&expr);
        update_expr_node(&expr, Some(new.clone()), op.token.clone(), vec![prior]);
        return expr;
    }
}

// ---------------------------------------------------------------------------
// The plugin
// ---------------------------------------------------------------------------

/// Install the expression grammar on a parser that already carries the
/// jsonic base rules (`val`, `map`, `list`, `pair`, `elem`).
///
/// This is the plugin body; most callers want [`plugin`], [`apply`] or
/// [`make`].
pub fn expr(parser: &mut Tabnas, options: &ExprOptions) -> Result<(), PluginError> {
    let rules = parser.rule_names();

    // A re-run on an instance that already carries the grammar must not
    // give it a second copy of every alternate. A derived instance starts
    // from an empty rule set and so installs normally.
    if rules.iter().any(|name| "expr" == name) {
        return Ok(());
    }

    // The plugin hangs its operator alternates on the base grammar's
    // `val` rule. On a bare engine there is nothing to hang them on, and
    // the parse would fail later with a message about the document.
    if !rules.iter().any(|name| "val" == name) {
        return Err(PluginError(
            "tabnas-expr: the instance carries no `val` rule. This plugin layers on the \
             jsonic base grammar; install that first (tabnas_jsonic::jsonic, or \
             tabnas_expr::make)."
                .into(),
        ));
    }

    let ops = resolve_options(options);

    // A key operator registers no token: a fold recognises it by a map's
    // shape. The table is still checked here, as the canonical plugin
    // checks it when it installs, so two key operators on one member name
    // are refused when the grammar is built rather than at the first fold.
    if let Err(error) = make_key_map(&ops) {
        return Err(PluginError(format!(
            "tabnas-expr: {error} [{}]",
            error.code()
        )));
    }

    let prefix = make_op_map(parser, &ops, Anyfix::Prefix);
    let suffix = make_op_map(parser, &ops, Anyfix::Suffix);
    let infix = make_op_map(parser, &ops, Anyfix::Infix);
    let ternary = make_op_map(parser, &ops, Anyfix::Ternary);
    // Several paren operators may share an opener: a group, whose preval
    // is inactive, and a call or a subscript, whose preval is active. A
    // value before the opener selects the preval one, and no value the
    // group, so `(e)` and `e()` are different operators. Each map gives,
    // for an opener, the operator of one of the two forms: the last
    // declared of its kind, and for the group, failing an operator whose
    // preval is inactive, the last whose preval is active and not
    // required, which serves both forms as a lone operator always has.
    let parens = make_paren_ops(parser, &ops);
    let mut paren_plain: IndexMap<Tin, Arc<Op>> = IndexMap::new();
    let mut paren_preval: IndexMap<Tin, Arc<Op>> = IndexMap::new();
    for op in &parens {
        if op.preval.active {
            paren_preval.insert(op.otin, op.clone());
        }
        let group = paren_plain.get(&op.otin);
        if !op.preval.active
            || (!op.preval.required && group.is_none_or(|group| group.preval.active))
        {
            paren_plain.insert(op.otin, op.clone());
        }
    }
    let cast = make_cast_ops(parser, &ops);
    // Separators: a comma separates in a paren whose content is separated,
    // and, once an infix operator on `,` is declared a separator, in lists
    // and maps too.
    let mut tin_sep: Vec<Tin> = vec![TIN_CA];
    for op in infix.values() {
        if "," == op.src && !tin_sep.contains(&op.tin) {
            tin_sep.push(op.tin);
        }
    }
    let has_separator = infix.values().any(|op| op.separator);
    let separating = has_separator || parens.iter().any(|op| op.content.separated);
    let has_required = parens.iter().any(|op| op.content.required);
    let has_bound = paren_preval.values().any(|op| bound(op));
    let mut tin_open: Vec<Tin> = Vec::new();
    let mut tin_close: Vec<Tin> = Vec::new();
    for op in &parens {
        if !tin_open.contains(&op.otin) {
            tin_open.push(op.otin);
        }
        if !tin_close.contains(&op.ctin) {
            tin_close.push(op.ctin);
        }
    }

    let bound_tins = |index: usize| -> Vec<Tin> {
        ternary
            .values()
            .filter(|op| Some(index) == op.ternary_index && bound_ternary(op))
            .map(|op| op.tin)
            .collect()
    };
    let tin_tern0b = bound_tins(0);
    let tin_tern1b = bound_tins(1);
    let host_values: Vec<Tin> = options
        .values
        .iter()
        .map(|name| parser.token(name.clone()))
        .collect();

    let grammar = Arc::new(Grammar {
        tin_prefix: prefix.keys().copied().collect(),
        tin_suffix: suffix.keys().copied().collect(),
        tin_infix: infix.keys().copied().collect(),
        tin_tern0: ternary
            .values()
            .filter(|op| Some(0) == op.ternary_index)
            .map(|op| op.tin)
            .collect(),
        tin_tern1: ternary
            .values()
            .filter(|op| Some(1) == op.ternary_index)
            .map(|op| op.tin)
            .collect(),
        tin_open,
        tin_close,
        prefix,
        suffix,
        infix,
        ternary,
        parens,
        paren_plain,
        paren_preval,
        evaluate: options.evaluate.clone(),
        cast,
        tin_sep,
        separating,
        has_separator,
        has_required,
        has_bound,
        no_juxtapose: Some(false) == options.juxtapose,
        tin_tern0b,
        tin_tern1b,
        host_values,
    });

    comment_before_fixed(parser, &grammar);

    // Release the previous parse's expression nodes when no parse this
    // crate drives is in flight. A caller driving the engine directly
    // therefore holds its result's nodes until the next parse on the
    // thread, which is when to call `realize`.
    parser.parse_prepare(|_context: &mut Context| release_arena());

    bound_expression_size(parser, options.node_limit.unwrap_or(NODE_LIMIT));

    install_val(parser, &grammar);
    install_list(parser, &grammar);
    install_map(parser, &grammar);
    install_elem(parser, &grammar);
    install_pair(parser, &grammar);
    install_expr(parser, &grammar);
    if grammar.has_paren() {
        install_paren(parser, &grammar);
    }
    if grammar.has_ternary() {
        install_ternary(parser, &grammar);
    }

    Ok(())
}

/// Keep a comment opening marker out of the fixed-token matcher's reach.
///
/// The canonical plugin moves the comment matcher in front of the fixed
/// one, because an operator such as `/` would otherwise cut `//` into two
/// operator tokens and a comment would never be recognised. This engine's
/// matcher families sit in fixed priority bands, so the same effect comes
/// from a `check` on the fixed family: where a comment starts, the fixed
/// matcher stands aside and the comment matcher takes the run.
///
/// It is installed whenever some operator source really is a prefix of a
/// comment marker, INCLUDING on a host that already configured
/// `options.fixed.check`. Omitting it there left the host's check in place
/// and the `/` operator ahead of `//` and `/*`, so a valid comment lexed
/// as operators and the document failed; the canonical runs a host check
/// and lexes comments correctly at the same time, because reordering the
/// matchers means the fixed family, its check included, is never reached
/// at a comment opener. Standing aside there is the same behaviour.
///
/// A host check is DISPLACED rather than chained. `LexCheck` holds its
/// callback privately and the engine offers no way to run one from
/// outside, so the check installed here cannot call through to the one it
/// replaces; everywhere but a contested comment opener it returns
/// `Continue`, which is what the fixed family does with no check at all. A
/// host that needs both installs its own check AFTER this plugin and skips
/// the comment openers itself.
fn comment_before_fixed(parser: &mut Tabnas, grammar: &Grammar) {
    let options = parser.config();
    let markers: Vec<String> = options
        .comment
        .definitions
        .values()
        .filter(|def| def.lex)
        .map(|def| def.start.clone())
        .filter(|start| !start.is_empty())
        .collect();
    if markers.is_empty() {
        return;
    }

    let sources: Vec<String> = grammar
        .prefix
        .values()
        .chain(grammar.suffix.values())
        .chain(grammar.infix.values())
        .chain(grammar.ternary.values())
        .map(|op| op.src.clone())
        .chain(
            grammar
                .parens
                .iter()
                .flat_map(|op| [op.osrc.clone(), op.csrc.clone()]),
        )
        .filter(|src| !src.is_empty())
        .collect();

    let contested: Vec<String> = markers
        .into_iter()
        .filter(|marker| {
            sources
                .iter()
                .any(|src| src.len() < marker.len() && marker.starts_with(src.as_str()))
        })
        .collect();
    if contested.is_empty() {
        return;
    }

    parser.lex_check_ref(COMMENT_FIRST, move |remaining: &str| {
        if contested
            .iter()
            .any(|marker| remaining.starts_with(marker.as_str()))
        {
            tabnas::LexCheckResult::Skip
        } else {
            tabnas::LexCheckResult::Continue
        }
    });
    let _ = parser.grammar_json(COMMENT_FIRST_DOCUMENT);
}

/// Refuse an expression that has outgrown [`NODE_LIMIT`], or the limit the
/// options set ([`ExprOptions::node_limit`]), and a rule stack past
/// [`RULE_LIMIT`].
///
/// The check is a parse guard, which the engine runs at every step and
/// keeps apart from the parse budget: a budget a caller sets after the
/// grammar is installed replaces the one slot the budget has, and the limit
/// went with it when the check rode there, and a check every few steps let
/// an expression that outgrew the limit in its last steps through.
fn bound_expression_size(parser: &mut Tabnas, limit: usize) {
    parser.parse_guard(LIMIT_GUARD, move |context: &Context| {
        LARGEST.with(Cell::get) <= limit && context.rule_stack.len() <= RULE_LIMIT
    });
}

/// The name of the parse guard [`bound_expression_size`] installs.
const LIMIT_GUARD: &str = "expr-limits";

const COMMENT_FIRST: &str = "@expr-comment-before-fixed";
const COMMENT_FIRST_DOCUMENT: &str =
    r#"{"options":{"fixed":{"check":"@expr-comment-before-fixed"}}}"#;

// ---------------------------------------------------------------------------
// val
// ---------------------------------------------------------------------------

fn install_val(parser: &mut Tabnas, grammar: &Arc<Grammar>) {
    let grammar = grammar.clone();
    parser.define_rule("val", move |spec| {
        // Implicit pair not allowed inside a ternary: the `2:` of `1?2:3`
        // is the ternary's second operator, not a pair key.
        if grammar.has_ternary() && grammar.tin_tern1.contains(&TIN_CL) {
            for alt in spec.open.iter_mut().filter(|alt| group_has(&alt.g, "pair")) {
                let previous = alt.c_fn.clone();
                alt.c_fn = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
                    previous
                        .as_ref()
                        .is_none_or(|condition| condition(rule, context))
                        && 0 == counter(rule, "expr_ternary")
                }));
            }
        }

        // With `juxtapose: false`, the base grammar's implicit list of
        // values side by side is refused inside a paren group, where the
        // paren rule allows implicits again, and after a value an
        // expression made (its val pushed an expr rule: `-a b`): no
        // alternate takes the second value, and the parse fails on it with
        // `unexpected`.
        if grammar.no_juxtapose {
            for alt in spec.close.iter_mut().filter(|alt| {
                group_has(&alt.g, "imp")
                    && group_has(&alt.g, "space")
                    && group_has(&alt.g, "jsonic")
            }) {
                let previous = alt.c_fn.clone();
                alt.c_fn = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
                    previous
                        .as_ref()
                        .is_none_or(|condition| condition(rule, context))
                        && 0 == counter(rule, "expr_paren")
                        && rule
                            .child_rule
                            .as_ref()
                            .is_none_or(|child| "expr" != child.name.as_ref())
                }));
            }
        }

        let mut open: Vec<AltSpec> = Vec::new();

        // The prefix operator of the first term of an expression.
        if grammar.has_prefix() {
            let mut alt = on(&grammar.tin_prefix);
            alt.b = 1;
            alt.n = counters(&[("expr_prefix", 1), ("expr_suffix", 0)]);
            alt.p = Some("expr".into());
            alt.g = "expr,expr-prefix".into();
            alt.add_action(detach_node);
            open.push(alt);
        }

        // A value followed by an opening paren: `foo(1)`, `a[1]`.
        if grammar.has_paren() {
            let mut alt = on2(&VAL_TINS, &grammar.tin_open);
            alt.b = 1;
            alt.p = Some("expr".into());
            let condition = grammar.clone();
            alt.c_fn = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
                let Some(pdef) = rule
                    .o1()
                    .and_then(|token| condition.paren_preval.get(&token.tin))
                    .cloned()
                else {
                    return false;
                };
                if let Some(allow) = &pdef.preval.allow {
                    let preval = rule.resolve_open_value(0, context);
                    if !allow.contains(&value_string(Some(&preval))) {
                        return false;
                    }
                }
                binds_here(rule, &pdef)
            }));
            alt.u = locals(&[("paren_preval", Value::Bool(true))]);
            alt.g = "expr,expr-paren,expr-paren-preval".into();
            alt.add_action(|rule: &mut Rule, context: &mut Context| {
                let preval = rule.resolve_open_value(0, context);
                set_node(rule, preval);
            });
            open.push(alt);
        }

        // An opening parenthesis. NOTE: this can happen outside an
        // expression.
        if grammar.has_paren() {
            let mut alt = on(&grammar.tin_open);
            alt.b = 1;
            alt.p = Some("expr".into());
            let condition = grammar.clone();
            alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
                rule.o0()
                    .is_some_and(|token| condition.paren_plain.contains_key(&token.tin))
            }));
            alt.g = "expr,expr-paren".into();
            alt.add_action(detach_node);
            open.push(alt);
        }

        prepend_open_all(spec, open);

        let mut close: Vec<AltSpec> = Vec::new();

        // A separator where the context separates (n.expr_sep): the value
        // ends, and the rule that collects the terms takes the comma.
        if grammar.separating {
            let mut alt = on(&grammar.tin_sep);
            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
                separated_here(rule)
            }));
            alt.b = 1;
            alt.g = "expr,expr-sep".into();
            close.push(alt);
        }

        // Comma-op suppression. When a parent rule (an embedding
        // grammar's wrapper rule, say) sets n.no_comma_op, bail at `,`
        // without treating it as the comma operator: the parent then
        // consumes the `,` itself as a separator. Match by `src` on the
        // next infix token, so this works whichever token the embedding
        // grammar uses for `,`.
        if grammar.has_infix() {
            let mut alt = on(&grammar.tin_infix);
            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
                0 < counter(rule, "no_comma_op")
                    && rule.c0().is_some_and(|token| "," == token.src.as_str())
            }));
            alt.b = 1;
            alt.g = "expr,no-comma-op-bail".into();
            close.push(alt);
        }

        // A ternary with a binding power follows a term as an infix
        // operator does: the first term's val becomes the expression, and a
        // later term's ends for the expression it belongs to.
        if grammar.has_bound_ternary() {
            let mut alt = on(&grammar.tin_tern0b);
            alt.b = 1;
            alt.n = counters(&[("expr_prefix", 0), ("expr_suffix", 0)]);
            alt.r_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
                (0 == counter(rule, "expr")).then(|| "expr".to_string())
            }));
            alt.g = "expr,expr-ternary,expr-ternary-bound".into();
            close.push(alt);
        }

        if grammar.has_ternary() {
            let mut alt = on(&grammar.tin_tern0);
            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
                0 == counter(rule, "expr")
            }));
            alt.b = 1;
            alt.r = Some("ternary".into());
            alt.g = "expr,expr-ternary".into();
            close.push(alt);
        }

        // The infix operator following the first term of an expression.
        if grammar.has_infix() {
            let mut alt = on(&grammar.tin_infix);
            alt.b = 1;
            alt.n = counters(&[("expr_prefix", 0), ("expr_suffix", 0)]);
            alt.r_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
                (0 == counter(rule, "expr")).then(|| "expr".to_string())
            }));
            alt.g = "expr,expr-infix".into();
            close.push(alt);
        }

        // The suffix operator following the first term of an expression.
        if grammar.has_suffix() {
            let mut alt = on(&grammar.tin_suffix);
            alt.b = 1;
            alt.n = counters(&[("expr_prefix", 0), ("expr_suffix", 1)]);
            alt.r_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
                (0 == counter(rule, "expr")).then(|| "expr".to_string())
            }));
            alt.g = "expr,expr-suffix".into();
            close.push(alt);
        }

        // The closing parenthesis of an expression.
        if grammar.has_paren() {
            let mut alt = on(&grammar.tin_close);
            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
                0 != counter(rule, "expr_paren")
            }));
            alt.b = 1;
            alt.g = "expr,expr-paren".into();
            close.push(alt);
        }

        // Chain for postfix paren forms. When a val has just produced a
        // value (`a[0]`, `f(0)`, or a parenthesised expression like
        // `(*p)`) and the next token is another preval-active paren-open,
        // push expr, which descends into paren, so the new paren-form
        // picks up this val's node as the preval. Pushing rather than
        // replacing keeps the current val rule alive, so the chained
        // result is still what the parse returns. `paren_preval` is set
        // so the paren close finds it on the grandparent and pushes this
        // node into the new paren expression. This complements the
        // open-time preval alternate above, which only fires on the first
        // preval-paren of an expression: chain-time detection is needed
        // for later parens, because by then the leading value is a
        // produced node rather than a token in the lex buffer.
        if grammar.has_paren() {
            let mut alt = on(&grammar.tin_open);
            alt.b = 1;
            let condition = grammar.clone();
            alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
                let Some(pdef) = rule
                    .c0()
                    .and_then(|token| condition.paren_preval.get(&token.tin))
                    .cloned()
                else {
                    return false;
                };
                let node = node_of(rule);
                if node.is_undefined() {
                    return false;
                }
                if let Some(allow) = &pdef.preval.allow {
                    if !allow.contains(&value_string(Some(&node))) {
                        return false;
                    }
                }
                binds_here(rule, &pdef)
            }));
            alt.p = Some("expr".into());
            alt.u = locals(&[("paren_preval", Value::Bool(true))]);
            alt.g = "expr,expr-paren,expr-paren-preval-chain".into();
            close.push(alt);
        }

        // A bound preval paren that binds looser than the operator whose
        // operand this value is: the value ends, and the expression that
        // operator heads takes the paren as its postfix.
        if grammar.has_bound {
            let mut alt = on(&grammar.tin_open);
            alt.b = 1;
            let condition = grammar.clone();
            alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
                let Some(pdef) = rule
                    .c0()
                    .and_then(|token| condition.paren_preval.get(&token.tin))
                    .cloned()
                else {
                    return false;
                };
                bound(&pdef) && !node_of(rule).is_undefined() && !binds_here(rule, &pdef)
            }));
            alt.g = "expr,expr-paren,expr-postfix".into();
            close.push(alt);
        }

        if grammar.has_ternary() {
            let mut alt = on(&grammar.tin_tern1);
            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
                0 != counter(rule, "expr_ternary")
            }));
            alt.b = 1;
            alt.g = "expr,expr-ternary".into();
            close.push(alt);
        }

        // Do not create an implicit list inside an expression (comma
        // separator).
        let mut comma = on(&[TIN_CA]);
        comma.c_fn = Some(Arc::new(no_implicit_in_expr));
        comma.b = 1;
        comma.g = "expr,list,val,imp,comma,top".into();
        close.push(comma);

        // Do not create an implicit list inside an expression (space
        // separator).
        let mut space = on(&VAL_TINS);
        space.c_fn = Some(Arc::new(no_implicit_in_expr));
        space.b = 1;
        space.g = "expr,list,val,imp,space,top".into();
        close.push(space);

        // A host grammar's value after this one, with `juxtapose: false`:
        // values side by side, refused.
        if grammar.refuse_host_values() {
            let mut alt = on(&grammar.host_values);
            alt.e = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
                rule.c0().cloned()
            }));
            alt.g = "expr,expr-juxtaposed".into();
            close.push(alt);
        }

        prepend_close_all(spec, close);
    });
}

/// Give this rule its own node cell, keeping the value it was seeded with.
///
/// A rule pushed by the engine shares its parent's cell, so a later write
/// to this rule's node would reach the parent too. The canonical engine
/// gives every rule its own `node` field and seeds it by VALUE, and the
/// base grammar's own val alternates reach the same state by resetting the
/// node outright. The alternates this plugin adds to `val` need the seeded
/// value, a partly built expression the operator alternates read back, so
/// they detach instead of resetting.
fn detach_node(rule: &mut Rule, _context: &mut Context) {
    let node = node_of(rule);
    set_node(rule, node);
}

fn no_implicit_in_expr(rule: &mut Rule, _context: &mut Context) -> bool {
    (1 == rule.d && (1 <= counter(rule, "expr") || 1 <= counter(rule, "expr_ternary")))
        || (1 <= counter(rule, "expr_ternary") && 1 <= counter(rule, "expr_paren"))
}

// ---------------------------------------------------------------------------
// list, map, elem, pair
// ---------------------------------------------------------------------------

fn clear_expr_counters(rule: &mut Rule) {
    let counters = rule.n_mut();
    counters.insert("expr".into(), 0);
    counters.insert("expr_prefix".into(), 0);
    counters.insert("expr_suffix".into(), 0);
    counters.insert("expr_paren".into(), 0);
    counters.insert("expr_ternary".into(), 0);
}

fn install_list(parser: &mut Tabnas, grammar: &Arc<Grammar>) {
    let grammar = grammar.clone();
    parser.define_rule("list", move |spec| {
        let flags = grammar.clone();
        spec.prepend_bo(move |rule: &mut Rule, _context: &mut Context| {
            // List elements are new expressions, unless this is an
            // implicit list.
            let implicit = rule
                .prev_rule
                .as_ref()
                .is_some_and(|prev| matches!(prev.u.get("implist"), Some(Value::Bool(true))));
            if !implicit {
                clear_expr_counters(rule);
                // A list separates on `,` once an infix operator on `,`
                // gives way to separators, and otherwise leaves the comma
                // to that operator.
                if flags.separating {
                    let sep = i32::from(flags.has_separator);
                    rule.n_mut().insert("expr_sep".into(), sep);
                }
            }
        });

        let mut close: Vec<AltSpec> = Vec::new();

        if grammar.has_paren() {
            let mut alt = on(&grammar.tin_close);
            // If this is the end of a normal list, consume `]`: it is not
            // a close paren.
            alt.b_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
                let square = rule.c0().is_some_and(|token| TIN_CS == token.tin);
                if square && 0 == counter(rule, "expr_paren") {
                    0
                } else {
                    1
                }
            }));
            alt.g = "expr".into();
            close.push(alt);
        }

        // An implicit list of values side by side ends at a separator of
        // the paren content it is a term of.
        if grammar.separating {
            let mut alt = on(&grammar.tin_sep);
            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
                separated_here(rule)
                    && rule
                        .prev_rule
                        .as_ref()
                        .is_some_and(|prev| flag(&prev.u, "implist"))
            }));
            alt.b = 1;
            alt.g = "expr,expr-sep".into();
            close.push(alt);
        }

        prepend_close_all(spec, close);

        if grammar.has_paren() {
            spec.add_ac(|rule: &mut Rule, _context: &mut Context| {
                propagate_to_paren(rule);
            });
        }
    });
}

fn install_map(parser: &mut Tabnas, grammar: &Arc<Grammar>) {
    let grammar = grammar.clone();
    parser.define_rule("map", move |spec| {
        // Map values are new expressions, and a map separates on `,` as a
        // list does.
        let flags = grammar.clone();
        spec.prepend_bo(move |rule: &mut Rule, _context: &mut Context| {
            clear_expr_counters(rule);
            if flags.separating {
                let sep = i32::from(flags.has_separator);
                rule.n_mut().insert("expr_sep".into(), sep);
            }
        });

        if grammar.has_paren() {
            let mut alt = on(&grammar.tin_close);
            // If this is the end of a normal map, consume `}`: it is not
            // a close paren.
            alt.b_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
                let brace = rule.c0().is_some_and(|token| TIN_CB == token.tin);
                if brace && 0 == counter(rule, "expr_paren") {
                    0
                } else {
                    1
                }
            }));
            alt.g = "expr".into();
            prepend_close_all(spec, vec![alt]);
        }
    });
}

fn install_elem(parser: &mut Tabnas, grammar: &Arc<Grammar>) {
    let grammar = grammar.clone();
    parser.define_rule("elem", move |spec| {
        let mut close: Vec<AltSpec> = Vec::new();

        // An implicit list of values side by side ends at a separator of
        // the paren content it is a term of: the list ends with it.
        if grammar.separating {
            let mut alt = on(&grammar.tin_sep);
            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
                separated_here(rule)
                    && rule
                        .parent_rule
                        .as_ref()
                        .and_then(|parent| parent.prev_rule.clone())
                        .is_some_and(|prev| flag(&prev.u, "implist"))
            }));
            alt.b = 1;
            alt.g = "expr,expr-sep".into();
            close.push(alt);
        }

        if !grammar.has_paren() {
            prepend_close_all(spec, close);
            return;
        }

        // Close an implicit list within parens.
        let mut alt = on(&grammar.tin_close);
        alt.b = 1;
        alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
            0 != counter(rule, "expr_paren")
        }));
        alt.g = "expr,expr-paren,imp,close,list".into();
        close.push(alt);

        // The following element is a paren expression.
        let mut alt = on(&grammar.tin_open);
        alt.b = 1;
        alt.r = Some("elem".into());
        alt.g = "expr,expr-paren,imp,open,list".into();
        close.push(alt);

        prepend_close_all(spec, close);

        // Propagate the collected list to the enclosing paren. A
        // container is copied on write here, so the paren cannot hold the
        // same array the `elem` rules are appending to; it takes the
        // finished one instead. The Go port does the same, for the same
        // reason.
        spec.add_ac(|rule: &mut Rule, _context: &mut Context| {
            propagate_to_paren(rule);
        });
    });
}

/// Write a rule's node onto the paren rule that encloses it.
fn propagate_to_paren(rule: &mut Rule) {
    if 0 == counter(rule, "expr_paren") {
        return;
    }
    let node = node_of(rule);
    let mut cursor = rule.parent_rule.clone();
    while let Some(current) = cursor {
        if "paren" == current.name.as_ref() {
            *current.node.borrow_mut() = node;
            return;
        }
        cursor = current.parent_rule.clone();
    }
}

fn install_pair(parser: &mut Tabnas, grammar: &Arc<Grammar>) {
    let grammar = grammar.clone();
    parser.define_rule("pair", move |spec| {
        if !grammar.has_paren() {
            return;
        }
        // Close an implicit map within parens.
        let mut alt = on(&grammar.tin_close);
        alt.b = 1;
        alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
            0 != counter(rule, "expr_paren") || 0 < counter(rule, "pk")
        }));
        alt.g = "expr,expr-paren,imp,map".into();
        prepend_close_all(spec, vec![alt]);
    });
}

// ---------------------------------------------------------------------------
// expr
// ---------------------------------------------------------------------------

/// The completed expression a top-level implicit list should start with.
///
/// The rule that meets the separator is the last one the Pratt core built,
/// which for a right-leaning tree is a SUB-expression: `1+2*3` leaves it
/// holding `[*,2,3]` while the finished `[+,1,[*,2,3]]` sits on the val
/// this expression publishes to, and on the outermost expr in the
/// replacement chain. Seeding the list from the rule's own node therefore
/// dropped the `1+`, a wrong answer with nothing to signal it.
fn expr_root(rule: &Rule) -> Value {
    let parent = linked_node(rule.parent_rule.as_ref());
    if rule.parent_rule.is_some() && is_op(&parent) {
        return parent;
    }

    // No usable parent. The outermost expr in the chain holds the root;
    // later entries are the sub-expressions built under it.
    let mut root: Option<Value> = None;
    if "expr" == rule.name.as_ref() {
        let node = node_of(rule);
        if is_op(&node) {
            root = Some(node);
        }
    }
    let mut cursor = rule.prev_rule.clone();
    while let Some(current) = cursor {
        if "expr" == current.name.as_ref() {
            let node = current.node.borrow().clone();
            if is_op(&node) {
                root = Some(node);
            }
        }
        cursor = current.prev_rule.clone();
    }

    root.unwrap_or_else(|| node_of(rule))
}

/// Start a top-level implicit list, publishing it to the rule's parent
/// unless there is none.
///
/// A rule seeds its node from its parent, so a list written to a missing
/// parent would be handed straight back out as the starting node of the
/// rules that follow. The rule's own node is what the parse returns at
/// this depth, so skipping the write costs nothing.
fn top_list(rule: &mut Rule) -> Value {
    let list = Value::array(vec![expr_root(rule)]);

    if rule.parent_rule.is_some() {
        write_linked_node(rule.parent_rule.as_ref(), list.clone());
        return list;
    }

    // No parent to publish to. The list is still built correctly by the
    // `elem` rules that follow, but nothing would ever read it: the
    // result would come back as the first member alone. Write it back
    // along the replacement chain instead, so whichever rule the parse
    // returns is holding this list.
    set_node(rule, list.clone());
    let mut cursor = rule.prev_rule.clone();
    while let Some(current) = cursor {
        *current.node.borrow_mut() = list.clone();
        cursor = current.prev_rule.clone();
    }

    list
}

/// Collect an expression into the implicit list its enclosing paren is
/// building, the port of the canonical `implicitList`.
fn implicit_list(mut matched: AltMatch, rule: &mut Rule, context: &mut Context) -> AltMatch {
    // Find the paren rule that contains this implicit list. A map or list
    // rule between the expression and the paren means the expression is
    // inside a contained value, not a direct paren child, so no implicit
    // list is created.
    let mut paren: Option<Rc<RuleSnapshot>> = None;
    let mut paren_index = 0usize;
    for index in (0..context.rule_stack.len()).rev() {
        let frame = &context.rule_stack[index];
        let name = frame.name.as_ref();
        if "paren" == name {
            paren = Some(frame.clone());
            paren_index = index;
            break;
        }
        if "map" == name || "list" == name {
            return matched;
        }
    }

    let Some(paren) = paren else {
        return matched;
    };

    // The node this expression contributes, captured before the write
    // below replaces it with the list. The ROOT, not the attachment
    // point: the canonical port takes it off the rule the paren pushed,
    // which is where `prior_expr` writes the whole expression, so a
    // right-leaning member such as `f(1+2*3, 4)` keeps its `1+`.
    let expr_node = node_of(rule);
    let expr_node = if is_op(&expr_node) {
        expression_root(rule)
    } else {
        expr_node
    };

    // Create the list value for the paren rule, unless one is already
    // being collected, in which case the `elem` rules do the collecting.
    //
    // The canonical port reads and writes this through the paren's own
    // child rule, because a JavaScript array is shared by reference: the
    // rule collecting the list and the paren then hold the same array.
    // This engine copies a container on write, so the list is kept on the
    // paren itself and the `elem` after-close hook puts the finished one
    // back (as the Go port does, for the same reason).
    let paren_node = paren.node.borrow().clone();
    if matches!(&paren_node, Value::Array(members) if !members.is_empty()) {
        // An `elem` rule is already collecting the list, and this
        // expression is one of its members: leave the node alone so that
        // the member, and not the list, is what the collector reads.
        return matched;
    }

    *paren.node.borrow_mut() = Value::array(vec![expr_node.clone()]);
    matched.r = Some("elem".into());
    matched.b = 0;

    let list = paren.node.borrow().clone();
    set_node(rule, list.clone());

    // The rule the first term belongs to holds the list too. The
    // canonical port gets that for nothing, because the rule it writes
    // the list through IS that rule; here the list is kept on the paren,
    // so this write is what the expression's own after-close reads when
    // it reduces the members with an evaluator.
    write_linked_node(rule.parent_rule.as_ref(), list.clone());

    // The rule that sees the comma is not always the paren's own child. A
    // first argument that nests operators, a prefix whose operand is
    // itself a prefix, `f(- -1, 2)`, leaves further rules on the stack
    // between the paren and this rule, all holding the same expression
    // node. Each writes that node back over the paren's when it closes,
    // discarding every element collected after the first. Point them at
    // the implicit list so the close-back is a no-op instead of a
    // truncation.
    //
    // Only the frames that carry this expression: the `expr` rules
    // themselves, and the `val` rules they were pushed from, which hold
    // either nothing yet or the expression node. A rule a host plugin
    // stacked in between has a node of its own to close with, and
    // overwriting it would destroy a value this plugin knows nothing
    // about.
    for index in (paren_index + 1)..context.rule_stack.len() {
        let frame = context.rule_stack[index].clone();
        let name = frame.name.as_ref().to_string();
        let node = frame.node.borrow().clone();
        let carries = "expr" == name
            || ("val" == name
                && (node.is_undefined()
                    || matches!(node, Value::Null)
                    || same_node(&node, &expr_node)
                    || is_op(&node)));
        if carries {
            *frame.node.borrow_mut() = list.clone();
        }
    }

    matched
}

/// Node identity, the canonical `===` on two expression nodes.
fn same_node(left: &Value, right: &Value) -> bool {
    match (node_id(left), node_id(right)) {
        (Some(left), Some(right)) => left == right,
        _ => false,
    }
}

fn install_expr(parser: &mut Tabnas, grammar: &Arc<Grammar>) {
    let grammar = grammar.clone();
    parser.define_rule("expr", move |spec| {
        let mut open: Vec<AltSpec> = Vec::new();

        // A cast: the group just closed (the expr this one replaced holds
        // it, `[group, type]`) heads a prefix expression, `[cast, type]`,
        // whose operand follows. It takes no token: the group was the
        // token.
        if grammar.has_cast() {
            let mut alt = always();
            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
                rule.prev_rule
                    .as_ref()
                    .is_some_and(|prev| flag(&prev.u, CAST_NEXT))
            }));
            alt.n = counters(&[
                ("expr", 1),
                ("expr_prefix", 1),
                ("expr_suffix", 0),
                ("dlist", 1),
                ("dmap", 1),
            ]);
            alt.p = Some("val".into());
            alt.g = "expr,expr-cast".into();
            let ops = grammar.clone();
            alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
                let group = linked_node(rule.prev_rule.as_ref());
                let Some(cast) = op_of(&group).and_then(|gop| ops.cast.get(&gop.otin).cloned())
                else {
                    return;
                };
                let token = with_node(&group, |entry| entry.token.clone()).flatten();
                let op = OpRef::at(&cast, token);
                let prior = rule.parent_rule.clone();
                let node = prior_expr(rule, prior.as_ref(), &op);
                push_term(&node, term_at(&group, 1));
                publish_expr(rule, node.clone());
                // The val that pushed the group's expr reads its node from
                // that expr, its child, when it closes: that expr holds the
                // cast too.
                write_linked_node(rule.prev_rule.as_ref(), node);
            });
            open.push(alt);
        }

        // A bound preval paren after an expression: a postfix operator
        // that takes the expression, or as much of it as it binds tighter
        // than, as its first term, placed as a suffix is
        // (`prattify_postfix`). The paren then parses the content into the
        // same node.
        if grammar.has_bound {
            let mut alt = on(&grammar.tin_open);
            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
                rule.prev_rule
                    .as_ref()
                    .is_some_and(|prev| flag(&prev.u, POSTFIX_NEXT))
            }));
            alt.n = counters(&[("expr", 1), ("expr_prefix", 0), ("dlist", 1), ("dmap", 1)]);
            alt.p = Some("paren".into());
            alt.b = 1;
            alt.g = "expr,expr-paren,expr-postfix".into();
            let ops = grammar.clone();
            alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
                let Some(op) = Grammar::op_use(&ops.paren_preval, rule.o0()) else {
                    return;
                };
                let previous = linked_node(rule.prev_rule.as_ref());
                let node = if is_op(&previous) {
                    prattify_postfix(&previous, &op)
                } else {
                    let prior = rule.prev_rule.clone();
                    prior_expr(rule, prior.as_ref(), &op)
                };
                publish_expr(rule, node.clone());
                rule.u_mut().insert(POSTFIX.to_string(), node);
            });
            open.push(alt);
        }

        // An opening parenthesis of an expression.
        if grammar.has_paren() {
            let mut alt = on(&grammar.tin_open);
            alt.p = Some("paren".into());
            alt.b = 1;
            alt.g = "expr,expr-paren,expr-start".into();
            open.push(alt);
        }

        if grammar.has_prefix() {
            let mut alt = on(&grammar.tin_prefix);
            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
                0 != counter(rule, "expr_prefix")
            }));
            alt.n = counters(&[("expr", 1), ("dlist", 1), ("dmap", 1)]);
            alt.p = Some("val".into());
            alt.g = "expr,expr-prefix".into();
            let ops = grammar.clone();
            alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
                let Some(op) = Grammar::op_use(&ops.prefix, rule.o0()) else {
                    return;
                };
                let parent = linked_node(rule.parent_rule.as_ref());
                // Only fold into the parent's node when it is an
                // expression THIS prefix chain is building (the outer `-`
                // of `--1`). A ternary or paren node on the parent is a
                // foreign seed the engine threaded down, and folding into
                // it would corrupt the wrapper with a stray hole and a
                // duplicated operand. Start a fresh operand expression
                // for those, mirroring the infix guard.
                if is_op(&parent) && !is_unbound_ternary_op(&parent) && !is_paren_op(&parent) {
                    let attach = prattify(&parent, &op);
                    publish_expr(rule, attach);
                    // This prefix is a term of the expression the parent is
                    // building, inside that expression's own tree, so this
                    // rule does not evaluate it: the expression that holds
                    // the root evaluates the whole tree once it ends.
                    rule.u_mut().insert(INNER.to_string(), Value::Bool(true));
                } else {
                    let prior = rule.parent_rule.clone();
                    let node = prior_expr(rule, prior.as_ref(), &op);
                    publish_expr(rule, node);
                }
            });
            open.push(alt);
        }

        if grammar.has_infix() {
            let mut alt = on(&grammar.tin_infix);
            alt.p = Some("val".into());
            alt.n = counters(&[("expr", 1), ("expr_prefix", 0), ("dlist", 1), ("dmap", 1)]);
            alt.g = "expr,expr-infix".into();
            let ops = grammar.clone();
            alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
                let Some(op) = Grammar::op_use(&ops.infix, rule.o0()) else {
                    return;
                };
                let parent = linked_node(rule.parent_rule.as_ref());
                let previous = linked_node(rule.prev_rule.as_ref());

                // Second and further operators.
                if is_op(&parent) && !is_unbound_ternary_op(&parent) {
                    let start = placing_start(rule, &parent, &op.op);
                    let attach = place_infix(&start, &op);
                    publish_expr(rule, attach);
                }
                // The first term was a unary expression.
                else if is_op(&previous) {
                    let attach = place_infix(&previous, &op);
                    if let Some(prev) = rule.prev_rule.clone() {
                        rule.parent_node = Some(prev.node.clone());
                        rule.parent_rule = Some(prev);
                    }
                    publish_expr(rule, attach);
                }
                // The first term was a plain value or a ternary part.
                else {
                    let prior = rule.prev_rule.clone();
                    let node = prior_expr(rule, prior.as_ref(), &op);
                    publish_expr(rule, node);
                }
                placed(rule, &op.op);
            });
            open.push(alt);
        }

        // A ternary with a binding power, placed as an infix operator is:
        // its first term is as much of the expression before it as binds
        // tighter than its `left`. Its middle term is a whole expression of
        // its own, up to the second token, pushed here; the close below
        // takes the second token and pushes its last term.
        if grammar.has_bound_ternary() {
            let mut alt = on(&grammar.tin_tern0b);
            alt.p = Some("val".into());
            alt.n = counters(&[("expr", 1), ("expr_prefix", 0), ("dlist", 1), ("dmap", 1)]);
            alt.g = "expr,expr-ternary,expr-ternary-bound".into();
            let ops = grammar.clone();
            alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
                let Some(op) = Grammar::op_use(&ops.ternary, rule.o0()) else {
                    return;
                };
                let parent = linked_node(rule.parent_rule.as_ref());
                let previous = linked_node(rule.prev_rule.as_ref());

                let attach = if is_op(&parent) && !is_unbound_ternary_op(&parent) {
                    let start = placing_start(rule, &parent, &op.op);
                    place_infix(&start, &op)
                } else if is_op(&previous) {
                    let attach = place_infix(&previous, &op);
                    if let Some(prev) = rule.prev_rule.clone() {
                        rule.parent_node = Some(prev.node.clone());
                        rule.parent_rule = Some(prev);
                    }
                    attach
                } else {
                    let prior = rule.prev_rule.clone();
                    prior_expr(rule, prior.as_ref(), &op)
                };
                placed(rule, &op.op);

                // The middle term is a new expression, bounded by the two
                // tokens as a group is by its parens: its counters start
                // again (a comma there is the comma operator), and those of
                // this expression come back for the last term.
                let saved = [
                    (TERN_PAREN, counter(rule, "expr_paren")),
                    (TERN_SEP, counter(rule, "expr_sep")),
                    (TERN_TERNARY, counter(rule, "expr_ternary")),
                ];
                let u = rule.u_mut();
                u.insert(TERN_NAME.into(), Value::String(op.op.name.clone()));
                u.insert(TERN_STEP.into(), Value::Number(1.0));
                for (name, value) in saved {
                    u.insert(name.into(), Value::Number(f64::from(value)));
                }
                // The middle term's val starts with no node, as a paren's
                // content does: a rule is handed its parent's node, and this
                // one's is the ternary, whose next term the middle term is
                // not placed as. The before-close puts it back.
                u.insert(TERN_NODE.into(), attach);
                u.remove(ATTACH);
                let n = rule.n_mut();
                n.insert("expr".into(), 0);
                n.insert("expr_paren".into(), 0);
                n.insert("expr_sep".into(), 0);
                n.insert("expr_ternary".into(), 1);
                set_node(rule, Value::Undefined);
            });
            open.push(alt);
        }

        if grammar.has_suffix() {
            let mut alt = on(&grammar.tin_suffix);
            alt.n = counters(&[("expr", 1), ("expr_prefix", 0), ("dlist", 1), ("dmap", 1)]);
            alt.g = "expr,expr-suffix".into();
            let ops = grammar.clone();
            alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
                let Some(op) = Grammar::op_use(&ops.suffix, rule.o0()) else {
                    return;
                };
                let previous = linked_node(rule.prev_rule.as_ref());
                if is_op(&previous) {
                    let attach = prattify(&previous, &op);
                    // The suffix took over the val of the expression's
                    // first term, whose node holds the root (`-1!`, `(1)!`):
                    // the root is evaluated from there, as the infix after
                    // a unary expression does. A suffix that took over an
                    // expr rule already has the first term's val as its
                    // parent.
                    if let Some(prev) = rule.prev_rule.clone() {
                        if "val" == prev.name.as_ref() {
                            rule.parent_node = Some(prev.node.clone());
                            rule.parent_rule = Some(prev);
                        }
                    }
                    publish_expr(rule, attach);
                } else {
                    let prior = rule.prev_rule.clone();
                    let node = prior_expr(rule, prior.as_ref(), &op);
                    publish_expr(rule, node);
                }
            });
            open.push(alt);
        }

        prepend_open_all(spec, open);

        // Append the final term to the expression.
        spec.add_bc(|rule: &mut Rule, _context: &mut Context| {
            let mut child = rule.child_node.clone();

            // A ternary with a binding power, back from its middle term,
            // has its node back (see the open alternate above). The middle
            // term's val was handed this rule's emptied cell, so its value
            // is read before the node is put back.
            match local_number(rule, TERN_STEP) {
                1 => {
                    child = rule.child_value();
                    let node = rule.u.get(TERN_NODE).cloned().unwrap_or(Value::Undefined);
                    rule.u_mut().insert(ATTACH.to_string(), node.clone());
                    set_node(rule, node);
                }
                // Back from its last term: the ternary is whole.
                2 => set_local_number(rule, TERN_STEP, 3),
                _ => {}
            }

            let node = node_of(rule);
            let Some(op) = op_of(&node) else {
                return;
            };
            if term_count(&node) < op.terms && !same_node(&node, &child) {
                push_term(&node, child);
            }
        });

        let mut close: Vec<AltSpec> = Vec::new();

        if grammar.has_bound_ternary() {
            // The second token of a ternary with a binding power, after its
            // middle term: its last term follows, an operand of this
            // expression, with this expression's counters back.
            let mut alt = on(&grammar.tin_tern1b);
            let condition = grammar.clone();
            alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
                1 == local_number(rule, TERN_STEP)
                    && rule
                        .c0()
                        .and_then(|token| condition.ternary.get(&token.tin))
                        .is_some_and(|op| {
                            matches!(rule.u.get(TERN_NAME), Some(Value::String(name)) if name == &op.name)
                        })
            }));
            alt.p = Some("val".into());
            alt.g = "expr,expr-ternary,expr-ternary-bound".into();
            alt.add_action(|rule: &mut Rule, _context: &mut Context| {
                let saved = [
                    ("expr_paren", local_number(rule, TERN_PAREN)),
                    ("expr_sep", local_number(rule, TERN_SEP)),
                    ("expr_ternary", local_number(rule, TERN_TERNARY)),
                ];
                let n = rule.n_mut();
                for (name, value) in saved {
                    n.insert(name.into(), value as i32);
                }
                n.insert("expr".into(), 1);
                n.insert("expr_prefix".into(), 0);
                n.insert("expr_suffix".into(), 0);
                set_local_number(rule, TERN_STEP, 2);
            });
            close.push(alt);

            // Anything else after its middle term: the ternary is
            // unfinished, and refused there.
            let mut alt = always();
            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
                1 == local_number(rule, TERN_STEP)
            }));
            alt.e = Some(Arc::new(|_rule: &mut Rule, context: &mut Context| {
                context.t0().cloned()
            }));
            alt.g = "expr,expr-ternary,expr-ternary-bound,unfinished".into();
            close.push(alt);
        }

        // A group the table's cast accepts: the expression goes on as a
        // cast whose operand follows (the open alternate above), so this
        // close keeps n.expr and nothing evaluates the group yet. Inside a
        // list, a map or a paren, n.expr is zero by descent, and the
        // after-close would evaluate the group.
        if grammar.has_cast() {
            let mut alt = always();
            let condition = grammar.clone();
            alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
                cast_here(&condition, rule)
            }));
            alt.n = counters(&[("expr", 1)]);
            alt.r = Some("expr".into());
            alt.u = locals(&[(CAST_NEXT, Value::Bool(true))]);
            alt.g = "expr,expr-cast".into();
            close.push(alt);
        }

        // A postfix paren's expression goes on after the paren, as a
        // suffix's does, so it takes the alternates below.
        let mut alt = always();
        alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
            rule.child_rule
                .as_ref()
                .is_some_and(|child| "paren" == child.name.as_ref())
                && !rule.u.contains_key(POSTFIX)
        }));
        alt.n = counters(&[("expr", 0)]);
        alt.g = "expr,expr-end,expr-paren-end".into();
        close.push(alt);

        // Comma-op suppression. When n.no_comma_op is set by a parent
        // rule, terminate the expression at `,` without treating it as
        // the comma operator. Closing the expression frame lets the
        // parent rule regain control before any comma-op alternate below
        // fires.
        if grammar.has_infix() {
            let mut alt = on(&grammar.tin_infix);
            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
                0 < counter(rule, "no_comma_op")
                    && rule.c0().is_some_and(|token| "," == token.src.as_str())
            }));
            alt.b = 1;
            alt.n = counters(&[("expr", 0)]);
            alt.g = "expr,no-comma-op-bail".into();
            close.push(alt);
        }

        // A separator where the context separates: the expression ends,
        // and the rule that collects the terms takes the comma.
        if grammar.separating {
            let mut alt = on(&grammar.tin_sep);
            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
                separated_here(rule)
            }));
            alt.b = 1;
            alt.n = counters(&[("expr", 0)]);
            alt.g = "expr,expr-sep".into();
            close.push(alt);
        }

        if grammar.has_infix() {
            // Complete the prefix first.
            let mut alt = on(&grammar.tin_infix);
            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
                0 == counter(rule, "expr_prefix")
            }));
            alt.b = 1;
            alt.r = Some("expr".into());
            alt.g = "expr,expr-infix,expr-prefix".into();
            close.push(alt);

            let mut alt = on(&grammar.tin_infix);
            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
                0 != counter(rule, "expr_prefix")
            }));
            alt.b = 1;
            alt.g = "expr,expr-infix".into();
            close.push(alt);
        }

        if grammar.has_suffix() {
            let mut alt = on(&grammar.tin_suffix);
            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
                0 == counter(rule, "expr_prefix")
            }));
            alt.b = 1;
            alt.r = Some("expr".into());
            alt.g = "expr,expr-suffix,expr-prefix".into();
            close.push(alt);

            // A suffix after a prefix expression: complete the prefix
            // first, as the infix alternate above does, and leave the
            // suffix to the expression the prefix belongs to, which drills
            // it into the prefix (`-1!` is `-(1!)`). The expression goes
            // on, so this close keeps n.expr, and nothing evaluates it
            // here: the after-close below evaluates an expression only
            // once it has ended, and the expression the suffix extends
            // evaluates the whole tree.
            let mut alt = on(&grammar.tin_suffix);
            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
                0 != counter(rule, "expr_prefix")
            }));
            alt.b = 1;
            alt.g = "expr,expr-suffix,expr-prefix".into();
            close.push(alt);
        }

        // A bound preval paren after this expression: a postfix that the
        // next expr rule places, as the suffix alternate above does. After
        // a prefix expression the prefix completes first, as for a suffix,
        // and the paren is left to the expression the prefix belongs to.
        if grammar.has_bound {
            let mut alt = on(&grammar.tin_open);
            let condition = grammar.clone();
            alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
                rule.c0()
                    .is_some_and(|token| condition.postfix_opener(token.tin))
                    && 0 == counter(rule, "expr_prefix")
            }));
            alt.b = 1;
            alt.r = Some("expr".into());
            alt.u = locals(&[(POSTFIX_NEXT, Value::Bool(true))]);
            alt.g = "expr,expr-paren,expr-postfix".into();
            close.push(alt);

            let mut alt = on(&grammar.tin_open);
            let condition = grammar.clone();
            alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
                rule.c0()
                    .is_some_and(|token| condition.postfix_opener(token.tin))
                    && 0 != counter(rule, "expr_prefix")
            }));
            alt.b = 1;
            alt.g = "expr,expr-paren,expr-postfix,expr-prefix".into();
            close.push(alt);
        }

        if grammar.has_paren() {
            let mut alt = on(&grammar.tin_close);
            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
                0 != counter(rule, "expr_paren")
            }));
            alt.b = 1;
            alt.g = "expr".into();
            close.push(alt);
        }

        // A ternary with a binding power after this expression, placed as
        // an infix operator is.
        if grammar.has_bound_ternary() {
            let mut alt = on(&grammar.tin_tern0b);
            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
                0 == counter(rule, "expr_prefix")
            }));
            alt.b = 1;
            alt.r = Some("expr".into());
            alt.g = "expr,expr-ternary,expr-ternary-bound".into();
            close.push(alt);
        }

        if grammar.has_ternary() {
            let mut alt = on(&grammar.tin_tern0);
            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
                0 == counter(rule, "expr_prefix")
            }));
            alt.b = 1;
            alt.r = Some("ternary".into());
            alt.g = "expr,expr-ternary".into();
            close.push(alt);

            // A ternary after a prefix expression: complete the prefix
            // first, as for an infix or a suffix, and leave the ternary to
            // the expression the prefix belongs to, which takes it as a
            // whole (`-a ? b : c` is `(-a) ? b : c`). The expression goes
            // on, so this close keeps n.expr and nothing evaluates it here.
            // Without it, inside a paren, `(-a ? b : c)`, the `?` reached
            // the implicit list below and was refused.
            let mut alt = on(&grammar.tin_tern0);
            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
                0 != counter(rule, "expr_prefix")
            }));
            alt.b = 1;
            alt.g = "expr,expr-ternary,expr-prefix".into();
            close.push(alt);

            // The `:` of a ternary whose middle term this expression is:
            // the expression ends there, and the ternary takes the `:`.
            // Without it, inside a paren, `(a ? b + c : d)` and
            // `(a ? -b : c)`, the `:` reached the implicit list below and
            // was refused.
            let mut alt = on(&grammar.tin_tern1);
            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
                0 != counter(rule, "expr_ternary")
            }));
            alt.b = 1;
            alt.g = "expr,expr-ternary".into();
            close.push(alt);
        }

        // Implicit list at the top level, comma separated.
        let mut alt = on(&[TIN_CA]);
        alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
            0 == rule.d
        }));
        alt.n = counters(&[("expr", 0)]);
        alt.r = Some("elem".into());
        alt.add_action(|rule: &mut Rule, _context: &mut Context| {
            let list = top_list(rule);
            set_node(rule, list);
        });
        alt.g = "expr,comma,list,top".into();
        close.push(alt);

        // Implicit list at the top level, space separated, unless values
        // side by side are refused.
        let mut alt = on(&VAL_TINS);
        let no_juxtapose = grammar.no_juxtapose;
        alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
            0 == rule.d && !no_juxtapose
        }));
        alt.n = counters(&[("expr", 0)]);
        alt.b = 1;
        alt.r = Some("elem".into());
        alt.add_action(|rule: &mut Rule, _context: &mut Context| {
            let list = top_list(rule);
            set_node(rule, list);
        });
        alt.g = "expr,space,list,top".into();
        close.push(alt);

        // Implicit list indicated by a comma.
        let mut alt = on(&[TIN_CA]);
        alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
            rule.lte("pk", 0)
        }));
        alt.n = counters(&[("expr", 0)]);
        alt.b = 1;
        alt.h_match = Some(Arc::new(|matched, rule, context, _next| {
            implicit_list(matched, rule, context)
        }));
        alt.g = "expr,list,val,imp,comma".into();
        close.push(alt);

        // Implicit list indicated by a space separated value.
        //
        // This alternate carries no token filter, so it also has to be
        // kept off a pending suffix operator. A suffix belongs to the
        // expression that just closed, not to a new element: `f(@x!)`
        // reaches here on the `!` of a completed prefix, opens `elem`,
        // and offers `!` as the start of a value, which nothing matches,
        // so a valid expression fails as unexpected. Leaving the token
        // alone lets the val-close suffix alternate take it, which is how
        // the same expression already parses at the top level.
        let mut alt = always();
        let condition = grammar.clone();
        alt.c_fn = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
            let next = context.t0().map(|token| token.tin);
            rule.lte("pk", 0)
                && rule.lte("expr_suffix", 0)
                && !next.is_some_and(|tin| condition.tin_suffix.contains(&tin))
                && !(condition.no_juxtapose && next.is_some_and(|tin| condition.starts_value(tin)))
        }));
        alt.n = counters(&[("expr", 0)]);
        alt.h_match = Some(Arc::new(|matched, rule, context, _next| {
            implicit_list(matched, rule, context)
        }));
        alt.g = "expr,list,val,imp,space".into();
        close.push(alt);

        // The expression ends on a non-expression token, but never at a
        // host grammar's value with `juxtapose: false`, which is refused
        // here.
        let mut alt = always();
        let condition = grammar.clone();
        alt.c_fn = Some(Arc::new(move |_rule: &mut Rule, context: &mut Context| {
            !condition.host_value(context.t0().map(|token| token.tin))
        }));
        alt.n = counters(&[("expr", 0)]);
        alt.g = "expr,expr-end".into();
        close.push(alt);

        prepend_close_all(spec, close);

        // Put the ROOT of the expression back on the node, so the last
        // rule of a replacement chain hands the whole expression to the
        // rule that collects it, rather than the sub-expression the last
        // operator attached to. Only while the node still IS the
        // attachment point: a close alternate that produced an implicit
        // list has replaced it deliberately.
        spec.add_ac(|rule: &mut Rule, _context: &mut Context| {
            // Not while a ternary with a binding power reads its last term:
            // the close that pushed it keeps the ternary on the node, where
            // the before-close appends the term when it is back.
            if 2 == local_number(rule, TERN_STEP) {
                return;
            }
            if is_op(&node_of(rule)) {
                let root = expression_root(rule);
                set_node(rule, root);
            }
        });

        // Evaluate at the root of the expression, where n.expr is zero.
        if let Some(evaluate) = grammar.evaluate.clone() {
            spec.add_ac(move |rule: &mut Rule, context: &mut Context| {
                if 0 != counter(rule, "expr") {
                    return;
                }
                // Evaluation follows the tree the S-expression shows, so an
                // expression is evaluated once, whole, from its root, once
                // it has ended. A prefix inside an operand of an enclosing
                // expression (`-2` in `1+-2`) was built into that
                // expression's tree: evaluating here evaluated the
                // enclosing tree too, before it was complete, and then
                // again when it was.
                if matches!(rule.u.get(INNER), Some(Value::Bool(true))) {
                    return;
                }
                let Some(parent) = rule.parent_rule.clone() else {
                    return;
                };
                let parent_node = parent.node.borrow().clone();

                // The parent holds an implicit list (`f(1+2, 3)`,
                // `1+2, 3`) rather than this expression's own node. A
                // list is a plain array, not an expression node, so its
                // members would otherwise reach the caller as raw
                // S-expressions the evaluator was never called on.
                //
                // Reduce them in place, keeping the array: the list is
                // still being collected, and the paren rule and the expr
                // rules between it and here all hold a reference to this
                // exact array, so replacing it would strand the members
                // still to come. A member already reduced is returned
                // untouched rather than reduced again.
                if let Value::Array(members) = &parent_node {
                    let mut site = EvalSite::new(Some(parent.clone()), context);
                    let reduced: Vec<Value> = members
                        .iter()
                        .map(|member| evaluation(&mut site.reborrow(), member, &evaluate))
                        .collect();
                    let reduced = Value::array(reduced);
                    *parent.node.borrow_mut() = reduced.clone();
                    // Through the shared cell, not into a fresh one: the
                    // rule that collects the rest of the list was already
                    // seeded from this cell, and the canonical port keeps
                    // the one array for the same reason.
                    publish(rule, reduced);
                    return;
                }

                // The parent node holds the root of the expression tree.
                let out = {
                    let mut site = EvalSite::new(Some(parent.clone()), context);
                    evaluation(&mut site, &parent_node, &evaluate)
                };
                *parent.node.borrow_mut() = out.clone();

                // A cast took over its group's expr rule, which the val that
                // pushed it reads its node from when it closes.
                if rule
                    .prev_rule
                    .as_ref()
                    .is_some_and(|prev| flag(&prev.u, CAST_NEXT))
                {
                    write_linked_node(rule.prev_rule.as_ref(), out.clone());
                }

                // Also write the evaluated result onto this rule's own
                // node. When the expr rule was PUSHED from a still-open
                // val (the prefix and paren forms, `+1`, `(a)`), that
                // val's close coalescing reads its child's node, which is
                // this rule, and would otherwise restore the raw
                // S-expression and discard the evaluated value.
                publish(rule, out);
            });
        }
    });
}

// ---------------------------------------------------------------------------
// paren
// ---------------------------------------------------------------------------

fn paren_depth(name: &str) -> String {
    format!("expr_paren_depth_{name}")
}

fn install_paren(parser: &mut Tabnas, grammar: &Arc<Grammar>) {
    let grammar = grammar.clone();
    parser.define_rule("paren", move |spec| {
        // Allow implicits inside parens.
        spec.add_bo(|rule: &mut Rule, _context: &mut Context| {
            let counters = rule.n_mut();
            counters.insert("dmap".into(), 0);
            counters.insert("dlist".into(), 0);
            counters.insert("pk".into(), 0);
        });

        let mut open: Vec<AltSpec> = Vec::new();

        // A paren whose content is required may not be empty: `()` is
        // refused at its closer, where a content was due.
        if grammar.has_required {
            let mut alt = on2(&grammar.tin_open, &grammar.tin_close);
            let condition = grammar.clone();
            alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
                let close = rule.o1().map(|token| token.tin);
                paren_op_for(&condition, rule)
                    .is_some_and(|op| Some(op.ctin) == close && op.content.required)
            }));
            alt.e = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
                rule.o1().cloned()
            }));
            alt.g = "expr,expr-paren,empty,required".into();
            open.push(alt);
        }

        // Empty parens: `()`.
        let mut alt = on2(&grammar.tin_open, &grammar.tin_close);
        alt.b = 1;
        alt.g = "expr,expr-paren,empty".into();
        let condition = grammar.clone();
        alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
            let close = rule.o1().map(|token| token.tin);
            paren_op_for(&condition, rule).is_some_and(|op| Some(op.ctin) == close)
        }));
        let ops = grammar.clone();
        alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
            open_paren(&ops, rule);
        });
        open.push(alt);

        // A normal paren open: consume the opener and push to val.
        let mut alt = on(&grammar.tin_open);
        alt.p = Some("val".into());
        alt.n = counters(&[
            ("expr_paren", 1),
            ("expr", 0),
            ("expr_prefix", 0),
            ("expr_suffix", 0),
        ]);
        alt.g = "expr,expr-paren,open".into();
        let ops = grammar.clone();
        alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
            open_paren(&ops, rule);
        });
        open.push(alt);

        prepend_open_all(spec, open);

        let mut close: Vec<AltSpec> = Vec::new();

        // A separator in a separated content: the term before it is done,
        // and the next one follows. The loop is this rule's own close, so a
        // long argument list adds no rule depth. A term that is empty
        // (`f(,a)`, `f(a,,b)`) is refused at the separator after it.
        if grammar.separating {
            let mut alt = on(&grammar.tin_sep);
            let condition = grammar.clone();
            alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
                separated_paren(&condition, rule) && paren_term(rule).is_undefined()
            }));
            alt.e = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
                rule.c0().cloned()
            }));
            alt.g = "expr,expr-paren,expr-sep,empty".into();
            close.push(alt);

            let mut alt = on(&grammar.tin_sep);
            let condition = grammar.clone();
            alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
                separated_paren(&condition, rule)
            }));
            alt.p = Some("val".into());
            alt.n = counters(&[("expr", 0), ("expr_prefix", 0), ("expr_suffix", 0)]);
            alt.add_action(|rule: &mut Rule, _context: &mut Context| {
                let term = paren_term(rule);
                collect_paren_item(rule, term);
                rule.u_mut()
                    .insert(PAREN_MORE.to_string(), Value::Bool(true));
                // The next term starts empty, as the first did.
                set_node(rule, Value::Undefined);
            });
            alt.g = "expr,expr-paren,expr-sep".into();
            close.push(alt);
        }

        let mut alt = on(&grammar.tin_close);
        let condition = grammar.clone();
        // The closer of the operator this paren opened.
        alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
            let close = rule.c0().map(|token| token.tin);
            opened_paren(&condition, rule).is_some_and(|op| Some(op.ctin) == close)
        }));
        let ops = grammar.clone();
        alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
            close_paren(&ops, rule);
        });
        alt.g = "expr,expr-paren,close".into();
        close.push(alt);

        prepend_close_all(spec, close);

        spec.add_ac(|rule: &mut Rule, _context: &mut Context| {
            // A separator's pass goes on to the next term: the paren is
            // not done.
            if flag(&rule.u, PAREN_MORE) {
                rule.u_mut()
                    .insert(PAREN_MORE.to_string(), Value::Bool(false));
                return;
            }
            // A postfix paren extended the node of the expression it
            // applies to, in place, and its expr rule holds that node
            // already: the rules above hold the expression's root, which
            // stays.
            if rule
                .parent_rule
                .as_ref()
                .is_some_and(|parent| parent.u.contains_key(POSTFIX))
            {
                return;
            }
            let node = node_of(rule);
            let parent = rule.parent_rule.clone();
            write_linked_node(parent.as_ref(), node.clone());
            let grandparent = parent.and_then(|parent| parent.parent_rule.clone());
            write_linked_node(grandparent.as_ref(), node);
        });
    });
}

/// The paren operator a paren rule opens: the preval one when a value
/// precedes the opener, which the val that pushed this rule's expr records
/// as `u.paren_preval`, and the group otherwise.
fn paren_op_for(grammar: &Grammar, rule: &Rule) -> Option<Arc<Op>> {
    let tin = rule.o0()?.tin;
    if paren_has_preval(rule) {
        grammar.paren_preval.get(&tin).cloned()
    } else {
        grammar.paren_plain.get(&tin).cloned()
    }
}

/// Whether a value precedes this paren's opener: the val that pushed its
/// expr recorded `paren_preval`, or the paren is a postfix of the
/// expression its expr extends.
fn paren_has_preval(rule: &Rule) -> bool {
    let Some(parent) = rule.parent_rule.as_ref() else {
        return false;
    };
    parent.u.contains_key(POSTFIX)
        || parent
            .parent_rule
            .as_ref()
            .is_some_and(|grandparent| flag(&grandparent.u, "paren_preval"))
}

/// The `u` key a paren rule records the operator it opened under, by name:
/// its close builds the node with it, since two operators may share a
/// closer.
const PAREN_OP: &str = "expr_paren_op";

/// The operator this paren rule opened.
fn opened_paren(grammar: &Grammar, rule: &Rule) -> Option<Arc<Op>> {
    let Some(Value::String(name)) = rule.u.get(PAREN_OP) else {
        return None;
    };
    grammar.parens.iter().find(|op| &op.name == name).cloned()
}

fn open_paren(grammar: &Grammar, rule: &mut Rule) {
    let Some(op) = paren_op_for(grammar, rule) else {
        return;
    };
    rule.u_mut()
        .insert(PAREN_OP.to_string(), Value::String(op.name.clone()));
    // A group, opened with no value before it, which a cast may take as
    // its token.
    let group = !paren_has_preval(rule);
    rule.u_mut()
        .insert(PAREN_GROUP.to_string(), Value::Bool(group));
    // The content separates on commas only in a paren whose content is
    // separated: a group inside a call takes the comma operator again.
    if grammar.separating {
        rule.n_mut()
            .insert("expr_sep".into(), i32::from(op.content.separated));
    }
    let depth = paren_depth(&op.name);
    rule.u_mut().insert(depth.clone(), Value::Number(1.0));
    rule.n_mut().insert(depth, 1);
    set_node(rule, Value::Undefined);
}

fn close_paren(grammar: &Grammar, rule: &mut Rule) {
    let child = rule.child_node.clone();
    let mut node = node_of(rule);
    // The child's value, when this paren holds nothing of its own yet.
    //
    // The canonical port also takes the child whenever it is an operator,
    // and can, because it collects an implicit list IN the child's node
    // (`paren.child.node = [...]`): there the child IS the list. This
    // engine copies a container on write, so the list is collected on the
    // paren itself instead, while the child link stays on the rule the
    // paren PUSHED rather than on whichever rule of a replacement chain
    // popped last (tabnas/parser a801621, matching TS and Go). That rule
    // can still hold the list's first member, an operator. A node already
    // on the paren is the collected list, and the child must not overwrite
    // it: `(1?2:3 b)` would come back as `(1?2:3)`.
    if node.is_undefined() {
        node = child;
    }

    let Some(op) = opened_paren(grammar, rule) else {
        set_node(rule, node);
        return;
    };
    let op = OpRef::at(&op, rule.c0().cloned());
    let depth = paren_depth(&op.op.name);

    // Construct the completed paren expression.
    if local_number(rule, &depth) == i64::from(counter(rule, &depth)) {
        let mut terms: Vec<Value> = Vec::new();

        let grandparent = rule
            .parent_rule
            .as_ref()
            .filter(|parent| !parent.u.contains_key(POSTFIX))
            .and_then(|parent| parent.parent_rule.clone());
        if let Some(grandparent) = &grandparent {
            let preval = grandparent.node.borrow().clone();
            if matches!(grandparent.u.get("paren_preval"), Some(Value::Bool(true)))
                && !preval.is_undefined()
            {
                terms.push(preval);
            }
        }

        // The content's terms: the one term, or each term of a separated
        // content, the earlier ones collected at their separators.
        let mut content: Vec<Value> = paren_items(rule);
        if !node.is_undefined() {
            content.push(node);
        }

        // A postfix paren extends the node its expr rule placed in the
        // tree, `[op, target]`, in place.
        let postfix = rule
            .parent_rule
            .as_ref()
            .and_then(|parent| parent.u.get(POSTFIX).cloned());
        if let Some(postfix) = postfix {
            with_node_mut(&postfix, |entry| {
                entry.op = Some(op.op.clone());
                entry.token = op.token.clone();
            });
            for term in content {
                push_term(&postfix, term);
            }
            set_node(rule, postfix);
            return;
        }

        terms.extend(content);
        set_node(rule, op.node(terms));
    } else {
        set_node(rule, node);
    }
}

// ---------------------------------------------------------------------------
// ternary
// ---------------------------------------------------------------------------

fn install_ternary(parser: &mut Tabnas, grammar: &Arc<Grammar>) {
    let grammar = grammar.clone();
    parser.define_rule("ternary", move |spec| {
        let mut open: Vec<AltSpec> = Vec::new();

        let mut alt = on(&grammar.tin_tern0);
        alt.p = Some("val".into());
        alt.n = counters(&[
            ("expr_ternary", 1),
            ("expr", 0),
            ("expr_prefix", 0),
            ("expr_suffix", 0),
        ]);
        alt.u = locals(&[("expr_ternary_step", Value::Number(1.0))]);
        alt.g = "expr,expr-ternary,open".into();
        let ops = grammar.clone();
        alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
            let Some(op) = Grammar::op_use(&ops.ternary, rule.o0()) else {
                return;
            };
            rule.u_mut().insert(
                "expr_ternary_name".into(),
                Value::String(op.op.name.clone()),
            );

            // The first term is the whole expression before the ternary.
            let previous = ternary_first(rule);
            let node = if is_op(&previous) {
                let duplicate = dup_node(&previous);
                update_expr_node(
                    &previous,
                    Some(op.op.clone()),
                    op.token.clone(),
                    vec![duplicate],
                );
                previous
            } else {
                let node = op.node(vec![previous]);
                write_linked_node(rule.prev_rule.as_ref(), node.clone());
                node
            };
            set_node(rule, node);

            let paren = if 0 != counter(rule, "expr_paren") {
                i64::from(counter(rule, "expr_paren"))
            } else {
                rule.prev_rule
                    .as_ref()
                    .map_or(0, |prev| snapshot_number(prev, "expr_ternary_paren"))
            };
            rule.u_mut()
                .insert("expr_ternary_paren".into(), Value::Number(paren as f64));
            rule.n_mut().insert("expr_paren".into(), 0);
        });
        open.push(alt);

        let mut alt = always();
        alt.p = Some("val".into());
        alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
            rule.prev_rule
                .as_ref()
                .is_some_and(|prev| 2 == snapshot_number(prev, "expr_ternary_step"))
        }));
        alt.add_action(|rule: &mut Rule, _context: &mut Context| {
            let (step, paren) = rule.prev_rule.as_ref().map_or((0, 0), |prev| {
                (
                    snapshot_number(prev, "expr_ternary_step"),
                    snapshot_number(prev, "expr_ternary_paren"),
                )
            });
            set_local_number(rule, "expr_ternary_step", step);
            set_local_number(rule, "expr_ternary_paren", paren);
            rule.n_mut().insert("expr_paren".into(), paren as i32);
        });
        alt.g = "expr,expr-ternary,step".into();
        open.push(alt);

        prepend_open_all(spec, open);

        let mut close: Vec<AltSpec> = Vec::new();

        let mut alt = on(&grammar.tin_tern1);
        let condition = grammar.clone();
        alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
            if 1 != local_number(rule, "expr_ternary_step") {
                return false;
            }
            let Some(op) = rule
                .c0()
                .and_then(|token| condition.ternary.get(&token.tin))
                .cloned()
            else {
                return false;
            };
            matches!(rule.u.get("expr_ternary_name"), Some(Value::String(name)) if name == &op.name)
        }));
        alt.r = Some("ternary".into());
        alt.add_action(|rule: &mut Rule, _context: &mut Context| {
            let step = local_number(rule, "expr_ternary_step");
            set_local_number(rule, "expr_ternary_step", step + 1);
            let node = node_of(rule);
            push_term(&node, rule.child_node.clone());
        });
        alt.g = "expr,expr-ternary,step".into();
        close.push(alt);

        // End of ternary at the top level, implicit list indicated by a
        // comma. Handle a ternary as the first item of an implicit list
        // inside parens.
        let mut tins = vec![TIN_CA];
        tins.extend(grammar.tin_close.iter().copied());
        let mut alt = on(&tins);
        // Not at a separator of a separated content, which ends the
        // ternary as one of that content's terms.
        let condition = grammar.clone();
        alt.c_fn = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
            let at_sep = rule
                .c0()
                .is_some_and(|token| condition.tin_sep.contains(&token.tin));
            implicit_ternary_cond(rule, context) && !(separated_here(rule) && at_sep)
        }));
        let closers = grammar.tin_close.clone();
        alt.b_fn = Some(Arc::new(move |_rule: &mut Rule, context: &mut Context| {
            usize::from(next_is_close(context, &closers))
        }));
        let closers = grammar.tin_close.clone();
        alt.r_fn = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
            let to_elem = !next_is_close(context, &closers)
                && (0 == rule.d
                    || (rule
                        .prev_rule
                        .as_ref()
                        .is_some_and(|prev| 0 != snapshot_number(prev, "expr_ternary_paren"))
                        && 0 == node_length(&linked_node(rule.parent_rule.as_ref()))));
            to_elem.then(|| "elem".to_string())
        }));
        alt.add_action_with_match(|rule: &mut Rule, _context: &mut Context, matched| {
            implicit_ternary_action(rule, matched);
            None
        });
        alt.g = "expr,expr-ternary,list,val,imp,comma".into();
        close.push(alt);

        // End of ternary at the top level, implicit list indicated by a
        // space separated value.
        let mut alt = always();
        // Neither at a separator of a separated content, nor, with
        // `juxtapose: false`, at a value beside the ternary.
        let condition = grammar.clone();
        alt.c_fn = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
            let next = context.t0().map(|token| token.tin);
            implicit_ternary_cond(rule, context)
                && !(separated_here(rule)
                    && next.is_some_and(|tin| condition.tin_sep.contains(&tin)))
                && !(condition.no_juxtapose && next.is_some_and(|tin| condition.starts_value(tin)))
        }));
        let closers = grammar.tin_close.clone();
        alt.r_fn = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
            let ended = context.t0().is_some_and(|token| TIN_ZZ == token.tin);
            let to_elem = (0 == rule.d
                || !next_is_close(context, &closers)
                || rule
                    .prev_rule
                    .as_ref()
                    .is_some_and(|prev| 0 != snapshot_number(prev, "expr_ternary_paren")))
                && 0 == node_length(&linked_node(rule.parent_rule.as_ref()))
                && !ended;
            to_elem.then(|| "elem".to_string())
        }));
        alt.add_action_with_match(|rule: &mut Rule, _context: &mut Context, matched| {
            implicit_ternary_action(rule, matched);
            None
        });
        alt.g = "expr,expr-ternary,list,val,imp,space".into();
        close.push(alt);

        // End of ternary, but never at a host grammar's value with
        // `juxtapose: false`, which is refused here.
        let mut alt = always();
        let condition = grammar.clone();
        alt.c_fn = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
            0 < rule.d
                && 2 == local_number(rule, "expr_ternary_step")
                && !condition.host_value(context.t0().map(|token| token.tin))
        }));
        alt.add_action(|rule: &mut Rule, _context: &mut Context| {
            let node = node_of(rule);
            push_term(&node, rule.child_node.clone());
        });
        alt.g = "expr,expr-ternary,close".into();
        close.push(alt);

        prepend_close_all(spec, close);

        // Ensure ternary results get evaluated. Without this, a ternary
        // that is not wrapped in an expr leaves its result as a raw
        // S-expression. Fire on every ternary instance's after-close, but
        // act only when the chain has reached its final step: the node
        // has accumulated all three operands and the next rule is not
        // another ternary. Write the evaluated value back along the
        // replacement chain so whichever node the parse returns reflects
        // the evaluated form.
        if let Some(evaluate) = grammar.evaluate.clone() {
            spec.add_ac(move |rule: &mut Rule, context: &mut Context| {
                if rule
                    .next_rule_name
                    .as_ref()
                    .is_some_and(|name| "ternary" == name.as_ref())
                {
                    return;
                }
                let node = node_of(rule);
                if !is_op(&node) {
                    return;
                }
                // The node is not fully populated until all three
                // operands sit under it; earlier steps carry fewer.
                if node_length(&node) < 4 {
                    return;
                }
                let out = {
                    // The canonical port hands the ternary rule itself to
                    // the evaluator here, where the expr rule hands its
                    // parent.
                    let site_rule = rule.snapshot();
                    let mut site = EvalSite::new(Some(site_rule), context);
                    evaluation(&mut site, &node, &evaluate)
                };
                // The rules of the ternary's own replacement chain hold its
                // node, the val that started it among them, which the rule
                // above reads its value from. That rule's own node (a
                // list's elements, a map's members, a paren's terms) is its
                // own, and is never written here.
                publish(rule, out.clone());
                let mut cursor = rule.prev_rule.clone();
                while let Some(current) = cursor {
                    *current.node.borrow_mut() = out.clone();
                    cursor = current.prev_rule.clone();
                }
                // The rule the expression's first term belongs to holds the
                // ternary's node, its root, when the ternary followed an
                // expression: the canonical port reaches it along the
                // chain, which this engine keeps only three rules of.
                if let Some(parent) = rule.parent_rule.as_ref() {
                    let held = parent.node.borrow().clone();
                    if node_id(&held).is_some() && node_id(&held) == node_id(&node) {
                        *parent.node.borrow_mut() = out;
                    }
                }
            });
        }
    });
}

/// The first term of a ternary with no binding power: the whole expression
/// before it. An expr rule holds the node its last operator heads, which is
/// the expression's root only when that operator was looser than the ones
/// before it: in `a + b * c ? d : e` the rule before the ternary holds
/// `b * c`. The root is held by the rule the expression's first term
/// belongs to, the expr rule's parent, and the node the expr rule holds is
/// on the root's last terms.
fn ternary_first(rule: &Rule) -> Value {
    let previous = linked_node(rule.prev_rule.as_ref());
    let Some(prev) = rule.prev_rule.as_ref() else {
        return previous;
    };
    if "expr" != prev.name.as_ref() || !is_op(&previous) {
        return previous;
    }
    let Some(holder) = prev.parent_rule.as_ref() else {
        return previous;
    };
    let root = holder.node.borrow().clone();
    if !is_op(&root) || same_node(&root, &previous) {
        return previous;
    }
    let mut at = root.clone();
    while let Some(op) = op_of(&at) {
        if same_node(&at, &previous) {
            return root;
        }
        at = term_at(&at, op.terms);
    }
    previous
}

fn snapshot_number(snapshot: &RuleSnapshot, name: &str) -> i64 {
    match snapshot.u.get(name) {
        Some(Value::Number(number)) => *number as i64,
        _ => 0,
    }
}

fn next_is_close(context: &mut Context, closers: &[Tin]) -> bool {
    context
        .t0()
        .is_some_and(|token| closers.contains(&token.tin))
}

fn implicit_ternary_cond(rule: &mut Rule, _context: &mut Context) -> bool {
    (0 == rule.d || 1 <= counter(rule, "expr_paren"))
        && 0 == counter(rule, "pk")
        && 2 == local_number(rule, "expr_ternary_step")
}

fn implicit_ternary_action(rule: &mut Rule, matched: &AltMatch) {
    let paren = rule
        .prev_rule
        .as_ref()
        .map_or(0, |prev| snapshot_number(prev, "expr_ternary_paren"));
    rule.n_mut().insert("expr_paren".into(), paren as i32);

    let node = node_of(rule);
    push_term(&node, rule.child_node.clone());

    if matched.r.as_deref() != Some("elem") {
        return;
    }

    // The completed ternary becomes the first element of an implicit
    // list. The canonical port rewrites the node into that list in place,
    // so that every holder sees it; here the list is written through the
    // shared node cell instead, which is what the replacing `elem` rule
    // is seeded from, and onto the enclosing paren, because a container
    // is copied on write and the two cannot share one array.
    let list = Value::array(vec![node]);
    publish(rule, list.clone());
    if 1 <= counter(rule, "expr_paren") {
        let mut cursor = rule.parent_rule.clone();
        while let Some(current) = cursor {
            if "paren" == current.name.as_ref() {
                *current.node.borrow_mut() = list;
                break;
            }
            cursor = current.parent_rule.clone();
        }
    }
}

// ---------------------------------------------------------------------------
// Public entry points
// ---------------------------------------------------------------------------

/// The plugin, for [`Tabnas::use_plugin`], carrying the default operator
/// table as its declared defaults.
///
/// Call-site options are deep-merged over those defaults by the engine, so
/// an entry naming a default operator extends it and a `null` entry
/// deletes it, exactly as in the canonical TypeScript. An evaluator cannot
/// travel in a serialized option bag: pass one with [`plugin_with`].
///
/// ```
/// use tabnas::Value;
///
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let mut parser = tabnas_jsonic::make();
///     parser.use_plugin(tabnas_expr::plugin(), None)?;
///     let value = tabnas_expr::realize(&parser.parse("1+2")?);
///     assert_eq!(tabnas_expr::simplify(&value).to_string(), "[\"+\",1,2]");
///     Ok::<(), Box<dyn std::error::Error>>(())
/// }
/// ```
pub fn plugin() -> Plugin {
    Plugin::new(PLUGIN_NAME, |parser: &mut Tabnas, options: &Value| {
        expr(parser, &ExprOptions::from_value(options))
    })
    .with_defaults(defaults())
}

/// The plugin with typed options, which is how an evaluator and any
/// operator data that no `Value` can carry reach the grammar.
///
/// The typed options resolve the defaults themselves, so the serialized
/// option bag is not consulted: an operator given here replaces the
/// default of the same name outright rather than extending it.
pub fn plugin_with(options: ExprOptions) -> Plugin {
    Plugin::new(PLUGIN_NAME, move |parser: &mut Tabnas, _options: &Value| {
        expr(parser, &options)
    })
}

/// Install the expression grammar on a parser through
/// [`Tabnas::use_plugin`], so that a derived instance rebuilds it.
pub fn apply(parser: &mut Tabnas, options: ExprOptions) -> Result<(), PluginError> {
    parser.use_plugin(plugin_with(options), None).map(|_| ())
}

/// Build a parser with the jsonic base grammar and the default operator
/// table.
///
/// ```
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let parser = tabnas_expr::make();
///     let value = tabnas_expr::parse_with(&parser, "(1+2)*3")?;
///     assert_eq!(tabnas_expr::simplify(&value).to_string(),
///                r#"["*",["(",["+",1,2]],3]"#);
///     Ok(())
/// }
/// ```
pub fn make() -> Tabnas {
    make_with(ExprOptions::new())
}

/// Build a parser with the jsonic base grammar and the given options.
pub fn make_with(options: ExprOptions) -> Tabnas {
    make_on(tabnas_jsonic::make(), options)
}

/// Install the expression grammar on `parser`, jsonic's base, and declare
/// this parser's own window setting: `lex.window` false, so that
/// [`Tabnas::parse_reader`] reads a reader whole (admin ADR-30). The
/// grammar's matchers are not yet verified at the window's edge, and a base
/// that declares the window must not carry it to them; the setting comes
/// last, after everything the base and the grammar set.
fn make_on(mut parser: Tabnas, options: ExprOptions) -> Tabnas {
    parser
        .use_plugin(plugin_with(options), None)
        .expect("the expression grammar installs on the jsonic base");
    parser
        .set_options(|options| options.lex.window = false)
        .expect("lex.window sets");
    parser
}

#[cfg(test)]
mod window_tests {
    /// The parser's own setting wins over its base's: a base that declares
    /// `lex.window`, as jsonic's own constructor may, given the
    /// constructor's steps, comes out with the window off.
    #[test]
    fn a_windowed_base_comes_out_without_the_window() {
        let mut base = tabnas_jsonic::make();
        base.set_options(|options| options.lex.window = true)
            .expect("lex.window sets");
        assert!(base.options.lex.window);
        let parser = super::make_on(base, super::ExprOptions::new());
        assert!(!parser.options.lex.window);
        assert!(super::parse_with(&parser, "1+2*3").is_ok());
    }
}

/// The lazily built instance the no-options [`parse`] reuses.
///
/// Building the grammar dominates a parse, so a fresh instance per call is
/// many times slower (see `tests/perf_test.rs`). Parsing builds a fresh
/// context per call and only reads instance state, so one shared instance
/// is safe to use from several threads.
static DEFAULT_PARSER: OnceLock<Tabnas> = OnceLock::new();

/// Parse one document with the default operator table.
///
/// ```
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let value = tabnas_expr::parse("a:1+2")?;
///     assert_eq!(tabnas_expr::simplify(&value).to_string(),
///                r#"{"a":["+",1,2]}"#);
///     Ok(())
/// }
/// ```
pub fn parse(src: &str) -> Result<Value, TabnasError> {
    parse_with(DEFAULT_PARSER.get_or_init(make), src)
}

/// Parse one document with a parser this crate configured, and realize the
/// expression nodes in the result.
///
/// A parser driven directly through [`Tabnas::parse`] returns a value whose
/// expression nodes are still handles into the per-parse arena; pass that
/// value to [`realize`] before the next parse on the same thread.
pub fn parse_with(parser: &Tabnas, src: &str) -> Result<Value, TabnasError> {
    let _guard = ArenaGuard::enter();
    let value = parser.parse(src)?;
    Ok(realize(&value))
}

/// Parse one document and hand the unrealized value to a closure, with
/// the expression arena held open for as long as it runs.
///
/// This is the parse-once, evaluate-many workflow: inside the closure the
/// expression nodes are live, so [`evaluation`] can reduce them, and
/// whatever the closure returns outlives them.
///
/// The arena is released when this returns, so the closure must not let an
/// expression HANDLE escape in what it returns. Return a reduced value, as
/// the example below does, or call [`realize`] on the tree and return
/// that; [`parse_with`] is the same parse with the realizing already done.
/// A handle that escapes names a node that no longer exists, and
/// [`realize`] and [`simplify`] then PANIC rather than report the lost
/// expression as an empty array. The closure return type is a type
/// parameter, so nothing in the signature can realize it for a caller, and
/// nothing in it can stop a handle from being returned.
///
/// ```
/// use tabnas::Value;
/// use tabnas_expr::{evaluation, EvalSite, Evaluate, Op};
///
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let parser = tabnas_expr::make();
///     let add: Evaluate = std::sync::Arc::new(
///         |_site: &mut EvalSite<'_>, _op: &Op, terms: &[Value]| match terms {
///             [Value::Number(left), Value::Number(right)] => Value::Number(left + right),
///             _ => Value::Null,
///         },
///     );
///     let total = tabnas_expr::parse_scope(&parser, "1+2", |value| {
///         evaluation(&mut EvalSite::detached(), &value, &add)
///     })?;
///     assert_eq!(total, Value::Number(3.0));
///     Ok(())
/// }
/// ```
pub fn parse_scope<R>(
    parser: &Tabnas,
    src: &str,
    use_value: impl FnOnce(Value) -> R,
) -> Result<R, TabnasError> {
    let _guard = ArenaGuard::enter();
    let value = parser.parse(src)?;
    Ok(use_value(value))
}

/// Parse one document and reduce it to the S-expression form the shared
/// fixtures compare.
pub fn parse_simplified(parser: &Tabnas, src: &str) -> Result<Value, TabnasError> {
    let _guard = ArenaGuard::enter();
    let value = parser.parse(src)?;
    Ok(simplify(&value))
}

// --- Translation parts (admin ADR-27) ---------------------------------

/// One optional alchemy translation source and its explicit entry point.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TranslationPart {
    /// The definition a host calls after linking the source.
    pub entry: &'static str,
    /// The source text, or `None` for an entry supplied by alchemy.
    pub source: Option<&'static str>,
}

/// The package-local structural translation interface.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TranslationParts {
    /// The complete `tabnas.plugin.json` text.
    pub manifest: &'static str,
    /// An optional lift from the grammar's events to its first read shape.
    pub lift: Option<TranslationPart>,
    /// An optional embedding of a plain tree in the format's schema, with its reverse.
    pub embed: Option<TranslationPart>,
    /// An optional render from the write shape to text.
    pub render: Option<TranslationPart>,
}

const TRANSLATION: TranslationParts = TranslationParts {
    manifest: include_str!("../translate/manifest.json"),
    lift: None,
    embed: Some(TranslationPart {
        entry: "expr-embed",
        source: Some(include_str!("../translate/embed.alc")),
    }),
    render: Some(TranslationPart {
        entry: "expr-render",
        source: Some(include_str!("../translate/render.alc")),
    }),
};

/// Return the expression format's immutable translation parts.
#[must_use]
pub const fn translate() -> Option<TranslationParts> {
    Some(TRANSLATION)
}

/// The plugin's manifest, `tabnas.plugin.json`, as the repository carries
/// it. Its `translate` object is what a host that translates reads: the
/// shape an expression document is read as and written from (`tree`), the root the render
/// takes, the schema of the tree its events carry (`expr`), the files
/// that hold the embedding of a plain tree in that schema and the render,
/// and the sentences that say what a written document does not keep. The
/// crate embeds its own copy, `translate/manifest.json`, since a packaged
/// crate holds nothing outside `rs/`; `tests/translate_test.rs` holds the
/// copy to the file.
///
/// ```
/// assert!(tabnas_expr::manifest_text().contains("\"translate\""));
/// ```
pub fn manifest_text() -> &'static str {
    TRANSLATION.manifest
}

/// The expression format's render, `alchemy/render.alc`, the file the manifest's
/// `translate.render` names: a library of alchemy definitions, with no
/// `export`, whose entry point `expr-render` writes a tree's events as one
/// document. A host links it with its own program. The crate embeds its
/// own copy, `translate/render.alc`, held to the file as the manifest's
/// is; the embedding, `translate/embed.alc`, is `translate().embed`.
///
/// ```
/// assert!(tabnas_expr::render_text().contains("def expr-render [input]"));
/// ```
pub fn render_text() -> &'static str {
    match TRANSLATION.render {
        Some(part) => part.source.unwrap_or_default(),
        None => "",
    }
}