texrs 0.6.0

A TeX engine: Knuth's mouth and expander, lowered for a bytecode VM
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
//! TeX's expander: the half of the engine that turns tokens into other tokens.
//!
//! Everything here is "mouth" work in Knuth's sense — `\def`, `\csname`, the
//! conditionals and `\the` all produce token lists and never build a box.
//!
//! Two reading contexts exist and the difference is load-bearing. Executing a
//! file reads from the mouth, which falls through to the source when the
//! pushed-back list runs dry. Expanding a token list — a `\message` body, an
//! `\edef` body — must NOT: the list is the whole world, and a scanner that
//! reaches past it pulls the next line of the FILE into the result. Every
//! scanner below therefore takes `pending_only` rather than guessing.

use crate::catcode::{cat_from_i64, Cat, CatTable};
use crate::lexer::Lexer;
use crate::token::{CsId, Token};
use std::collections::HashMap;

/// A `\def`'d macro: the parameter text as written, and the body.
#[derive(Clone, PartialEq)]
pub struct Macro {
    pub params: Vec<Token>,
    pub body: Vec<Token>,
    /// `\long\def` — the argument may contain `\par`.
    pub long: bool,
    /// `\protected\def` — the macro does not expand inside an `\edef` or a
    /// `\write`; it survives as itself and runs when the result does.
    pub protected: bool,
    /// `\outer\def` — the macro may not appear in an argument, in a group
    /// being scanned as text, or in skipped conditional text.
    ///
    /// Both flags are part of the MEANING, not decoration: tex's `\ifx` says
    /// `\long\def\a{}` and `\def\a{}` differ, which falls out of deriving
    /// `PartialEq` here.
    pub outer: bool,
}

/// What a control sequence means. `\let` is why this is a value and not just a
/// macro table: `\let\a=\relax` makes `\a` a primitive, not a macro.
#[derive(Clone, PartialEq)]
pub enum Meaning {
    Macro(Macro),
    /// A primitive, by its canonical name (`relax`, `par`, …).
    Primitive(CsId),
    /// `\let\a=b` — a character token.
    Char(char, Cat),
    /// `\chardef\a=65` — a character code, standing for a number wherever one
    /// is scanned. plain.tex builds its constants this way: `\chardef\active=13`
    /// is what makes `\catcode`\~=\active` readable.
    CharDef(i64),
    /// `\toksdef\toks@=0` — another name for a token register.
    ToksDef(i64),
    /// `\countdef\pageno=0` — another name for a count register, in every
    /// position `\count0` itself works: assignment, arithmetic and `\the`.
    CountDef(i64),
}

/// eTeX's division: round half AWAY from zero, which is not what `\divide`
/// does (`tex.web` §1236 truncates). Measured -- 7/2 is 4, 5/2 is 3, -7/2 is
/// -4, and 6/4 is 2.
fn round_div(a: i64, b: i64) -> i64 {
    let sign = match (a < 0) == (b < 0) {
        true => 1,
        false => -1,
    };
    let (a, b) = (a.abs(), b.abs());
    sign * ((a + b / 2) / b)
}

/// What a control sequence contributes when a number is being scanned.
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum NumericCs {
    /// A constant, already known while lowering.
    Value(i64),
    /// A count register, whose value is only known at run time.
    Register(i64),
}

/// One undo record. TeX's save stack restores individual changes at group end
/// rather than snapshotting the whole state, which is what makes deep grouping
/// affordable; the same choice is made here.
enum Save {
    Cat(char, Cat),
    /// One token register as it stood before a group assigned to it.
    Toks(i64, Option<Vec<Token>>),
    /// One entry of one character-code table, as it stood before a group
    /// changed it. The tables are scoped exactly as the category codes are --
    /// measured: 777 inside the group, 555 outside.
    CharCode(crate::charcodes::Table, char, i64),
    Count(i64, Option<i64>),
    Meaning(CsId, Option<Meaning>),
    /// The whole intercept registry as it stood before a registration inside
    /// this group. Advice is a document-wide effect, and TeX's rule is that a
    /// non-global assignment does not escape its group; the registry is small
    /// and registrations are rare, so the undo record is the whole list rather
    /// than a per-entry diff.
    Intercepts(crate::intercepts::Registry),
    /// A token `\aftergroup` is holding for this group's `}`.
    ///
    /// `tex.web` §326 puts it on the SAVE STACK rather than in a list of its
    /// own, which is what makes a nested group's tokens come out at its own
    /// closing brace and several in one group come out in order.
    AfterGroup(Token),
}

pub struct Engine {
    pub cats: CatTable,
    /// What each control sequence means, keyed by interned id.
    ///
    /// Keyed on `CsId` rather than the name: a lookup here happens on every
    /// control sequence the expander touches, and hashing a `u32` is what makes
    /// that cheap. `tex.web` reaches `eqtb` the same way, by the pointer the
    /// hash table already produced.
    pub meanings: HashMap<CsId, Meaning>,
    /// Default values recorded by `\newcommand{\x}[n][default]`.
    optional_defaults: HashMap<CsId, Vec<Token>>,
    pub count: HashMap<i64, i64>,
    pub messages: Vec<String>,
    pub escape: char,
    /// One frame per open group; each holds the undo records for that group.
    groups: Vec<Vec<Save>>,
    /// Open conditionals, so `\else`/`\fi` know what they close.
    conds: Vec<CondState>,
    /// Set by `\global`, cleared by the assignment it prefixes.
    /// `\mathcode`, `\lccode`, `\uccode`, `\sfcode`, `\delcode`.
    pub charcodes: crate::charcodes::CharCodes,
    /// `\toks` registers. A token list is frontend state like a macro body, not
    /// a number in a slot, so it lives here and is scoped by the same save
    /// stack -- measured: `{\toks0={b}}` leaves the outer value behind.
    pub toks: std::collections::HashMap<i64, Vec<Token>>,
    global: bool,
    /// Whether a `\long` prefix is in force for the definition being read.
    long: bool,
    /// Whether an `\outer` prefix is.
    outer: bool,
    /// Whether a `\protected` prefix is.
    protected: bool,
    /// Advice registered with `\intercept`, woven into matching expansions.
    pub intercepts: crate::intercepts::Registry,
    /// How deep inside an advice body expansion currently is.
    ///
    /// Advice is NOT woven into a call that occurs inside advice: a handler
    /// that calls the macro it advises would otherwise weave itself forever.
    /// The depth is carried in the token stream by the two markers below rather
    /// than by a counter around the weave, because the handler's tokens are
    /// pushed back and expanded later, long after the weave returned.
    /// Tokens the group that just closed held for `\aftergroup`, waiting for
    /// a caller with a mouth to put them back.
    after_group_tokens: Vec<Token>,
    /// The token `\afterassignment` is holding for the next assignment
    /// (`tex.web` §1269's `after_token`). One only: a second `\afterassignment`
    /// before the assignment replaces the first, as it does there.
    after_assignment: Option<Token>,
    advice_depth: u32,
    /// Whether an `\unless` is waiting for the conditional it negates.
    ///
    /// eTeX's `\unless` is not a conditional of its own: it flips the sense of
    /// the NEXT one, which is why this is a flag the conditional spends rather
    /// than a second set of primitives. It lives on the engine rather than on
    /// the lowerer because both decide conditionals -- `\ifnum` becomes a
    /// run-time branch the lowerer builds and `\ifx` is settled here -- and two
    /// flags would leave whichever one did not run the conditional still set,
    /// so the NEXT conditional would be negated instead.
    unless: bool,
    /// Whether the scanner is reading MATH units.
    ///
    /// `tex.web` §448 passes this as `scan_dimen`'s `mu` argument, and §455 is
    /// what it decides: where a mu is wanted, `mu` is the only finite unit and
    /// every other one is illegal; where a mu is not wanted, `mu` is illegal
    /// and the rest are legal. The arithmetic is the same either way -- a mu
    /// is 65536ths exactly as a point is -- so this is the whole difference.
    /// A field rather than an argument because the mode has to survive down
    /// through `scan_glue` into `scan_dimen_or_fil`, and threading it would
    /// change five signatures that are already public.
    mu_units: bool,
    /// Errors REPORTED rather than raised, in the order they happened.
    ///
    /// `tex.web` §82's `error` prints the message and carries on; only a few
    /// conditions (§93's `fatal_error`, running out of memory) stop the run.
    /// A `TexError` here is the stopping kind, so a condition tex recovers from
    /// cannot be one -- it goes here instead, and the lowerer writes it into the
    /// message stream in front of whatever is printed next, which is where tex
    /// prints it.
    errors: Vec<String>,
}

/// An advice body between the two depth markers, so a call inside it is not
/// itself advised.
fn wrapped(body: &[Token]) -> Vec<Token> {
    let mut v = Vec::with_capacity(body.len() + 2);
    v.push(Token::cs(ADVICE_IN));
    v.extend(body.iter().copied());
    v.push(Token::cs(ADVICE_OUT));
    v
}

/// Pushed in front of an advice body, and behind it. The NUL keeps both out of
/// reach of any document: a control sequence's name comes from the mouth, and
/// the mouth cannot produce one.
pub const ADVICE_IN: &str = "\u{0}advice-in";
pub const ADVICE_OUT: &str = "\u{0}advice-out";

/// Which of the three conditional boundaries a skip stopped at
/// (`tex.web` §489's `or_code`, `else_code`, `fi_code`).
#[derive(PartialEq, Clone, Copy, Debug)]
enum Stop {
    Or,
    Else,
    Fi,
}

#[derive(PartialEq, Clone, Copy)]
enum CondState {
    /// The true branch is running; an `\else` here starts skipping.
    Taken,
    /// A branch was skipped to get here; `\else` must not re-enter.
    Done,
}

#[derive(Debug)]
pub struct TexError(pub String);

type R<T> = Result<T, TexError>;

/// Every conditional primitive, so the skipper can count nesting correctly.
/// Missing one here would make a skipped `\ifnum` eat its own `\fi` and unbalance
/// everything after it.
/// Every command `tex.web` §1211 routes through `prefixed_command` — the
/// ASSIGNMENTS, which are exactly what `\afterassignment` waits for. A `\the`
/// or a `\message` is not one, and neither is a group.
const ASSIGNMENTS: &[&str] = &[
    "def",
    "gdef",
    "edef",
    "xdef",
    "let",
    "futurelet",
    "chardef",
    "mathchardef",
    "countdef",
    "dimendef",
    "skipdef",
    "muskipdef",
    "toksdef",
    "count",
    "dimen",
    "skip",
    "muskip",
    "toks",
    "advance",
    "multiply",
    "divide",
    "catcode",
    "mathcode",
    "lccode",
    "uccode",
    "sfcode",
    "delcode",
    "newcommand",
    "renewcommand",
    "providecommand",
    "DeclareRobustCommand",
];

const CONDITIONALS: &[&str] = &[
    "if",
    "ifcat",
    "ifnum",
    "ifdim",
    "ifodd",
    "ifvmode",
    "ifhmode",
    "ifmmode",
    "ifinner",
    "ifvoid",
    "ifhbox",
    "ifvbox",
    "ifx",
    "ifeof",
    "iftrue",
    "iffalse",
    "ifcase",
    "ifdefined",
    "ifcsname",
];

impl Engine {
    pub fn new() -> Self {
        Self {
            cats: CatTable::new(),
            meanings: HashMap::new(),
            optional_defaults: HashMap::new(),
            count: HashMap::new(),
            messages: Vec::new(),
            escape: '\\',
            groups: Vec::new(),
            conds: Vec::new(),
            charcodes: crate::charcodes::CharCodes::default(),
            toks: std::collections::HashMap::new(),
            global: false,
            long: false,
            outer: false,
            protected: false,
            intercepts: crate::intercepts::Registry::new(),
            advice_depth: 0,
            unless: false,
            mu_units: false,
            errors: Vec::new(),
            after_group_tokens: Vec::new(),
            after_assignment: None,
        }
    }

    pub fn run(&mut self, src: &str) -> R<()> {
        let mut lx = Lexer::new(src);
        while let Some(tok) = lx.next_token(&self.cats) {
            if self.step(&mut lx, tok)? {
                break;
            }
        }
        Ok(())
    }

    // ── grouping ─────────────────────────────────────────────────────────

    fn begin_group(&mut self) {
        self.groups.push(Vec::new());
    }

    /// `\aftergroup<token>` — hold the token and insert it after the `}`.
    ///
    /// `tex.web` §326 saves it on the save stack as an `insert_token`, so
    /// several `\aftergroup`s in one group come back in the order they were
    /// given and a nested group's tokens come out at ITS `}`. Keeping them in
    /// the group frame is the same arrangement.
    ///
    /// Outside every group there is nothing to wait for and tex inserts the
    /// token at once, which is what the empty-stack case does.
    pub fn after_group(&mut self, lx: &mut Lexer, tok: Token) {
        match self.groups.last_mut() {
            Some(frame) => frame.push(Save::AfterGroup(tok)),
            None => lx.push_back(&[tok]),
        }
    }

    /// Undo this group's assignments, newest first.
    fn end_group(&mut self) -> R<()> {
        let Some(frame) = self.groups.pop() else {
            return Err(TexError("Too many }'s".into()));
        };
        // §282: the tokens `\aftergroup` held come out in the order they were
        // given, AFTER the group's own restores. Collected before the undo pass
        // so the reverse walk below does not reverse them too, and buffered
        // rather than pushed because a group can close in a context that has no
        // mouth in hand -- `take_after_group` is where they reach one.
        self.after_group_tokens
            .extend(frame.iter().filter_map(|s| match s {
                Save::AfterGroup(t) => Some(*t),
                _ => None,
            }));
        for save in frame.into_iter().rev() {
            match save {
                Save::Cat(c, cat) => self.cats.set(c, cat),
                Save::Toks(reg, was) => {
                    match was {
                        Some(v) => self.toks.insert(reg, v),
                        None => self.toks.remove(&reg),
                    };
                }
                Save::CharCode(t, c, v) => {
                    let _ = self.charcodes.set(t, c, v);
                }
                Save::Count(reg, old) => match old {
                    Some(v) => {
                        self.count.insert(reg, v);
                    }
                    None => {
                        self.count.remove(&reg);
                    }
                },
                Save::Meaning(name, old) => match old {
                    Some(m) => {
                        self.meanings.insert(name, m);
                    }
                    None => {
                        self.meanings.remove(&name);
                    }
                },
                Save::Intercepts(old) => self.intercepts = old,
                // Already collected above; it is a token to insert, not a
                // value to put back.
                Save::AfterGroup(_) => {}
            }
        }
        Ok(())
    }

    /// Hold `tok` until the next assignment finishes (`\afterassignment`).
    pub fn set_after_assignment(&mut self, tok: Token) {
        self.after_assignment = Some(tok);
    }

    /// The token `\afterassignment` is holding, if the command just executed
    /// was an ASSIGNMENT (`tex.web` §1269 inserts it at the end of
    /// `prefixed_command` and nowhere else).
    pub fn take_after_assignment(&mut self, was_assignment: bool) -> Option<Token> {
        match was_assignment {
            true => self.after_assignment.take(),
            false => None,
        }
    }

    /// Whether `name` is one of the assignment commands `\afterassignment`
    /// waits for -- `tex.web` §1211's `prefixed_command` set.
    ///
    /// A register named through `\countdef` and friends is an assignment too,
    /// and is not spelt here because it is not spelt: the caller asks the
    /// meaning table for that one.
    pub fn is_assignment(name: &str) -> bool {
        ASSIGNMENTS.contains(&name)
    }

    /// The tokens the group that just closed held for `\aftergroup`, in the
    /// order they were given, clearing the buffer.
    ///
    /// Every caller of a group end has a mouth; `end_group` does not, so this
    /// is where the two meet. Empty whenever no `\aftergroup` ran, which is
    /// almost always.
    pub fn take_after_group(&mut self) -> Vec<Token> {
        std::mem::take(&mut self.after_group_tokens)
    }

    /// Report an error and CARRY ON — `tex.web` §82's `print_err(msg)` followed
    /// by `error`, which prints a period and then §311's context display.
    ///
    /// This is TeX's error model and it is not a detail: a document with one
    /// bad constant in it still sets, because every condition tex can guess a
    /// value for is reported and then given one. Raising a `TexError` instead
    /// stops the run, which is right only for what §93 calls fatal.
    ///
    /// The three lines tex writes are joined with nothing, because that is what
    /// separates them: `print_ln` ends a terminal line and adds no character,
    /// so the message stream reads `! Number too big.l.6 \count1=…`. It is the
    /// same reading `crate::parity::messages_of` takes of tex's own output,
    /// which is what makes the two comparable at all.
    pub fn report(&mut self, lx: &Lexer, msg: &str) {
        let context = lx.context().unwrap_or_default();
        self.errors
            .push(format!("! {msg}.{}", context.replace('\n', "")));
    }

    /// The errors reported since the last call, clearing them.
    pub fn take_errors(&mut self) -> Vec<String> {
        std::mem::take(&mut self.errors)
    }

    /// Record the current value so the enclosing group can put it back.
    ///
    /// `\global` skips every frame, which is what makes `\gdef` survive to the
    /// outermost level rather than only to the next `}`.
    fn save(&mut self, rec: Save) {
        if self.global || self.groups.is_empty() {
            return;
        }
        if let Some(frame) = self.groups.last_mut() {
            frame.push(rec);
        }
    }

    fn set_meaning(&mut self, name: CsId, m: Meaning) {
        let old = self.meanings.get(&name).cloned();
        self.save(Save::Meaning(name, old));
        // A global assignment wipes the saved values other groups hold, so no
        // `}` can restore the old meaning over it.
        if self.global {
            for frame in &mut self.groups {
                frame.retain(|s| !matches!(s, Save::Meaning(n, _) if *n == name));
            }
        }
        self.meanings.insert(name, m);
    }

    fn set_count(&mut self, reg: i64, val: i64) {
        let old = self.count.get(&reg).copied();
        self.save(Save::Count(reg, old));
        self.count.insert(reg, val);
    }

    fn set_cat(&mut self, c: char, cat: Cat) {
        self.save(Save::Cat(c, self.cats.get(c)));
        self.cats.set(c, cat);
    }

    // ── execution ────────────────────────────────────────────────────────

    /// One token of execution. `Ok(true)` means `\end` was seen.
    fn step(&mut self, lx: &mut Lexer, tok: Token) -> R<bool> {
        match &tok {
            Token::Char(_, Cat::BeginGroup) => {
                self.begin_group();
                return Ok(false);
            }
            Token::Char(_, Cat::EndGroup) => {
                self.end_group()?;
                let after = self.take_after_group();
                lx.push_back(&after);
                return Ok(false);
            }
            Token::Char(..) => return Ok(false),
            Token::Cs(_) => {}
        }
        let Token::Cs(name) = &tok else {
            return Ok(false);
        };
        let name = *name;
        if self.try_expand(lx, name, false)? {
            return Ok(false);
        }
        match name.name() {
            "end" => return Ok(true),
            kind @ ("def" | "gdef" | "edef" | "xdef") => self.do_def(lx, kind)?,
            "newcommand" | "renewcommand" | "providecommand" | "DeclareRobustCommand" => {
                self.do_newcommand(lx, name.name())?
            }
            "let" => self.do_let(lx)?,
            "futurelet" => self.do_futurelet(lx, false)?,
            // `\long` and `\outer` take a prefix each, exactly as `\global`
            // does, and chain in any order: `\global\outer\long\def` is one
            // definition with three of them.
            "long" | "outer" | "protected" => {
                let which = name.name();
                match which {
                    "long" => self.long = true,
                    "outer" => self.outer = true,
                    _ => self.protected = true,
                }
                let Some(next) = lx.next_token(&self.cats) else {
                    return Err(TexError("Missing control sequence".into()));
                };
                let out = self.step(lx, next);
                match which {
                    "long" => self.long = false,
                    "outer" => self.outer = false,
                    _ => self.protected = false,
                }
                return out;
            }
            "global" => {
                self.global = true;
                let Some(next) = lx.next_token(&self.cats) else {
                    return Err(TexError("Missing control sequence".into()));
                };
                let out = self.step(lx, next);
                self.global = false;
                return out;
            }
            "begingroup" => self.begin_group(),
            "endgroup" => {
                self.end_group()?;
                let after = self.take_after_group();
                lx.push_back(&after);
            }
            // `tex.web` §1288. The group is read unexpanded and its characters
            // are looked up in `\uccode`/`\lccode`.
            "uppercase" | "lowercase" => {
                let table = match name.name() {
                    "uppercase" => crate::charcodes::Table::Upper,
                    _ => crate::charcodes::Table::Lower,
                };
                self.do_case_shift(lx, table)?
            }
            // §326: hold the next token and insert it after the enclosing
            // group's `}`.
            "aftergroup" => {
                let Some(t) = lx.next_token(&self.cats) else {
                    return Err(TexError("Missing token for \\aftergroup".into()));
                };
                self.after_group(lx, t);
            }
            // §1269: hold the next token and insert it after the assignment
            // that follows finishes.
            "afterassignment" => {
                let Some(t) = lx.next_token(&self.cats) else {
                    return Err(TexError("Missing token for \\afterassignment".into()));
                };
                self.after_assignment = Some(t);
            }
            "catcode" => self.do_catcode(lx)?,
            "mathcode" | "lccode" | "uccode" | "sfcode" | "delcode" => {
                let t = crate::charcodes::Table::from_name(name.name())
                    .expect("one of the five just matched");
                self.do_charcode(lx, t)?
            }
            "count" => self.do_count_assign(lx)?,
            "advance" => self.do_arith(lx, Arith::Add)?,
            "multiply" => self.do_arith(lx, Arith::Mul)?,
            "divide" => self.do_arith(lx, Arith::Div)?,
            "message" => {
                let text = self.read_group_text(lx)?;
                self.messages.push(text);
            }
            "relax" | "par" | "ignorespaces" => {}
            other => {
                return Err(TexError(format!("Undefined control sequence \\{other}")));
            }
        }
        Ok(false)
    }

    // ── the expandable primitives ────────────────────────────────────────

    /// Handle `name` if it is expandable, returning whether it was.
    ///
    /// This is the gullet. Both the executor and `expand_to_text` route through
    /// it so a conditional behaves identically in a file and inside a `\message`
    /// body — in TeX they are the same machinery, and splitting them here would
    /// make `\ifnum` work in one place and not the other.
    fn try_expand(&mut self, lx: &mut Lexer, name: CsId, pending_only: bool) -> R<bool> {
        if let Some(Meaning::Macro(_)) = self.meanings.get(&name) {
            self.expand_macro(lx, name, pending_only)?;
            return Ok(true);
        }
        // A `\let` alias MEANS the primitive it was given, so it must act like
        // one here too. The dispatch below is by NAME, so without this an alias
        // is matched as itself: `\let\ifdim=\iffalse` still reached the
        // \ifdim arm and reported an unsupported conditional, which is how a
        // document says "I know this engine has no dimensions, take the other
        // branch" and was refused anyway.
        let name = match self.meanings.get(&name) {
            Some(Meaning::Primitive(p)) if *p != name => *p,
            _ => name,
        };
        match name.name() {
            // The advice markers: they carry the "inside advice" depth through
            // the token stream, and expand to nothing.
            ADVICE_IN | ADVICE_OUT => {
                self.advice_marker(name.name());
                Ok(true)
            }
            n if CONDITIONALS.contains(&n) => {
                self.do_conditional(lx, n, pending_only)?;
                Ok(true)
            }
            "else" => {
                // Reaching `\else` in running text means the true branch ran;
                // everything to the matching `\fi` is skipped.
                match self.conds.pop() {
                    Some(_) => {
                        self.skip_to(lx, false, pending_only)?;
                        Ok(true)
                    }
                    None => Err(TexError("Extra \\else".into())),
                }
            }
            "or" => match self.conds.pop() {
                Some(_) => {
                    self.skip_to(lx, false, pending_only)?;
                    Ok(true)
                }
                None => Err(TexError("Extra \\or".into())),
            },
            "fi" => match self.conds.pop() {
                Some(_) => Ok(true),
                None => Err(TexError("Extra \\fi".into())),
            },
            "expandafter" => {
                self.do_expandafter(lx, pending_only)?;
                Ok(true)
            }
            // `\string` is expandable and reaches running text, not only the
            // inside of a `\message`. tex.web 262 has the expander produce the
            // characters of the next token wherever it appears; handling it only
            // in message context left it undefined in the body of a document.
            // `\csstring` is the same primitive without the escape character,
            // and lower.rs already answered it inside a `\message`. In running
            // text it was undefined, which is why the prelude had to spell a
            // lone backslash as `\string\\` -- escape plus the name `\`, i.e.
            // TWO backslashes, so every `\textbackslash` in a code listing came
            // out doubled. `\csstring\\` is the one character.
            "string" | "csstring" => {
                let bare = name.name() == "csstring";
                if let Some(t) = self.take(lx, pending_only) {
                    let text = match &t {
                        Token::Cs(n) if bare => n.name().to_string(),
                        Token::Cs(n) => format!("{}{}", self.escape, n.name()),
                        other => other.to_text(self.escape),
                    };
                    let toks: Vec<Token> =
                        text.chars().map(|c| Token::Char(c, Cat::Other)).collect();
                    lx.push_back(&toks);
                }
                Ok(true)
            }
            "noexpand" => {
                // The next token is passed through unexpanded. Reading it and
                // pushing it back is enough here because nothing re-examines it.
                if let Some(t) = self.take(lx, pending_only) {
                    lx.push_back(&[t]);
                }
                Ok(true)
            }
            // `\meaning` is a `convert` primitive (`tex.web` §470), so it is
            // expandable and belongs beside `\string` rather than in the
            // executor: it turns the NEXT token into the characters §296's
            // `print_meaning` would write for it.
            "meaning" => {
                if let Some(t) = self.take(lx, pending_only) {
                    let text = self.meaning_text(&t);
                    let toks: Vec<Token> =
                        text.chars().map(|c| Token::Char(c, Cat::Other)).collect();
                    lx.push_back(&toks);
                }
                Ok(true)
            }
            "csname" => {
                let built = self.read_csname(lx, pending_only)?;
                // An undefined \csname name becomes \relax, per tex.web §372.
                let id = CsId::intern(&built);
                self.meanings
                    .entry(id)
                    .or_insert_with(|| Meaning::Primitive(CsId::intern("relax")));
                lx.push_back(&[Token::Cs(id)]);
                Ok(true)
            }
            _ => Ok(false),
        }
    }

    /// Read one token from whichever source this context uses.
    fn take(&mut self, lx: &mut Lexer, pending_only: bool) -> Option<Token> {
        match pending_only {
            true => lx.pending.pop(),
            false => lx.next_token(&self.cats),
        }
    }

    /// `\expandafter\A\B` — hold `\A`, expand `\B` once, then put `\A` back.
    fn do_expandafter(&mut self, lx: &mut Lexer, pending_only: bool) -> R<()> {
        let Some(held) = self.take(lx, pending_only) else {
            return Err(TexError("Missing token after \\expandafter".into()));
        };
        let Some(next) = self.take(lx, pending_only) else {
            return Err(TexError("Missing token after \\expandafter".into()));
        };
        match &next {
            Token::Cs(n) => {
                let n = *n;
                // Expand in the SAME context `\expandafter` was read in. Forcing
                // pending-only here meant the one-step expansion could not reach
                // the file, so `\expandafter\def\csname foo\endcsname{...}` at
                // the top of a document had `\csname` scanning an empty pending
                // list and reporting a missing `\endcsname` that was sitting in
                // the source a token away.
                if !self.try_expand(lx, n, pending_only)? {
                    lx.push_back(&[next]);
                }
            }
            _ => lx.push_back(&[next]),
        }
        lx.push_back(&[held]);
        Ok(())
    }

    // ── conditionals ─────────────────────────────────────────────────────

    fn do_conditional(&mut self, lx: &mut Lexer, name: &str, pending_only: bool) -> R<()> {
        // `\unless` negates whatever this one decides. Taken BEFORE the test so
        // that a conditional inside the test -- `\ifx` over two macros one of
        // which expands -- cannot spend it.
        let negated = std::mem::take(&mut self.unless);
        let truth = match name {
            "iftrue" => true,
            "iffalse" => false,
            "ifnum" => {
                let a = self.scan_number(lx, pending_only)?;
                let rel = self.read_relation(lx, pending_only)?;
                let b = self.scan_number(lx, pending_only)?;
                match rel {
                    '<' => a < b,
                    '>' => a > b,
                    _ => a == b,
                }
            }
            // `tex.web` §503: the same comparison `\ifnum` makes, over
            // dimensions -- only the scanner differs.
            "ifdim" => {
                let a = self.scan_dimen(lx, pending_only)?;
                let rel = self.read_relation(lx, pending_only)?;
                let b = self.scan_dimen(lx, pending_only)?;
                match rel {
                    '<' => a < b,
                    '>' => a > b,
                    _ => a == b,
                }
            }
            "ifodd" => self.scan_number(lx, pending_only)? % 2 != 0,
            "ifdefined" => match self.take(lx, pending_only) {
                Some(Token::Cs(n)) => self.meanings.contains_key(&n),
                _ => false,
            },
            // etex.ch's `if_cs_code`. It reads the characters up to
            // `\endcsname` exactly as `\csname` does and then asks whether that
            // name is defined -- but its `id_lookup` runs with
            // `no_new_control_sequence` still TRUE, so a name it does not find
            // is not entered in the hash table. That single difference is the
            // whole primitive: `tex.web` §372's `\csname` DEFINES what it does
            // not find (as `\relax`), which makes it useless for asking the
            // question, and `\ifcsname` answers without changing the answer.
            //
            // The predicate is the same one `\ifdefined` above uses, because
            // etex's is: both test `eq_type(cur_cs) <> undefined_cs`.
            "ifcsname" => {
                let built = self.read_csname(lx, pending_only)?;
                self.meanings.contains_key(&CsId::intern(&built))
            }
            "ifx" => {
                let a = self.take(lx, pending_only);
                let b = self.take(lx, pending_only);
                self.meanings_equal(a.as_ref(), b.as_ref())
            }
            "if" => {
                // `\if` compares CHARACTER CODES after expansion; a control
                // sequence compares equal to any other control sequence.
                let a = self.expand_one_char(lx, pending_only)?;
                let b = self.expand_one_char(lx, pending_only)?;
                a == b
            }
            // `tex.web` §503's box conditionals. Each reads an eight-bit
            // register number (§433) and asks what is in that box register: is
            // it empty, does it hold an \hbox, does it hold a \vbox.
            //
            // texrs has no `\setbox`, so every box register is VOID -- which is
            // not a refusal to answer, it is the answer. §462's `box(n)` is
            // `null` for a register nothing has filled, and that is the state
            // of all 256 of them here. So `\ifvoid` is true, `\ifhbox` and
            // `\ifvbox` are false, and a document that reads one gets what tex
            // would give it for the same document -- one that cannot have
            // filled a box, because `\setbox` stops the run before it could.
            //
            // The day `\setbox` exists this has to consult it. It is written as
            // one arm over the three names so that there is one place to
            // change rather than three.
            "ifvoid" | "ifhbox" | "ifvbox" => {
                let reg = self.scan_number(lx, pending_only)?;
                if !(0..=255).contains(&reg) {
                    self.report(lx, &format!("Bad register code ({reg})"));
                }
                name == "ifvoid"
            }
            "ifcase" => {
                let n = self.scan_number(lx, pending_only)?;
                return self.do_ifcase(lx, n, pending_only);
            }
            other => return Err(TexError(format!("Unsupported conditional \\{other}"))),
        };
        match truth != negated {
            true => self.conds.push(CondState::Taken),
            false => {
                // Skip to `\else` (run that branch) or `\fi` (run nothing).
                let hit_else = self.skip_to(lx, true, pending_only)?;
                if hit_else {
                    self.conds.push(CondState::Done);
                }
            }
        }
        Ok(())
    }

    /// `\ifcase<n>` selects the nth `\or` branch, `\else` being the default.
    ///
    /// `tex.web` §509 is `while n<>0`, not `while n>0`, and only an `\or`
    /// decrements: landing on `\else` goes straight to `common_ending`, which
    /// runs the else text, and landing on `\fi` ends the conditional with
    /// nothing run. That is why a selector that is NEGATIVE, or past the last
    /// `\or`, takes the `\else` branch rather than case 0 -- a negative n never
    /// reaches zero, so every `\or` is skipped until the `\else` stops it.
    fn do_ifcase(&mut self, lx: &mut Lexer, n: i64, pending_only: bool) -> R<()> {
        let mut remaining = n;
        while remaining != 0 {
            match self.pass_text(lx, pending_only)? {
                // Another case boundary: one case skipped, keep counting.
                Stop::Or => remaining -= 1,
                // §509's `common_ending` with `cur_chr <> fi_code`: the else
                // text runs and its `\fi` closes the conditional.
                Stop::Else => {
                    self.conds.push(CondState::Done);
                    return Ok(());
                }
                // The conditional ended before the case was reached.
                Stop::Fi => return Ok(()),
            }
        }
        self.conds.push(CondState::Taken);
        Ok(())
    }

    /// Skip tokens to the matching `\else`/`\or` (when `stop_at_else`) or `\fi`.
    ///
    /// Returns whether it stopped at an `\else`/`\or` rather than the `\fi`.
    /// Nested conditionals are counted so a skipped branch containing its own
    /// `\if` does not mistake that one's `\fi` for the outer one's.
    fn skip_to(&mut self, lx: &mut Lexer, stop_at_else: bool, pending_only: bool) -> R<bool> {
        loop {
            match self.pass_text(lx, pending_only)? {
                Stop::Fi => return Ok(false),
                // `\else` and `\or` only stop a skip that is looking for one;
                // to a skip that is not, they are ordinary tokens of the
                // skipped text and the scan runs on to the `\fi`.
                _ if !stop_at_else => continue,
                _ => return Ok(true),
            }
        }
    }

    /// `tex.web` §494's `pass_text`: skip balanced conditional text and say
    /// WHICH of the three boundaries stopped it.
    ///
    /// `\ifcase` needs the distinction -- `\or` counts down a case and `\else`
    /// does not -- while an ordinary skip only needs "else-or-or versus fi",
    /// which is why `skip_to` is a wrapper rather than a second scanner.
    fn pass_text(&mut self, lx: &mut Lexer, pending_only: bool) -> R<Stop> {
        let mut depth = 0usize;
        loop {
            let Some(t) = self.take(lx, pending_only) else {
                return Err(TexError("Incomplete \\if; all text was ignored".into()));
            };
            let Token::Cs(n) = &t else { continue };
            match n.name() {
                n if CONDITIONALS.contains(&n) => depth += 1,
                "fi" => match depth {
                    0 => return Ok(Stop::Fi),
                    _ => depth -= 1,
                },
                "else" if depth == 0 => return Ok(Stop::Else),
                "or" if depth == 0 => return Ok(Stop::Or),
                _ => {}
            }
        }
    }

    fn read_relation(&mut self, lx: &mut Lexer, pending_only: bool) -> R<char> {
        loop {
            let Some(t) = self.take(lx, pending_only) else {
                return Err(TexError("Missing = inserted for \\ifnum".into()));
            };
            match &t {
                t if t.is_space() => continue,
                Token::Char(c, _) if *c == '<' || *c == '>' || *c == '=' => return Ok(*c),
                _ => return Err(TexError("Missing = inserted for \\ifnum".into())),
            }
        }
    }

    /// `\ifx` equality: same meaning, or the same character token.
    fn meanings_equal(&self, a: Option<&Token>, b: Option<&Token>) -> bool {
        match (a, b) {
            (Some(Token::Cs(x)), Some(Token::Cs(y))) => {
                match (self.meanings.get(x), self.meanings.get(y)) {
                    (None, None) => true,
                    (Some(mx), Some(my)) => mx == my,
                    // One side is a bare primitive and the other has been GIVEN
                    // that primitive as its meaning. texrs does not enter a
                    // primitive in `meanings` -- primitives are dispatched by
                    // name -- so `\relax` itself is absent from the table while
                    // a name `\let` to it, or one `tex.web` §372's `\csname`
                    // made `\relax` because it found nothing, carries
                    // `Primitive(relax)`. §507 compares the COMMAND, and both
                    // of these are the same command.
                    //
                    // This is what `\expandafter\ifx\csname NAME\endcsname\relax`
                    // rests on -- LaTeX's older `\@ifundefined` is exactly that
                    // line -- and it answered "not \relax" for every name until
                    // this arm existed.
                    (Some(Meaning::Primitive(p)), None) => p == y,
                    (None, Some(Meaning::Primitive(p))) => p == x,
                    _ => false,
                }
            }
            (Some(Token::Char(c1, k1)), Some(Token::Char(c2, k2))) => c1 == c2 && k1 == k2,
            // A control sequence `\let` (or `\futurelet`) to a character token
            // MEANS that character, so it compares equal to it -- `tex.web` §507
            // compares meanings, and the meaning of `\next` after
            // `\futurelet\next` over an `A` is the character A. Without this,
            // `\ifx\next[` is always false, and that single comparison is what
            // LaTeX's `\@ifnextchar` is, hence every optional argument in the
            // language.
            (Some(Token::Cs(x)), Some(Token::Char(c, k)))
            | (Some(Token::Char(c, k)), Some(Token::Cs(x))) => {
                matches!(self.meanings.get(x), Some(Meaning::Char(mc, mk)) if mc == c && mk == k)
            }
            _ => false,
        }
    }

    /// Expand until a character token appears, for `\if`'s code comparison.
    fn expand_one_char(&mut self, lx: &mut Lexer, pending_only: bool) -> R<char> {
        loop {
            let Some(t) = self.take(lx, pending_only) else {
                return Err(TexError("Missing token for \\if".into()));
            };
            match &t {
                Token::Char(c, _) => return Ok(*c),
                Token::Cs(n) => {
                    let n = *n;
                    if !self.try_expand(lx, n, pending_only)? {
                        // An unexpandable control sequence compares as itself.
                        return Ok('\u{0}');
                    }
                }
            }
        }
    }

    // ── definitions ──────────────────────────────────────────────────────

    /// `\def`, `\gdef`, `\edef`, `\xdef` — the last two expand the body now.
    /// A dimension: an optional sign, a decimal number, and a unit
    /// (`tex.web` §448-453). The result is scaled points, which is the only
    /// form a dimension ever has -- `pt` is not privileged, it is just the unit
    /// whose ratio is one.
    /// The number in front of a unit: a sign, an integer part, and a fraction
    /// already scaled to 65536ths. Shared by the finite scanner and the one
    /// that also accepts `fil`, so the two cannot drift.
    fn scan_dimen_number(&mut self, lx: &mut Lexer, pending_only: bool) -> R<(i64, i64, i64)> {
        let mut sign = 1i64;
        let mut cur = loop {
            let Some(t) = self.take(lx, pending_only) else {
                return Err(TexError("Missing number, treated as zero".into()));
            };
            match &t {
                t if t.is_space() => continue,
                Token::Char('-', _) => {
                    sign = -sign;
                    continue;
                }
                Token::Char('+', _) => continue,
                other => break *other,
            }
        };
        // The integer part, then an optional fraction after `.` or `,`.
        let mut whole = String::new();
        let mut fraction = String::new();
        let mut seen_point = false;
        loop {
            match &cur {
                Token::Char(c, _) if c.is_ascii_digit() => match seen_point {
                    true => fraction.push(*c),
                    false => whole.push(*c),
                },
                Token::Char('.' | ',', _) if !seen_point => seen_point = true,
                other => {
                    lx.push_back(std::slice::from_ref(other));
                    break;
                }
            }
            match self.take(lx, pending_only) {
                Some(t) => cur = t,
                None => break,
            }
        }
        let int: i64 = whole.parse().unwrap_or(0);
        Ok((sign, int, crate::dimen::round_decimals(&fraction)))
    }

    /// A finite unit's value in scaled points, under the mode the scanner is in.
    ///
    /// `tex.web` §455: in mu mode `mu` is the only unit there is, and outside it
    /// `mu` is not a unit at all. A mu scales exactly as a point does -- both
    /// are 65536ths -- so the conversion is the identity and the whole content
    /// of the rule is which spellings are accepted where.
    fn finite_unit(&self, int: i64, frac: i64, unit: &str) -> Option<i64> {
        match self.mu_units {
            true => (unit == "mu").then(|| int * crate::dimen::UNITY + frac),
            false => crate::dimen::to_scaled(int, frac, unit),
        }
    }

    /// §454's complaint, which names the unit it would have inserted: `pt`
    /// where a dimension was wanted and `mu` where a math glue was. Measured
    /// against luatex, which says `Illegal unit of measure (mu inserted)` for
    /// `\muskip0=1pt`.
    fn illegal_unit(&self) -> TexError {
        match self.mu_units {
            true => TexError("Illegal unit of measure (mu inserted)".into()),
            false => TexError("Illegal unit of measure (pt inserted)".into()),
        }
    }

    /// A dimension: the number, then a unit (`tex.web` §448-453). The result is
    /// scaled points, which is the only form a dimension ever has.
    pub fn scan_dimen(&mut self, lx: &mut Lexer, pending_only: bool) -> R<i64> {
        // `\dimexpr ...\relax` stands where a dimension does.
        if let Some(t) = self.take(lx, pending_only) {
            let is_expr = matches!(&t, Token::Cs(n) if n.name() == "dimexpr");
            lx.push_back(std::slice::from_ref(&t));
            if is_expr {
                let _ = self.take(lx, pending_only);
                return self.scan_expr(lx, pending_only, true);
            }
        }
        let (sign, int, frac) = self.scan_dimen_number(lx, pending_only)?;
        // `tex.web` §453 takes an optional `true` in front of the unit and
        // divides by the magnification ratio. `\mag` is 1000 here and there is
        // no way to change it, so a true unit IS the unit -- but the keyword
        // still has to be eaten, or `1truept` reads as the unit `tr` and the
        // document stops on an illegal unit of measure.
        let _true_prefix = self.scan_keyword(lx, "true", pending_only);
        let mut unit = String::new();
        while unit.len() < 2 {
            let Some(t) = self.take(lx, pending_only) else {
                break;
            };
            match &t {
                t if t.is_space() && unit.is_empty() => continue,
                Token::Char(c, _) if c.is_ascii_alphabetic() => unit.push(c.to_ascii_lowercase()),
                other => {
                    lx.push_back(std::slice::from_ref(other));
                    break;
                }
            }
        }
        let Some(sp) = self.finite_unit(int, frac, &unit) else {
            return Err(self.illegal_unit());
        };
        // One optional space is absorbed after a unit, as after a constant.
        if let Some(t) = self.take(lx, pending_only) {
            if !t.is_space() {
                lx.push_back(std::slice::from_ref(&t));
            }
        }
        Ok((sign * sp).clamp(-crate::dimen::MAX_DIMEN, crate::dimen::MAX_DIMEN))
    }

    /// `\uppercase{...}` / `\lowercase{...}` — `tex.web` §1288.
    ///
    /// The group is read WITHOUT expanding it, every character token is looked
    /// up in `\uccode` or `\lccode`, and the result is pushed back to be read
    /// again. A zero code means "no case", so the character stands: that is why
    /// `\uppercase{a1}` is `A1` and not `A` followed by nothing. The catcode
    /// travels with the character unchanged, which is the property LaTeX's
    /// `\MakeUppercase` is built on.
    pub fn do_case_shift(&mut self, lx: &mut Lexer, table: crate::charcodes::Table) -> R<()> {
        let group = self.read_group_tokens(lx)?;
        let shifted: Vec<Token> = group
            .into_iter()
            .map(|t| match &t {
                Token::Char(c, cat) => match self.charcodes.get(table, *c) {
                    0 => t,
                    code => match u32::try_from(code).ok().and_then(char::from_u32) {
                        Some(to) => Token::Char(to, *cat),
                        None => t,
                    },
                },
                Token::Cs(_) => t,
            })
            .collect();
        lx.push_back(&shifted);
        Ok(())
    }

    /// What `\meaning` writes for a token (`tex.web` §296's `print_meaning`
    /// over §298's `print_cmd_chr`).
    ///
    /// Every shape here was read off tex 3.141592653, not derived from the
    /// source: a macro is `macro:` then its parameter text, `->`, and its body;
    /// a `\chardef` constant is `\char"41`; a register name is the register it
    /// stands for; a character carries the NAME of its category, which is why
    /// this cannot be `Token::to_text`.
    pub fn meaning_text(&self, tok: &Token) -> String {
        let Token::Cs(name) = tok else {
            let Token::Char(c, cat) = tok else {
                unreachable!("a token is a character or a control sequence")
            };
            return Self::char_meaning(*c, *cat);
        };
        match self.meanings.get(name) {
            Some(Meaning::Char(c, cat)) => Self::char_meaning(*c, *cat),
            // A `\mathchardef` name reads back as `\char` rather than
            // `\mathchar`: both are `Meaning::CharDef`, and telling them apart
            // needs a variant `src/format.rs` also has to serialise.
            Some(Meaning::CharDef(v)) => format!("{}char\"{v:X}", self.escape),
            Some(Meaning::CountDef(r)) => self.register_name(*r),
            Some(Meaning::ToksDef(r)) => format!("{}toks{r}", self.escape),
            Some(Meaning::Primitive(p)) => format!("{}{}", self.escape, p.name()),
            Some(Meaning::Macro(m)) => {
                let mut out = String::new();
                // §1295's `print_cmd_chr` prints the whole thing as ONE escaped
                // string -- `print_esc("long outer macro")` -- so the prefixes
                // run together and a single space separates the last of them
                // from the word `macro`: `\long\outer macro:`.
                for (on, word) in [
                    (m.protected, "protected"),
                    (m.long, "long"),
                    (m.outer, "outer"),
                ] {
                    if on {
                        out.push(self.escape);
                        out.push_str(word);
                    }
                }
                if !out.is_empty() {
                    out.push(' ');
                }
                out.push_str("macro:");
                out.push_str(&self.tokens_text(&m.params));
                out.push_str("->");
                out.push_str(&self.tokens_text(&m.body));
                out
            }
            // Not in the meaning table: either a primitive nothing has
            // redefined, or a name that means nothing at all. The corpus is
            // the list of primitives texrs resolves -- `tests/docs_reference_
            // sections.rs` is what keeps it level with the dispatch -- so it
            // answers which of the two this is.
            None => match crate::corpus::lookup(&format!("{}{}", self.escape, name.name())) {
                Some(_) => format!("{}{}", self.escape, name.name()),
                None => "undefined".to_string(),
            },
        }
    }

    /// The register a slot number names, spelt as the document would spell it.
    fn register_name(&self, slot: i64) -> String {
        let e = self.escape;
        if slot >= crate::compiler::MUSKIP_BASE {
            let n = (slot - crate::compiler::MUSKIP_BASE) / crate::compiler::SKIP_STRIDE;
            return format!("{e}muskip{n}");
        }
        if slot >= crate::compiler::SKIP_BASE {
            let n = (slot - crate::compiler::SKIP_BASE) / crate::compiler::SKIP_STRIDE;
            return format!("{e}skip{n}");
        }
        match slot >= crate::compiler::DIMEN_BASE {
            true => format!("{e}dimen{}", slot - crate::compiler::DIMEN_BASE),
            false => format!("{e}count{slot}"),
        }
    }

    /// A character token's meaning: the category's own name and the character
    /// (`tex.web` §298). Measured against tex, one category at a time.
    fn char_meaning(c: char, cat: Cat) -> String {
        match cat {
            Cat::Letter => format!("the letter {c}"),
            Cat::BeginGroup => format!("begin-group character {c}"),
            Cat::EndGroup => format!("end-group character {c}"),
            Cat::MathShift => format!("math shift character {c}"),
            Cat::AlignTab => format!("alignment tab character {c}"),
            Cat::Param => format!("macro parameter character {c}"),
            Cat::Superscript => format!("superscript character {c}"),
            Cat::Subscript => format!("subscript character {c}"),
            Cat::Space => format!("blank space {c}"),
            _ => format!("the character {c}"),
        }
    }

    /// `\toks<n>={...}` or `\toks<n>=\toks<m>`.
    ///
    /// The braced form is stored VERBATIM: nothing in it expands, which is the
    /// difference between a token register and a macro. Measured --
    /// `\toks0={\x}` reads back as `\x`, whatever `\x` means.
    pub fn do_toks_assign(&mut self, lx: &mut Lexer, reg: i64) -> R<()> {
        self.skip_equals(lx)?;
        let value = loop {
            let Some(t) = lx.next_token(&self.cats) else {
                return Err(TexError("Missing { inserted".into()));
            };
            match &t {
                t if t.is_space() => continue,
                Token::Char(_, Cat::BeginGroup) => break self.read_balanced(lx)?,
                // `\toks1=\toks0` copies, and `\toks1=\toksA` copies through a
                // name defined by \toksdef.
                Token::Cs(n) => {
                    let from = match n.name() {
                        "toks" => self.scan_number(lx, false)?,
                        _ => match self.meanings.get(n) {
                            Some(Meaning::ToksDef(r)) => *r,
                            _ => return Err(TexError("Missing { inserted".into())),
                        },
                    };
                    break self.toks.get(&from).cloned().unwrap_or_default();
                }
                _ => return Err(TexError("Missing { inserted".into())),
            }
        };
        self.save(Save::Toks(reg, self.toks.get(&reg).cloned()));
        self.toks.insert(reg, value);
        Ok(())
    }

    /// What `\the\toks<n>` writes: the tokens as text, by the same rule
    /// `\string` uses -- a control word carries a trailing space, a
    /// single-character control sequence does not.
    /// A token list as text, by the token-list rule: a control WORD carries a
    /// trailing space, a one-character control sequence does not. Shared by
    /// `\the\toks` and `\detokenize`, which write the same way.
    pub fn tokens_text(&self, tokens: &[Token]) -> String {
        let mut out = String::new();
        for t in tokens {
            match t {
                Token::Char(c, _) => out.push(*c),
                Token::Cs(id) => {
                    let name = id.name();
                    out.push(self.escape);
                    out.push_str(name);
                    if name.chars().all(|c| c.is_alphabetic()) {
                        out.push(' ');
                    }
                }
            }
        }
        out
    }

    pub fn toks_text(&self, reg: i64) -> String {
        let Some(tokens) = self.toks.get(&reg) else {
            return String::new();
        };
        let mut out = String::new();
        for t in tokens {
            match t {
                Token::Char(c, _) => out.push(*c),
                Token::Cs(id) => {
                    let name = id.name();
                    out.push(self.escape);
                    out.push_str(name);
                    // A control WORD carries a trailing space here, however
                    // short: `\b` prints as `\b `. A control sequence made of
                    // one non-letter does not. Measured -- and it is not the
                    // rule `\string` follows, which never adds the space, so
                    // the two cannot share a renderer.
                    if name.chars().all(|c| c.is_alphabetic()) {
                        out.push(' ');
                    }
                }
            }
        }
        out
    }

    /// The register a `\toksdef` name stands for.
    pub fn toks_cs(&self, name: CsId) -> Option<i64> {
        match self.meanings.get(&name) {
            Some(Meaning::ToksDef(r)) => Some(*r),
            _ => None,
        }
    }

    /// eTeX's `\numexpr` and `\dimexpr`, evaluated on the spot.
    ///
    /// Ordinary precedence, parentheses, and left to right within a level. The
    /// one rule worth stating is division: it ROUNDS, half away from zero, so
    /// `7/2` is 4 and `-7/2` is -4 -- which is not what `\divide` does, and is
    /// why the two cannot share an implementation. Measured against
    /// LuaTeX 1.24.0.
    pub fn scan_expr(&mut self, lx: &mut Lexer, pending_only: bool, dimen: bool) -> R<i64> {
        let v = self.expr_sum(lx, pending_only, dimen)?;
        // An expression is closed by an optional `\relax`, which is absorbed.
        if let Some(t) = self.take(lx, pending_only) {
            match &t {
                Token::Cs(n) if n.name() == "relax" => {}
                other => lx.push_back(std::slice::from_ref(other)),
            }
        }
        Ok(v)
    }

    fn expr_sum(&mut self, lx: &mut Lexer, pending_only: bool, dimen: bool) -> R<i64> {
        let mut acc = self.expr_term(lx, pending_only, dimen)?;
        loop {
            match self.expr_operator(lx, pending_only, &['+', '-']) {
                Some('+') => acc += self.expr_term(lx, pending_only, dimen)?,
                Some('-') => acc -= self.expr_term(lx, pending_only, dimen)?,
                _ => return Ok(acc),
            }
        }
    }

    fn expr_term(&mut self, lx: &mut Lexer, pending_only: bool, dimen: bool) -> R<i64> {
        let mut acc = self.expr_factor(lx, pending_only, dimen)?;
        loop {
            match self.expr_operator(lx, pending_only, &['*', '/']) {
                // A multiplier and a divisor are integers even in a dimension
                // expression: `1pt*3` is three points, not a square.
                Some('*') => acc *= self.expr_factor(lx, pending_only, false)?,
                Some('/') => {
                    let by = self.expr_factor(lx, pending_only, false)?;
                    if by == 0 {
                        return Err(TexError("Arithmetic overflow".into()));
                    }
                    acc = round_div(acc, by);
                }
                _ => return Ok(acc),
            }
        }
    }

    fn expr_factor(&mut self, lx: &mut Lexer, pending_only: bool, dimen: bool) -> R<i64> {
        // Skip spaces to see whether a group is opening.
        loop {
            let Some(t) = self.take(lx, pending_only) else {
                return Err(TexError("Missing number, treated as zero".into()));
            };
            match &t {
                t if t.is_space() => continue,
                Token::Char('(', _) => {
                    let v = self.expr_sum(lx, pending_only, dimen)?;
                    match self.take(lx, pending_only) {
                        Some(Token::Char(')', _)) => return Ok(v),
                        _ => return Err(TexError("Missing ) inserted".into())),
                    }
                }
                other => {
                    lx.push_back(std::slice::from_ref(other));
                    return match dimen {
                        true => self.scan_dimen(lx, pending_only),
                        false => self.scan_number(lx, pending_only),
                    };
                }
            }
        }
    }

    /// The next operator, if the next non-space token is one of `wanted`.
    fn expr_operator(
        &mut self,
        lx: &mut Lexer,
        pending_only: bool,
        wanted: &[char],
    ) -> Option<char> {
        loop {
            let t = self.take(lx, pending_only)?;
            if t.is_space() {
                continue;
            }
            if let Token::Char(c, _) = &t {
                if wanted.contains(c) {
                    return Some(*c);
                }
            }
            lx.push_back(std::slice::from_ref(&t));
            return None;
        }
    }

    /// A dimension that may be infinite: the same number, but with `fil`,
    /// `fill` or `filll` accepted as its unit. Returns the value and its order,
    /// 0 being an ordinary finite dimension.
    pub fn scan_dimen_or_fil(&mut self, lx: &mut Lexer, pending_only: bool) -> R<(i64, i64)> {
        let (sign, int, frac) = self.scan_dimen_number(lx, pending_only)?;
        // §453's optional `true`, eaten here for the same reason it is eaten in
        // `scan_dimen`: with `\mag` fixed at 1000 a true unit is the unit, but
        // the word still has to come off the stream.
        let _true_prefix = self.scan_keyword(lx, "true", pending_only);
        // Up to five letters, because `filll` is five; whatever is not part of
        // the unit goes back, so `1pt x` still leaves the `x` in the document.
        let mut letters = String::new();
        let mut extra = Vec::new();
        while letters.len() < 5 {
            let Some(t) = self.take(lx, pending_only) else {
                break;
            };
            match &t {
                t if t.is_space() && letters.is_empty() => continue,
                Token::Char(c, _) if c.is_ascii_alphabetic() => {
                    letters.push(c.to_ascii_lowercase());
                    extra.push(t);
                }
                other => {
                    lx.push_back(std::slice::from_ref(other));
                    break;
                }
            }
        }
        // Longest match wins, so `filll` is not read as `fil` with two letters
        // left over.
        let mut order = 0;
        let mut taken = 0;
        for n in (2..=letters.len()).rev() {
            let candidate = &letters[..n];
            if let Some(o) = crate::glue::order_of(candidate) {
                order = o;
                taken = n;
                break;
            }
            if n == 2 && self.finite_unit(0, 0, candidate).is_some() {
                taken = 2;
                break;
            }
        }
        if taken == 0 {
            return Err(self.illegal_unit());
        }
        // Letters past the unit were never part of it.
        for t in extra[taken..].iter().rev() {
            lx.push_back(std::slice::from_ref(t));
        }
        let unit = &letters[..taken];
        let sp = match order {
            // An infinite component's number is not converted: `1fil` is one,
            // in the same 65536ths a point uses, at a different order. §455's
            // infinities are the same in mu mode, which is why only the finite
            // branch consults the unit table.
            0 => self
                .finite_unit(int, frac, unit)
                .ok_or_else(|| self.illegal_unit())?,
            _ => int * crate::dimen::UNITY + frac,
        };
        if let Some(t) = self.take(lx, pending_only) {
            if !t.is_space() {
                lx.push_back(std::slice::from_ref(&t));
            }
        }
        Ok((
            (sign * sp).clamp(-crate::dimen::MAX_DIMEN, crate::dimen::MAX_DIMEN),
            order,
        ))
    }

    /// Whether the next tokens spell `word`, consuming them if they do.
    ///
    /// TeX's keyword scan (`tex.web` §407): letters match either case, and
    /// nothing is consumed when the word is not there.
    pub fn scan_keyword(&mut self, lx: &mut Lexer, word: &str, pending_only: bool) -> bool {
        let mut seen = Vec::new();
        for want in word.chars() {
            loop {
                let Some(t) = self.take(lx, pending_only) else {
                    for t in seen.iter().rev() {
                        lx.push_back(std::slice::from_ref(t));
                    }
                    return false;
                };
                if t.is_space() && seen.is_empty() {
                    continue;
                }
                let matched = matches!(&t, Token::Char(c, _)
                    if c.eq_ignore_ascii_case(&want));
                seen.push(t);
                if !matched {
                    for t in seen.iter().rev() {
                        lx.push_back(std::slice::from_ref(t));
                    }
                    return false;
                }
                break;
            }
        }
        true
    }

    /// `\glueexpr ...\relax` — the same expression grammar over glue.
    ///
    /// Addition is componentwise with TeX's order rule (an infinite component
    /// beats a finite one, a higher infinity beats a lower, equal orders add),
    /// and `*` and `/` scale every component. Division rounds, as it does in
    /// `\numexpr`.
    pub fn scan_glue_expr(&mut self, lx: &mut Lexer) -> R<crate::glue::Glue> {
        let v = self.glue_expr_sum(lx)?;
        if let Some(t) = self.take(lx, false) {
            match &t {
                Token::Cs(n) if n.name() == "relax" => {}
                other => lx.push_back(std::slice::from_ref(other)),
            }
        }
        Ok(v)
    }

    fn glue_expr_sum(&mut self, lx: &mut Lexer) -> R<crate::glue::Glue> {
        let mut acc = self.glue_expr_term(lx)?;
        loop {
            match self.expr_operator(lx, false, &['+', '-']) {
                Some('+') => acc = acc + self.glue_expr_term(lx)?,
                Some('-') => acc = acc - self.glue_expr_term(lx)?,
                _ => return Ok(acc),
            }
        }
    }

    fn glue_expr_term(&mut self, lx: &mut Lexer) -> R<crate::glue::Glue> {
        let mut acc = self.glue_expr_factor(lx)?;
        loop {
            match self.expr_operator(lx, false, &['*', '/']) {
                // The multiplier and divisor are integers: a glue times a glue
                // is not a glue.
                Some('*') => acc = acc.scale(self.scan_number(lx, false)?),
                Some('/') => {
                    let by = self.scan_number(lx, false)?;
                    if by == 0 {
                        return Err(TexError("Arithmetic overflow".into()));
                    }
                    acc = acc.divide(by, round_div);
                }
                _ => return Ok(acc),
            }
        }
    }

    fn glue_expr_factor(&mut self, lx: &mut Lexer) -> R<crate::glue::Glue> {
        loop {
            let Some(t) = self.take(lx, false) else {
                return Err(TexError("Missing number, treated as zero".into()));
            };
            match &t {
                t if t.is_space() => continue,
                Token::Char('(', _) => {
                    let v = self.glue_expr_sum(lx)?;
                    match self.take(lx, false) {
                        Some(Token::Char(')', _)) => return Ok(v),
                        _ => return Err(TexError("Missing ) inserted".into())),
                    }
                }
                other => {
                    lx.push_back(std::slice::from_ref(other));
                    let (natural, stretch, stretch_order, shrink, shrink_order) =
                        self.scan_glue(lx)?;
                    return Ok(crate::glue::Glue {
                        natural,
                        stretch,
                        stretch_order,
                        shrink,
                        shrink_order,
                    });
                }
            }
        }
    }

    /// The same, in MATH units: `\muskip0=3mu plus 1mu minus 2mu`.
    ///
    /// One scanner, one mode flag. `tex.web` §461's `scan_glue(mu_val)` is
    /// literally §461's `scan_glue(glue_val)` with `mu` passed down to every
    /// `scan_dimen` inside it, and a second copy here would be a second place
    /// for the `plus`/`minus` grammar to drift.
    pub fn scan_muglue(&mut self, lx: &mut Lexer) -> R<(i64, i64, i64, i64, i64)> {
        self.mu_units = true;
        let got = self.scan_glue(lx);
        self.mu_units = false;
        got
    }

    /// `<dimen> [plus <dimen|fil>] [minus <dimen|fil>]` — a glue.
    pub fn scan_glue(&mut self, lx: &mut Lexer) -> R<(i64, i64, i64, i64, i64)> {
        // `\glueexpr ...\relax` stands where a glue does, and `\muexpr` where a
        // math glue does -- eTeX gives each unit its own expression primitive
        // so that the operands cannot be mixed, and the mode the scanner is in
        // is what says which of the two is the one being read.
        let mu = self.mu_units;
        if let Some(t) = self.take(lx, false) {
            let is_expr = matches!(&t, Token::Cs(n)
                if (mu && n.name() == "muexpr") || (!mu && n.name() == "glueexpr"));
            lx.push_back(std::slice::from_ref(&t));
            if is_expr {
                let _ = self.take(lx, false);
                let g = self.scan_glue_expr(lx)?;
                return Ok((
                    g.natural,
                    g.stretch,
                    g.stretch_order,
                    g.shrink,
                    g.shrink_order,
                ));
            }
        }
        let natural = self.scan_dimen(lx, false)?;
        let (stretch, stretch_order) = match self.scan_keyword(lx, "plus", false) {
            true => self.scan_dimen_or_fil(lx, false)?,
            false => (0, 0),
        };
        let (shrink, shrink_order) = match self.scan_keyword(lx, "minus", false) {
            true => self.scan_dimen_or_fil(lx, false)?,
            false => (0, 0),
        };
        Ok((natural, stretch, stretch_order, shrink, shrink_order))
    }

    /// The same, for a caller that is lowering.
    pub fn scan_dimen_file(&mut self, lx: &mut Lexer) -> R<i64> {
        self.scan_dimen(lx, false)
    }

    /// The control sequence an ACTIVE CHARACTER stands for.
    ///
    /// An active `~` and the control sequence `\~` are different things in TeX
    /// -- `\def~{[a]}\def\~{[b]}` gives `[a][b]`, measured -- so they cannot
    /// share a name. A name the lexer produces is either a run of letters or
    /// exactly one character, so `active:~` is a name no source can spell, and
    /// interning under it keeps the two apart with no second table.
    pub fn active_cs(c: char) -> CsId {
        CsId::intern(&format!("active:{c}"))
    }

    /// The control sequence an active character stands for, if it HAS a
    /// meaning.
    ///
    /// One with no meaning is left alone rather than reported: an undefined
    /// control sequence is not an error in this engine either (see BUGS.md), so
    /// an undefined active character behaves the same way instead of being the
    /// one construct that stops a run.
    pub fn active_meaning(&self, c: char) -> Option<CsId> {
        let id = Self::active_cs(c);
        self.meanings.contains_key(&id).then_some(id)
    }

    /// The token a definition names: a control sequence, or an active
    /// character, which TeX's `get_r_token` accepts in the same position
    /// (`tex.web` §1215).
    fn scan_defined_name(&mut self, lx: &mut Lexer) -> R<CsId> {
        match lx.next_token(&self.cats) {
            Some(Token::Cs(name)) => Ok(name),
            Some(Token::Char(c, Cat::Active)) => Ok(Self::active_cs(c)),
            _ => Err(TexError("Missing control sequence inserted".into())),
        }
    }

    /// The parameter text between a definition's name and its body
    /// (`tex.web` §476), and the left brace of a trailing `#{` if there was one.
    ///
    /// `#{` is the one form where the brace that ends the parameter text is
    /// also a DELIMITER: it goes into the parameter text so the argument stops
    /// there, it opens the body as any brace does, and §473 puts it back on the
    /// end of the body. Nothing else in the scan is special -- the `#` before
    /// it is dropped rather than becoming a match token, which is why
    /// `\def\a#{...}` takes no argument at all while `\def\a#1#{...}` takes one
    /// delimited by the brace.
    fn scan_parameter_text(&mut self, lx: &mut Lexer) -> R<(Vec<Token>, Option<Token>)> {
        let mut params = Vec::new();
        loop {
            let Some(t) = lx.next_token(&self.cats) else {
                return Err(TexError("Runaway definition".into()));
            };
            if matches!(t, Token::Char(_, Cat::BeginGroup)) {
                return Ok((params, None));
            }
            if matches!(t, Token::Char(_, Cat::Param)) {
                let Some(next) = lx.next_token(&self.cats) else {
                    return Err(TexError("Runaway definition".into()));
                };
                if matches!(next, Token::Char(_, Cat::BeginGroup)) {
                    params.push(next);
                    return Ok((params, Some(next)));
                }
                params.push(t);
                params.push(next);
                continue;
            }
            params.push(t);
        }
    }

    fn do_def(&mut self, lx: &mut Lexer, kind: &str) -> R<()> {
        let global = matches!(kind, "gdef" | "xdef") || self.global;
        let expand_body = matches!(kind, "edef" | "xdef");
        let name = self.scan_defined_name(lx)?;
        let (params, hash_brace) = self.scan_parameter_text(lx)?;
        validate_params(&params)?;
        let raw = self.read_balanced(lx)?;
        let mut body = match expand_body {
            true => self.expand_to_tokens(lx, &raw)?,
            false => raw,
        };
        // `tex.web` §473: a parameter text that ended with `#{` appends that
        // left brace to the BODY, which is how the brace tex matched comes
        // back out. `\def\a#{[X]}` called as `\a{Y}` therefore produces
        // `[X]` then `{`, and the document's own `Y}` follows.
        if let Some(brace) = hash_brace {
            body.push(brace);
        }
        let was = std::mem::replace(&mut self.global, global);
        self.set_meaning(name, Meaning::Macro(self.new_macro(params, body)));
        self.global = was;
        // A prefix applies to the definition it precedes and to nothing after
        // it, so it is spent here rather than left to colour the next `\def`.
        self.long = false;
        self.outer = false;
        self.protected = false;
        Ok(())
    }

    /// `\newcommand{\x}{body}`, `\newcommand{\x}[n]{body}`,
    /// `\newcommand{\x}[n][default]{body}`.
    ///
    /// LaTeX writes this in TeX, as a chain of `\ifnum...\def...\else` that
    /// dispatches on the argument count. That chain cannot run here: a `\def`
    /// inside an arm of a run-time conditional is executed while lowering, and
    /// lowering emits BOTH arms, so the losing branch's definition wins
    /// (`tests/cases/def_in_conditional_arm.tex`). Doing the dispatch natively
    /// sidesteps it entirely, and the observable behaviour is the same one
    /// latex.ltx specifies — which is what a port has to preserve, not the
    /// particular macros it was written with.
    ///
    /// The optional-argument form defines a macro whose FIRST parameter has a
    /// default. TeX has no such thing, so it is built the way LaTeX builds it:
    /// the macro takes `n` ordinary parameters and a separate `\\x` is not
    /// created; a call that omits the bracket gets the default substituted.
    fn do_newcommand(&mut self, lx: &mut Lexer, kind: &str) -> R<()> {
        // The name, either bare (`\newcommand\x`) or braced (`\newcommand{\x}`).
        let Some(name) = self.scan_command_name(lx)? else {
            // Nothing definable was found; consume what a definition would have
            // taken so the arguments do not land in the document as text.
            let _ = self.scan_optional_bracket(lx)?;
            let _ = self.scan_optional_bracket(lx)?;
            self.skip_spaces(lx);
            let _ = self.read_group_tokens(lx)?;
            return Ok(());
        };
        if kind == "providecommand" && self.meanings.contains_key(&name) {
            // `\providecommand` leaves an existing definition alone; the body
            // still has to be consumed or it lands in the document as text.
            let _ = self.scan_optional_bracket(lx)?;
            let _ = self.scan_optional_bracket(lx)?;
            self.skip_spaces(lx);
            let _ = self.read_group_tokens(lx)?;
            return Ok(());
        }
        let argc = match self.scan_optional_bracket(lx)? {
            Some(toks) => {
                let text: String = toks.iter().map(|t| t.to_text(self.escape)).collect();
                text.trim().parse::<usize>().unwrap_or(0).min(9)
            }
            None => 0,
        };
        // A second bracket is the default for the first argument.
        let default = self.scan_optional_bracket(lx)?;
        self.skip_spaces(lx);
        let body = self.read_group_tokens(lx)?;

        let mut params = Vec::new();
        for i in 1..=argc {
            params.push(Token::Char('#', Cat::Param));
            params.push(Token::Char(
                char::from_digit(i as u32, 10).unwrap_or('1'),
                Cat::Other,
            ));
        }
        self.set_meaning(name, Meaning::Macro(self.new_macro(params, body)));
        // The default is recorded but not yet honoured: a call that omits the
        // bracket would need the same peek `\@ifnextchar` does, at every use
        // site rather than at the definition. Recorded here so the definition
        // does not silently drop it.
        if let Some(d) = default {
            self.optional_defaults.insert(name, d);
        }
        Ok(())
    }

    /// A command name after `\newcommand` and friends: `\x` or `{\x}`,
    /// either spelling optionally preceded by the star of `\newcommand*`.
    ///
    /// The star asks LaTeX for a command whose arguments may not contain
    /// `\par`. Nothing here reads that restriction, so the star is skipped
    /// rather than refused -- and skipping it is not cosmetic: an unrecognised
    /// star made the scan give up, which DROPPED the definition. That is how
    /// pandoc's `\newcommand*\pandocbounded[1]{...}` left every use of
    /// `\pandocbounded` undefined and stopped the document.
    fn scan_command_name(&mut self, lx: &mut Lexer) -> R<Option<CsId>> {
        let mut braced = false;
        let name = loop {
            let Some(t) = lx.next_token(&self.cats) else {
                return Ok(None);
            };
            match t {
                t if t.is_space() => continue,
                Token::Char('*', _) => continue,
                Token::Char(_, Cat::BeginGroup) => {
                    braced = true;
                    continue;
                }
                Token::Cs(n) => break n,
                // A name that is not a control sequence: `\newcommand` given
                // something it cannot define. LaTeX would raise an error and
                // carry on; refusing the whole document over one definition is
                // the harsher answer, and the rest of the file is still
                // readable. The definition is dropped, not guessed at.
                //
                // The rest of the braced name goes with it. Leaving it in the
                // stream is worse than the error was: the scan that follows
                // takes the NEXT group as the body, which swallows whatever
                // came after the definition.
                _ => {
                    if braced {
                        let mut depth = 1usize;
                        while let Some(t) = lx.next_token(&self.cats) {
                            match t {
                                Token::Char(_, Cat::BeginGroup) => depth += 1,
                                Token::Char(_, Cat::EndGroup) => {
                                    depth -= 1;
                                    if depth == 0 {
                                        break;
                                    }
                                }
                                _ => {}
                            }
                        }
                    }
                    return Ok(None);
                }
            }
        };
        // `{\x}` leaves its closing brace, and a brace left in the stream is a
        // group the document never opened -- it swallowed the definition body
        // and printed as text.
        if braced {
            while let Some(t) = lx.next_token(&self.cats) {
                if matches!(t, Token::Char(_, Cat::EndGroup)) {
                    break;
                }
                if !t.is_space() {
                    lx.push_back(&[t]);
                    break;
                }
            }
        }
        Ok(Some(name))
    }

    /// `[...]` if one is next, leaving the stream untouched when it is not.
    fn scan_optional_bracket(&mut self, lx: &mut Lexer) -> R<Option<Vec<Token>>> {
        let mut skipped = Vec::new();
        loop {
            let Some(t) = lx.next_token(&self.cats) else {
                lx.push_back(&skipped);
                return Ok(None);
            };
            if t.is_space() {
                skipped.push(t);
                continue;
            }
            if !matches!(&t, Token::Char('[', _)) {
                lx.push_back(&[t]);
                return Ok(None);
            }
            let mut inner = Vec::new();
            loop {
                let Some(t) = lx.next_token(&self.cats) else {
                    return Err(TexError("Missing ] inserted".into()));
                };
                if matches!(&t, Token::Char(']', _)) {
                    return Ok(Some(inner));
                }
                inner.push(t);
            }
        }
    }

    fn skip_spaces(&mut self, lx: &mut Lexer) {
        while let Some(t) = lx.next_token(&self.cats) {
            if !t.is_space() {
                lx.push_back(&[t]);
                return;
            }
        }
    }

    /// A `{...}` group's tokens, with the braces removed.
    pub fn read_group_tokens(&mut self, lx: &mut Lexer) -> R<Vec<Token>> {
        loop {
            let Some(t) = lx.next_token(&self.cats) else {
                return Err(TexError("Runaway argument".into()));
            };
            if t.is_space() {
                continue;
            }
            if matches!(t, Token::Char(_, Cat::BeginGroup)) {
                return self.read_balanced(lx);
            }
            // A single token stands in for a group, as TeX's argument scan does.
            return Ok(vec![t]);
        }
    }

    /// `\let\a=\b` — `\a` takes `\b`'s CURRENT meaning, not a reference to it.
    /// `\futurelet\a\b\c` — look one token past the next without eating it.
    ///
    /// `tex.web` §1221: read three tokens, `\let` the first take the meaning of
    /// the THIRD, then put the second and third back so the stream is exactly as
    /// it was. That non-destructive peek is the whole basis of LaTeX's
    /// `\@ifnextchar`, and so of every optional argument in the language --
    /// `\newcommand{\x}[1]{...}` cannot be written without it.
    /// What `name` contributes to a number, if anything.
    ///
    /// The two definitions differ in WHEN the value is known: a `\chardef`
    /// constant is fixed at definition time and can be folded while lowering,
    /// while a `\countdef` name is a register whose value the run may change.
    pub fn numeric_cs(&self, name: CsId) -> Option<NumericCs> {
        match self.meanings.get(&name) {
            Some(Meaning::CharDef(v)) => Some(NumericCs::Value(*v)),
            Some(Meaning::CountDef(r)) => Some(NumericCs::Register(*r)),
            _ => None,
        }
    }

    /// `\chardef\a=65` and `\countdef\pageno=0`, which differ only in what the
    /// number means and in the message tex reports when it is out of range.
    pub fn compile_time_numeric_def(&mut self, lx: &mut Lexer, kind: &str) -> R<()> {
        let Some(Token::Cs(name)) = self.take(lx, false) else {
            return Err(TexError("Missing control sequence inserted".into()));
        };
        self.skip_equals_file(lx)?;
        let mut v = self.scan_number_file(lx)?;
        // Both are limited to 0..255, and tex names the limit differently for
        // each: `! Bad character code (256).` against `! Bad register code
        // (256).`. Measured, and worth keeping apart -- the message is how a
        // document author finds which of the two they got wrong.
        // Each has its own limit and its own message, all measured: a mathchar
        // runs to "7FFF and is reported as `Bad mathchar', while the other two
        // stop at 255 and name the table they overran.
        let (limit, what) = match kind {
            "mathchardef" => (32767, "mathchar"),
            "dimendef" | "skipdef" | "muskipdef" | "toksdef" => (255, "register code"),
            "chardef" => (255, "character code"),
            _ => (255, "register code"),
        };
        // `tex.web` §434's `scan_char_num` and §433's `scan_eight_bit_int` both
        // say "I changed this one to zero": the code is reported, replaced by
        // zero, and the definition is still made. `\chardef\x=256` therefore
        // leaves `\x` meaning `\char0` and the document carries on, which is
        // the whole of TeX's error model in one line.
        if !(0..=limit).contains(&v) {
            self.report(lx, &format!("Bad {what} ({v})"));
            v = 0;
        }
        let meaning = match kind {
            // A mathchar is a constant like a chardef: what differs is the
            // range it may hold, not what it then does.
            "chardef" | "mathchardef" => Meaning::CharDef(v),
            // A dimension register is a register: the name stands for the slot,
            // and the slot is the one the dimensions live in.
            "dimendef" => Meaning::CountDef(crate::compiler::DIMEN_BASE + v),
            // A token register is not a slot: the list lives in the frontend,
            // so the name stands for the register number itself.
            "toksdef" => Meaning::ToksDef(v),
            "skipdef" => {
                Meaning::CountDef(crate::compiler::SKIP_BASE + v * crate::compiler::SKIP_STRIDE)
            }
            // A math glue register is a glue register in the second glue file,
            // so its name stands for a slot exactly as `\skipdef`'s does.
            "muskipdef" => {
                Meaning::CountDef(crate::compiler::MUSKIP_BASE + v * crate::compiler::SKIP_STRIDE)
            }
            _ => Meaning::CountDef(v),
        };
        self.set_meaning(name, meaning);
        Ok(())
    }

    fn do_futurelet(&mut self, lx: &mut Lexer, pending_only: bool) -> R<()> {
        let Some(Token::Cs(name)) = self.take(lx, pending_only) else {
            return Err(TexError("Missing control sequence inserted".into()));
        };
        let Some(first) = self.take(lx, pending_only) else {
            return Err(TexError("Missing token for \\futurelet".into()));
        };
        let Some(second) = self.take(lx, pending_only) else {
            return Err(TexError("Missing token for \\futurelet".into()));
        };
        let meaning = match &second {
            Token::Char(c, k) => Meaning::Char(*c, *k),
            Token::Cs(n) => match self.meanings.get(n) {
                Some(m) => m.clone(),
                None => Meaning::Primitive(*n),
            },
        };
        self.set_meaning(name, meaning);
        // Both tokens go back, in order: the peek must not consume them.
        lx.push_back(&[first, second]);
        Ok(())
    }

    fn do_let(&mut self, lx: &mut Lexer) -> R<()> {
        let name = self.scan_defined_name(lx)?;
        // An optional `=` and one optional space, then the source token.
        let mut src = None;
        while let Some(t) = lx.next_token(&self.cats) {
            match &t {
                t if t.is_space() => continue,
                Token::Char('=', _) => continue,
                other => {
                    src = Some(*other);
                    break;
                }
            }
        }
        let Some(src) = src else {
            return Err(TexError("Missing token for \\let".into()));
        };
        let meaning = match &src {
            Token::Char(c, k) => Meaning::Char(*c, *k),
            Token::Cs(n) => match self.meanings.get(n) {
                Some(m) => m.clone(),
                None => Meaning::Primitive(*n),
            },
        };
        self.set_meaning(name, meaning);
        Ok(())
    }

    fn read_balanced(&mut self, lx: &mut Lexer) -> R<Vec<Token>> {
        let mut depth = 1usize;
        let mut out = Vec::new();
        while let Some(t) = lx.next_token(&self.cats) {
            match &t {
                Token::Char(_, Cat::BeginGroup) => depth += 1,
                Token::Char(_, Cat::EndGroup) => {
                    depth -= 1;
                    if depth == 0 {
                        return Ok(out);
                    }
                }
                _ => {}
            }
            out.push(t);
        }
        Err(TexError("Runaway argument".into()))
    }

    // ── macro calls ──────────────────────────────────────────────────────

    fn expand_macro(&mut self, lx: &mut Lexer, name: CsId, pending_only: bool) -> R<()> {
        let Some(Meaning::Macro(m)) = self.meanings.get(&name).cloned() else {
            return Err(TexError(format!("\\{} is not a macro", name.name())));
        };
        // `\newcommand{\x}[n][default]` gives the FIRST parameter a default, and
        // a call may leave it out: `\includegraphics[width=1in]{f}` passes it,
        // `\includegraphics{f}` takes the default. TeX has no such parameter,
        // so the macro carries n ordinary ones and the bracket is matched here
        // -- which is where LaTeX matches it too, in `\@ifnextchar`.
        let args = match self.optional_defaults.get(&name).cloned() {
            Some(default) => {
                let first = self.read_optional(lx, &default, pending_only)?;
                let mut args = vec![first];
                args.extend(self.match_params(
                    lx,
                    m.params.get(2..).unwrap_or(&[]),
                    pending_only,
                )?);
                args
            }
            None => self.match_params(lx, &m.params, pending_only)?,
        };
        let mut out = Vec::with_capacity(m.body.len());
        let mut i = 0;
        while i < m.body.len() {
            match &m.body[i] {
                Token::Char(_, Cat::Param) => match m.body.get(i + 1) {
                    Some(Token::Char(d, _)) if d.is_ascii_digit() && *d != '0' => {
                        let idx = (*d as u8 - b'1') as usize;
                        if let Some(a) = args.get(idx) {
                            out.extend(a.iter().cloned());
                        }
                        i += 2;
                        continue;
                    }
                    Some(Token::Char(_, Cat::Param)) => {
                        out.push(m.body[i + 1]);
                        i += 2;
                        continue;
                    }
                    _ => out.push(m.body[i]),
                },
                t => out.push(*t),
            }
            i += 1;
        }
        let out = self.weave_advice(name, out)?;
        lx.push_back(&out);
        Ok(())
    }

    /// Wrap `expansion` in whatever advice matches `name`.
    ///
    /// Costs one `is_empty` check when a document registers none, which is
    /// every document that does not use the feature.
    fn weave_advice(&mut self, name: CsId, expansion: Vec<Token>) -> R<Vec<Token>> {
        if self.intercepts.is_empty() || self.advice_depth > 0 {
            return Ok(expansion);
        }
        let advice: Vec<crate::intercepts::Intercept> = self
            .intercepts
            .matching(name.name())
            .into_iter()
            .cloned()
            .collect();
        if advice.is_empty() {
            return Ok(expansion);
        }

        let mut out = expansion;
        for a in advice {
            let body = self.advice_body(&a.handler)?;
            out = match a.advice {
                crate::intercepts::Advice::Before => {
                    let mut v = wrapped(&body);
                    v.extend(out);
                    v
                }
                crate::intercepts::Advice::After => {
                    let mut v = out;
                    v.extend(wrapped(&body));
                    v
                }
                // `\proceed` stands for what the macro would have expanded to.
                // A handler with no `\proceed` replaces the call outright,
                // which is what an around advice that suppresses is for.
                crate::intercepts::Advice::Around => {
                    let mut v = Vec::with_capacity(body.len() + out.len());
                    for t in &body {
                        match t {
                            Token::Cs(n) if n.name() == "proceed" => v.extend(out.iter().copied()),
                            other => v.push(*other),
                        }
                    }
                    wrapped(&v)
                }
            };
        }
        Ok(out)
    }

    /// The body of an advice handler: a macro that takes no parameters.
    ///
    /// A handler with parameters is refused rather than called with whatever
    /// followed the intercepted call, which would silently eat the document's
    /// own tokens.
    fn advice_body(&self, handler: &str) -> R<Vec<Token>> {
        let id = CsId::intern(handler);
        match self.meanings.get(&id) {
            Some(Meaning::Macro(m)) if m.params.is_empty() => Ok(m.body.clone()),
            Some(Meaning::Macro(_)) => Err(TexError(format!(
                "Intercept handler \\{handler} takes parameters; advice handlers take none"
            ))),
            _ => Err(TexError(format!(
                "Intercept handler \\{handler} is not a macro"
            ))),
        }
    }

    fn match_params(
        &mut self,
        lx: &mut Lexer,
        params: &[Token],
        pending_only: bool,
    ) -> R<Vec<Vec<Token>>> {
        let mut args: Vec<Vec<Token>> = Vec::new();
        let mut i = 0;
        while i < params.len() {
            if !matches!(params[i], Token::Char(_, Cat::Param)) {
                let want = params[i];
                let got = self.take(lx, pending_only);
                if got.as_ref() != Some(&want) {
                    return Err(TexError("Use of macro doesn't match its definition".into()));
                }
                i += 1;
                continue;
            }
            let delim: Vec<Token> = params[i + 2..]
                .iter()
                .take_while(|t| !matches!(t, Token::Char(_, Cat::Param)))
                .cloned()
                .collect();
            let arg = match delim.is_empty() {
                true => self.read_undelimited(lx, pending_only)?,
                false => self.read_delimited(lx, &delim, pending_only)?,
            };
            args.push(arg);
            i += 2 + delim.len();
        }
        Ok(args)
    }

    /// The `[...]` of a call to a macro whose first parameter has a default,
    /// or the default itself when the call left the brackets out.
    fn read_optional(
        &mut self,
        lx: &mut Lexer,
        default: &[Token],
        pending_only: bool,
    ) -> R<Vec<Token>> {
        loop {
            let Some(t) = self.take(lx, pending_only) else {
                return Ok(default.to_vec());
            };
            if t.is_space() {
                continue;
            }
            if !matches!(&t, Token::Char('[', _)) {
                lx.push_back(&[t]);
                return Ok(default.to_vec());
            }
            let mut inner = Vec::new();
            loop {
                let Some(t) = self.take(lx, pending_only) else {
                    return Err(TexError("Missing ] inserted".into()));
                };
                if matches!(&t, Token::Char(']', _)) {
                    return Ok(inner);
                }
                inner.push(t);
            }
        }
    }

    fn read_undelimited(&mut self, lx: &mut Lexer, pending_only: bool) -> R<Vec<Token>> {
        loop {
            let Some(t) = self.take(lx, pending_only) else {
                return Err(TexError(
                    "Paragraph ended before argument was complete".into(),
                ));
            };
            if t.is_space() {
                continue;
            }
            return match t {
                Token::Char(_, Cat::BeginGroup) => self.read_balanced_from(lx, pending_only),
                other => Ok(vec![other]),
            };
        }
    }

    /// `read_balanced` for whichever source this context uses.
    fn read_balanced_from(&mut self, lx: &mut Lexer, pending_only: bool) -> R<Vec<Token>> {
        if !pending_only {
            return self.read_balanced(lx);
        }
        let mut depth = 1usize;
        let mut out = Vec::new();
        while let Some(t) = lx.pending.pop() {
            match &t {
                Token::Char(_, Cat::BeginGroup) => depth += 1,
                Token::Char(_, Cat::EndGroup) => {
                    depth -= 1;
                    if depth == 0 {
                        return Ok(out);
                    }
                }
                _ => {}
            }
            out.push(t);
        }
        Err(TexError("Runaway argument".into()))
    }

    fn read_delimited(
        &mut self,
        lx: &mut Lexer,
        delim: &[Token],
        pending_only: bool,
    ) -> R<Vec<Token>> {
        let mut out: Vec<Token> = Vec::new();
        let mut depth = 0usize;
        loop {
            let Some(t) = self.take(lx, pending_only) else {
                return Err(TexError(
                    "Paragraph ended before argument was complete".into(),
                ));
            };
            out.push(t);
            // `tex.web` §392 compares the token against the delimiter BEFORE it
            // touches the brace count, and the order is load-bearing twice: a
            // `{` can then BE the delimiter (the `#{` form), and the `}` that
            // closes a group inside the argument cannot be mistaken for a
            // delimiter `}` because the count is still one deep when it is
            // tested.
            if depth == 0 && out.len() >= delim.len() && out[out.len() - delim.len()..] == *delim {
                out.truncate(out.len() - delim.len());
                let wrapped = out.len() >= 2
                    && matches!(out[0], Token::Char(_, Cat::BeginGroup))
                    && matches!(out[out.len() - 1], Token::Char(_, Cat::EndGroup));
                if wrapped {
                    out.remove(0);
                    out.pop();
                }
                return Ok(out);
            }
            match &t {
                Token::Char(_, Cat::BeginGroup) => depth += 1,
                Token::Char(_, Cat::EndGroup) => depth = depth.saturating_sub(1),
                _ => {}
            }
        }
    }

    // ── assignments ──────────────────────────────────────────────────────

    fn do_catcode(&mut self, lx: &mut Lexer) -> R<()> {
        let ch = self.scan_number(lx, false)?;
        self.skip_equals(lx)?;
        let val = self.scan_number(lx, false)?;
        let (Some(c), Some(cat)) = (char::from_u32(ch as u32), cat_from_i64(val)) else {
            return Err(TexError("Invalid code".into()));
        };
        self.set_cat(c, cat);
        Ok(())
    }

    /// `\mathcode`\x=N` and its three siblings, which read and write exactly as
    /// `\catcode` does and are scoped by a group the same way.
    fn do_charcode(&mut self, lx: &mut Lexer, table: crate::charcodes::Table) -> R<()> {
        let ch = self.scan_number(lx, false)?;
        self.skip_equals(lx)?;
        let val = self.scan_number(lx, false)?;
        let Some(c) = char::from_u32(ch as u32) else {
            return Err(TexError("Invalid code".into()));
        };
        self.save(Save::CharCode(table, c, self.charcodes.get(table, c)));
        self.charcodes
            .set(table, c, val)
            .map_err(|e| TexError(e.to_string()))
    }

    /// The same, for a caller that is lowering rather than expanding.
    pub fn compile_time_charcode(
        &mut self,
        lx: &mut Lexer,
        table: crate::charcodes::Table,
    ) -> R<()> {
        self.do_charcode(lx, table)
    }

    /// What one of the tables says about a character, for `\the`.
    pub fn charcode_value(&mut self, lx: &mut Lexer, table: crate::charcodes::Table) -> R<i64> {
        let ch = self.scan_number(lx, false)?;
        let Some(c) = char::from_u32(ch as u32) else {
            return Err(TexError("Invalid code".into()));
        };
        Ok(self.charcodes.get(table, c))
    }

    fn do_count_assign(&mut self, lx: &mut Lexer) -> R<()> {
        let reg = self.scan_number(lx, false)?;
        self.skip_equals(lx)?;
        let val = self.scan_number(lx, false)?;
        self.set_count(reg, val);
        Ok(())
    }

    fn do_arith(&mut self, lx: &mut Lexer, op: Arith) -> R<()> {
        let Some(Token::Cs(what)) = lx.next_token(&self.cats) else {
            return Err(TexError("You can't use this after \\advance".into()));
        };
        if what.name() != "count" {
            return Err(TexError(format!("Unsupported register \\{}", what.name())));
        }
        let reg = self.scan_number(lx, false)?;
        self.skip_by(lx)?;
        let val = self.scan_number(lx, false)?;
        let cur = *self.count.get(&reg).unwrap_or(&0);
        let next = match op {
            Arith::Add => cur + val,
            Arith::Mul => cur * val,
            Arith::Div => match val {
                0 => return Err(TexError("Arithmetic overflow".into())),
                d => cur / d,
            },
        };
        self.set_count(reg, next);
        Ok(())
    }

    fn skip_by(&mut self, lx: &mut Lexer) -> R<()> {
        while let Some(t) = lx.next_token(&self.cats) {
            if !t.is_space() {
                lx.push_back(&[t]);
                break;
            }
        }
        let save = lx.pending.clone();
        for want in ['b', 'y'] {
            match lx.next_token(&self.cats) {
                Some(Token::Char(c, _)) if c.eq_ignore_ascii_case(&want) => {}
                other => {
                    lx.pending = save;
                    if let Some(t) = other {
                        lx.push_back(&[t]);
                    }
                    return Ok(());
                }
            }
        }
        Ok(())
    }

    fn skip_equals(&mut self, lx: &mut Lexer) -> R<()> {
        while let Some(t) = lx.next_token(&self.cats) {
            match &t {
                t if t.is_space() => continue,
                Token::Char('=', _) => return Ok(()),
                other => {
                    lx.push_back(std::slice::from_ref(other));
                    return Ok(());
                }
            }
        }
        Ok(())
    }

    fn scan_number(&mut self, lx: &mut Lexer, pending_only: bool) -> R<i64> {
        let mut sign = 1i64;
        let mut cur = loop {
            let Some(t) = self.take(lx, pending_only) else {
                return Err(TexError("Missing number, treated as zero".into()));
            };
            match &t {
                t if t.is_space() => continue,
                Token::Char('-', _) => {
                    sign = -sign;
                    continue;
                }
                Token::Char('+', _) => continue,
                other => break *other,
            }
        };
        if matches!(cur, Token::Char('`', _)) {
            let Some(t) = self.take(lx, pending_only) else {
                return Err(TexError("Missing number".into()));
            };
            let code = match t {
                Token::Char(c, _) => u32::from(c) as i64,
                Token::Cs(n) => n
                    .name()
                    .chars()
                    .next()
                    .map(|c| u32::from(c) as i64)
                    .unwrap_or(0),
            };
            return Ok(sign * code);
        }
        if let Token::Cs(name) = &cur {
            let name = *name;
            // `\numexpr ...\relax` in numeric position.
            if name.name() == "numexpr" {
                return Ok(sign * self.scan_expr(lx, pending_only, false)?);
            }
            if name.name() == "count" {
                let reg = self.scan_number(lx, pending_only)?;
                return Ok(sign * *self.count.get(&reg).unwrap_or(&0));
            }
            // A `\chardef` constant IS a number here, and a `\countdef` name is
            // the register it stands for -- which is the whole reason plain.tex
            // can write `\catcode`\~=\active`.
            match self.numeric_cs(name) {
                Some(NumericCs::Value(v)) => return Ok(sign * v),
                Some(NumericCs::Register(r)) => {
                    return Ok(sign * *self.count.get(&r).unwrap_or(&0));
                }
                None => {}
            }
            // A macro in numeric position expands and the scan resumes.
            if self.try_expand(lx, name, pending_only)? {
                return Ok(sign * self.scan_number(lx, pending_only)?);
            }
            return Err(TexError(format!("Missing number, found \\{}", name.name())));
        }
        // A constant may be octal or hexadecimal as well as decimal
        // (tex.web §445). The hex digits are UPPERCASE -- the opposite of `^^`
        // notation, which takes lowercase -- so `"FF` is 255 and `"ff` is an
        // error. Measured against tex -ini, not assumed from the symmetry.
        let radix = match &cur {
            Token::Char('\'', _) => Some(8u32),
            Token::Char('"', _) => Some(16u32),
            _ => None,
        };
        if let Some(radix) = radix {
            let ok = |c: char| match radix {
                8 => ('0'..='7').contains(&c),
                _ => c.is_ascii_digit() || ('A'..='F').contains(&c),
            };
            let mut value = 0i64;
            let mut any = false;
            let mut ok_so_far = true;
            while let Some(t) = self.take(lx, pending_only) {
                match &t {
                    Token::Char(c, _) if ok(*c) => {
                        let d = i64::from(c.to_digit(16).unwrap_or(0));
                        value = self.fold_digit(lx, value, d, i64::from(radix), &mut ok_so_far);
                        any = true;
                    }
                    other if other.is_space() && any => break,
                    other => {
                        lx.push_back(std::slice::from_ref(other));
                        break;
                    }
                }
            }
            if !any {
                return Err(TexError("Missing number, treated as zero".into()));
            }
            return Ok(sign * value);
        }
        let mut value = 0i64;
        let mut any = false;
        let mut ok_so_far = true;
        loop {
            match &cur {
                Token::Char(c, _) if c.is_ascii_digit() => {
                    let d = i64::from(c.to_digit(10).unwrap_or(0));
                    value = self.fold_digit(lx, value, d, 10, &mut ok_so_far);
                    any = true;
                }
                // A constant is terminated by ONE optional space, which is
                // ABSORBED (tex.web §444) -- it delimits the number and is not
                // part of what follows. Pushing it back put it in the text, so
                // `\ifnum\count0>3 BIG` rendered as " BIG".
                other if other.is_space() && any => break,
                other => {
                    lx.push_back(std::slice::from_ref(other));
                    break;
                }
            }
            match self.take(lx, pending_only) {
                Some(t) => cur = t,
                None => break,
            }
        }
        if !any {
            return Err(TexError("Missing number, treated as zero".into()));
        }
        Ok(sign * value)
    }

    /// Fold one digit into a constant being scanned — `tex.web` §445's
    /// "Accumulate the constant until `cur_tok` is not a suitable digit".
    ///
    /// The limit is TeX's `infinity` (2147483647), not the host integer's, and
    /// the test is made BEFORE the digit is folded in: `m` is the largest value
    /// that can still take one, and at `m` exactly only a digit above 7
    /// overflows (a radix other than ten has no such slack, which is the
    /// `radix<>10` arm). Deciding it per digit rather than by parsing the whole
    /// run is what puts the report at the right place -- tex's context display
    /// for `\count1=99999999999` shows ten nines read and the eleventh still to
    /// come, because that is the digit the overflow was found on.
    ///
    /// Reported and clamped, not raised: §445 calls `error` and sets
    /// `cur_val:=infinity`, then keeps scanning with `OK_so_far` false so the
    /// remaining digits are eaten in silence. The magnitude is tested before
    /// the sign is applied, which is why tex answers -2147483647 (not
    /// -2147483648) for a too-big negative.
    fn fold_digit(
        &mut self,
        lx: &Lexer,
        value: i64,
        d: i64,
        radix: i64,
        ok_so_far: &mut bool,
    ) -> i64 {
        const INFINITY: i64 = 2147483647;
        let m = INFINITY / radix;
        if value >= m && (value > m || d > 7 || radix != 10) {
            if *ok_so_far {
                self.report(lx, "Number too big");
                *ok_so_far = false;
            }
            return INFINITY;
        }
        value * radix + d
    }

    // ── text production ──────────────────────────────────────────────────

    fn read_group_text(&mut self, lx: &mut Lexer) -> R<String> {
        loop {
            let Some(t) = lx.next_token(&self.cats) else {
                return Err(TexError("Missing { inserted".into()));
            };
            if t.is_space() {
                continue;
            }
            if !matches!(t, Token::Char(_, Cat::BeginGroup)) {
                return Err(TexError("Missing { inserted".into()));
            }
            break;
        }
        let body = self.read_balanced(lx)?;
        self.expand_to_text(lx, &body)
    }

    /// Fully expand a token list to the tokens it produces.
    /// Expand the MACRO calls in `toks` and nothing else.
    ///
    /// `\edef` expands its body at definition time, but texrs cannot simply
    /// expand everything: `\the\count<n>` has to survive as tokens so the
    /// caller can snapshot the register into a scratch one, because a count
    /// lives in a VM slot at run time while this table only knows what was
    /// assigned while lowering. So macros expand here and `\the`, the
    /// conditionals and the primitives are left exactly as they were.
    ///
    /// A `\protected` macro is left alone too -- that is what the prefix is
    /// for, and it is the only thing that makes it observable.
    pub fn expand_macros_only(&mut self, toks: &[Token]) -> R<Vec<Token>> {
        let mut work = Lexer::new("");
        work.push_back(toks);
        let mut out = Vec::new();
        let mut steps = 0usize;
        while let Some(t) = work.pending.pop() {
            steps += 1;
            if steps > 200_000 {
                return Err(TexError("TeX capacity exceeded".into()));
            }
            match &t {
                // `\unexpanded{...}` is the one thing that stops this pass:
                // its group goes into the body as tokens, so a macro inside it
                // is called when the body runs rather than now.
                Token::Cs(name) if name.name() == "unexpanded" => {
                    let group = self.read_group_tokens(&mut work)?;
                    out.extend(group);
                }
                // `\expanded{...}` is the opposite and needs no special case
                // beyond dropping the wrapper: everything in the group is
                // expanded because everything here is.
                Token::Cs(name) if name.name() == "expanded" => {
                    let group = self.read_group_tokens(&mut work)?;
                    work.push_back(&group);
                }
                Token::Cs(name) => {
                    let name = *name;
                    let expandable = matches!(
                        self.meanings.get(&name),
                        Some(Meaning::Macro(m)) if !m.protected
                    );
                    match expandable {
                        true => self.expand_macro(&mut work, name, true)?,
                        false => out.push(t),
                    }
                }
                _ => out.push(t),
            }
        }
        Ok(out)
    }

    fn expand_to_tokens(&mut self, lx: &mut Lexer, toks: &[Token]) -> R<Vec<Token>> {
        let saved: Vec<Token> = std::mem::take(&mut lx.pending);
        lx.push_back(toks);
        let mut out = Vec::new();
        let mut steps = 0usize;
        while let Some(t) = lx.pending.pop() {
            steps += 1;
            if steps > 200_000 {
                return Err(TexError("TeX capacity exceeded".into()));
            }
            match &t {
                Token::Cs(name) => {
                    let name = *name;
                    // A `\protected` macro is NOT expanded here: that is the
                    // whole point of the prefix. It goes into the body as
                    // itself and runs when the body does, so redefining it
                    // afterwards changes what the \edef'd macro produces.
                    let protected = matches!(
                        self.meanings.get(&name),
                        Some(Meaning::Macro(m)) if m.protected
                    );
                    if protected || !self.try_expand(lx, name, true)? {
                        out.push(t);
                    }
                }
                _ => out.push(t),
            }
        }
        lx.pending = saved;
        Ok(out)
    }

    /// `tex.web` §366's `scan_toks(macro_def, xpand)`: expand an `\edef` body
    /// the whole way, so what gets DEFINED is the token run the expansion
    /// produced rather than the recipe for producing it.
    ///
    /// Two things follow from that and neither is optional. A conditional in
    /// the body is decided HERE -- `\edef\a{\ifcase\count1 ZERO\else OTHER\fi}`
    /// freezes to `ZERO` when `\count1` is 0, and a later `\count1=5` cannot
    /// move it. And `\the` produces §478's CHARACTERS, so two bodies that
    /// froze to the same run compare equal under `\ifx`, which they cannot do
    /// while one of them still holds the conditional.
    ///
    /// The caller decides when this may be used: the registers read have to be
    /// ones whose values the lowerer can prove, because a compiled engine holds
    /// them in VM slots and cannot read one whose value depends on the run.
    pub fn expand_edef_body(&mut self, toks: &[Token]) -> R<Vec<Token>> {
        let mut lx = Lexer::new("");
        lx.push_back(toks);
        let mut out = Vec::new();
        let mut steps = 0usize;
        while let Some(t) = lx.pending.pop() {
            steps += 1;
            if steps > 200_000 {
                return Err(TexError("TeX capacity exceeded".into()));
            }
            let Token::Cs(name) = &t else {
                out.push(t);
                continue;
            };
            let name = *name;
            // `\unexpanded{...}` is the one thing that stops this pass: its
            // group goes into the body AS TOKENS, so a macro inside it is
            // called when the body runs rather than now. `\expanded{...}` is
            // the opposite and needs no more than the wrapper coming off,
            // because everything here is expanded anyway.
            if name.name() == "unexpanded" {
                let group = self.read_group_tokens(&mut lx)?;
                out.extend(group);
                continue;
            }
            if name.name() == "expanded" {
                let group = self.read_group_tokens(&mut lx)?;
                lx.push_back(&group);
                continue;
            }
            // §478's `the_toks`, which is what `\the` means inside an \edef:
            // the value as characters, not the reading it stands for.
            if name.name() == "the" || name.name() == "number" {
                let text = self.read_the(&mut lx, name.name() == "number")?;
                out.extend(text.chars().map(|c| Token::Char(c, Cat::Other)));
                continue;
            }
            // §366 does not expand a `\protected` macro, which is the whole
            // point of the prefix: it survives as itself and runs when the
            // body does.
            let protected = matches!(
                self.meanings.get(&name),
                Some(Meaning::Macro(m)) if m.protected
            );
            if protected || !self.try_expand(&mut lx, name, true)? {
                out.push(t);
            }
        }
        Ok(out)
    }

    /// Fully expand a token list and render it, for `\message`.
    fn expand_to_text(&mut self, lx: &mut Lexer, toks: &[Token]) -> R<String> {
        let saved: Vec<Token> = std::mem::take(&mut lx.pending);
        lx.push_back(toks);
        let mut out = String::new();
        let mut steps = 0usize;
        while let Some(t) = lx.pending.pop() {
            steps += 1;
            if steps > 200_000 {
                return Err(TexError("TeX capacity exceeded".into()));
            }
            match &t {
                Token::Cs(name) if name.name() == "the" || name.name() == "number" => {
                    let n = self.read_the(lx, name.name() == "number")?;
                    out.push_str(&n);
                }
                Token::Cs(name) if name.name() == "string" => {
                    // `\string` is `sprint_cs` (tex.web §262), NOT `print_cs`:
                    // no trailing space after a multi-letter name.
                    if let Some(next) = lx.pending.pop() {
                        out.push_str(&match &next {
                            Token::Cs(n) => format!("{}{}", self.escape, n.name()),
                            other => other.to_text(self.escape),
                        });
                    }
                }
                Token::Cs(name) => {
                    let name = *name;
                    if !self.try_expand(lx, name, true)? {
                        out.push_str(&t.to_text(self.escape));
                    }
                }
                other => out.push_str(&other.to_text(self.escape)),
            }
        }
        lx.pending = saved;
        Ok(out)
    }

    /// `\the\count<n>`, and `\number<n>` which takes a bare number.
    fn read_the(&mut self, lx: &mut Lexer, bare: bool) -> R<String> {
        if bare {
            return Ok(self.scan_number(lx, true)?.to_string());
        }
        let Some(Token::Cs(what)) = lx.pending.pop() else {
            return Err(TexError("You can't use \\the here".into()));
        };
        if what.name() != "count" {
            return Err(TexError(format!("Unsupported \\the\\{}", what.name())));
        }
        let reg = self.scan_number(lx, true)?;
        Ok(self.count.get(&reg).unwrap_or(&0).to_string())
    }

    fn read_csname(&mut self, lx: &mut Lexer, pending_only: bool) -> R<String> {
        let mut name = String::new();
        loop {
            let Some(t) = self.take(lx, pending_only) else {
                return Err(TexError("Missing \\endcsname inserted".into()));
            };
            match &t {
                Token::Cs(n) if n.name() == "endcsname" => return Ok(name),
                Token::Char(c, _) => name.push(*c),
                Token::Cs(n) => {
                    let n = *n;
                    if !self.try_expand(lx, n, pending_only)? {
                        return Err(TexError(format!(
                            "Missing \\endcsname before \\{}",
                            n.name()
                        )));
                    }
                }
            }
        }
    }
}

enum Arith {
    Add,
    Mul,
    Div,
}

impl Default for Engine {
    fn default() -> Self {
        Self::new()
    }
}

/// The frontend surface `crate::lower` drives.
///
/// Lowering needs the expander's compile-time half — the macro table, the
/// catcode table, and the scanners — without its executor. These are thin,
/// deliberately named wrappers so the lowering pass reads as a compiler rather
/// than as a second interpreter reaching into private state.
impl Engine {
    /// `\def`/`\gdef` at compile time: it changes how the rest of the file reads.
    pub fn compile_time_def(&mut self, lx: &mut Lexer, kind: &str) -> R<()> {
        self.do_def(lx, kind)
    }

    /// `\catcode` at compile time, for the same reason.
    pub fn compile_time_catcode(&mut self, lx: &mut Lexer) -> R<()> {
        self.do_catcode(lx)
    }

    /// Skip the arm of a conditional the frontend decided against, the way
    /// TeX's `\if` skips: tokens are read and thrown away, nested conditionals
    /// counted, and nothing in them expands or assigns.
    ///
    /// Answers `true` when it stopped at an `\else` and `false` at the `\fi`;
    /// either way the token it stopped on is consumed.
    pub fn compile_time_skip_arm(&mut self, lx: &mut Lexer, stop_at_else: bool) -> R<bool> {
        self.skip_to(lx, stop_at_else, false)
    }

    pub fn scan_number_file(&mut self, lx: &mut Lexer) -> R<i64> {
        self.scan_number(lx, false)
    }

    pub fn scan_number_pending(&mut self, lx: &mut Lexer) -> R<i64> {
        self.scan_number(lx, true)
    }

    pub fn skip_equals_file(&mut self, lx: &mut Lexer) -> R<()> {
        self.skip_equals(lx)
    }

    pub fn skip_by_file(&mut self, lx: &mut Lexer) -> R<()> {
        self.skip_by(lx)
    }

    pub fn read_relation_file(&mut self, lx: &mut Lexer) -> R<char> {
        self.read_relation(lx, false)
    }

    pub fn expand_macro_file(&mut self, lx: &mut Lexer, name: CsId) -> R<()> {
        self.expand_macro(lx, name, false)
    }

    /// Try to expand `name` as an EXPANDABLE primitive in running text.
    ///
    /// Returns whether it was one. `\expandafter`, `\csname`, `\noexpand` and
    /// the conditionals are expandable: `tex.web` §366 has the expander handle
    /// them wherever they appear, including at the outermost level of a file.
    /// The lowerer dispatches top-level control sequences itself and so had no
    /// arm for them, which made `\expandafter\def\csname foo\endcsname{...}`
    /// -- the idiom LaTeX's own `\newcommand` is built out of -- an undefined
    /// control sequence at the top of a document while working perfectly inside
    /// a macro body. This is the door back into the expander for that case.
    pub fn expand_in_text(&mut self, lx: &mut Lexer, name: CsId) -> R<bool> {
        self.try_expand(lx, name, false)
    }

    pub fn expand_macro_pending(&mut self, lx: &mut Lexer, name: CsId) -> R<()> {
        self.expand_macro(lx, name, true)
    }

    /// One expansion step inside a token list, over the pending list alone.
    ///
    /// `tex.web` §366's `expand` does not care that the token is a macro:
    /// `\expandafter\A\B` expands `\B` whatever `\B` is, so a second
    /// `\expandafter`, a `\csname` or a `\string` behind the held token has to
    /// run here too. Returns whether anything was expanded.
    pub fn expand_pending(&mut self, lx: &mut Lexer, name: CsId) -> R<bool> {
        self.try_expand(lx, name, true)
    }

    /// Whether `name` is a conditional primitive (`tex.web` §487's list).
    ///
    /// The lowerer owns the conditionals inside a `\message` body -- they
    /// become run-time branches over registers the VM holds, not a decision
    /// taken now -- so it has to be able to keep them away from the expander's
    /// own immediate evaluation.
    pub fn is_conditional(name: CsId) -> bool {
        CONDITIONALS.contains(&name.name()) || matches!(name.name(), "else" | "or" | "fi")
    }

    /// Read `{...}` after `\message`, unexpanded — the pieces are split by the
    /// lowering pass, which has to keep `\the` as a run-time read.
    pub fn read_message_body(&mut self, lx: &mut Lexer) -> R<Vec<Token>> {
        loop {
            let Some(t) = lx.next_token(&self.cats) else {
                return Err(TexError("Missing { inserted".into()));
            };
            if t.is_space() {
                continue;
            }
            if !matches!(t, Token::Char(_, Cat::BeginGroup)) {
                return Err(TexError("Missing { inserted".into()));
            }
            break;
        }
        self.read_balanced(lx)
    }
}

/// Compile-time control the lowering pass needs: grouping and `\let`, both of
/// which act on the macro table and so belong to the frontend, not the VM.
impl Engine {
    /// `\futurelet` while lowering: the peek it performs is a frontend fact,
    /// exactly as `\let` is.
    pub fn compile_time_futurelet(&mut self, lx: &mut Lexer) -> R<()> {
        self.do_futurelet(lx, false)
    }

    /// `\newcommand` and friends while lowering, exactly as `\def` is: a macro
    /// definition is a frontend fact.
    pub fn compile_time_newcommand(&mut self, lx: &mut Lexer, kind: &str) -> R<()> {
        self.do_newcommand(lx, kind)
    }

    /// Consume a LaTeX preamble directive that takes `[options]{arguments}`,
    /// and return what it said.
    ///
    /// `\documentclass`, `\usepackage` and `\PassOptionsToPackage` load files
    /// texrs has no way to run -- a package is TeX that builds boxes, and there
    /// is no stomach to build them in. Consuming the arguments rather than
    /// failing on them lets the REST of a document be read, which is the
    /// difference between "cannot open this file at all" and "read it, minus
    /// what the packages would have drawn".
    ///
    /// The options and the argument names come back rather than being dropped
    /// on the floor, because some of what a preamble says needs no package to
    /// honour: `[11pt]` is a type size and `[margin=0.95in]{geometry}` is a
    /// page, and both are numbers the typesetter can simply use. Discarding
    /// them set every book on plain.tex's page.
    pub fn compile_time_preamble_directive(
        &mut self,
        lx: &mut Lexer,
        args: usize,
    ) -> R<(String, Vec<String>)> {
        let options = match self.scan_optional_bracket(lx)? {
            Some(toks) => toks.iter().map(|t| t.to_text(self.escape)).collect(),
            None => String::new(),
        };
        let mut names = Vec::with_capacity(args);
        for _ in 0..args {
            self.skip_spaces(lx);
            let toks = self.read_group_tokens(lx)?;
            names.push(toks.iter().map(|t| t.to_text(self.escape)).collect());
        }
        Ok((options, names))
    }

    /// `\makeatletter` / `\makeatother`: @ becomes a letter, or stops being
    /// one. LaTeX's internal names are only spellable while it is.
    pub fn compile_time_set_at_letter(&mut self, on: bool) {
        let cat = match on {
            true => Cat::Letter,
            false => Cat::Other,
        };
        self.set_cat('@', cat);
    }

    /// `[...]` if one is next, for a caller outside the expander.
    pub fn read_optional_bracket(&mut self, lx: &mut Lexer) -> R<Option<Vec<Token>>> {
        self.scan_optional_bracket(lx)
    }

    /// Consume a `*` if the next thing is one, for the starred form of a
    /// sectioning command.
    ///
    /// `\chapter*{Preface}` is the unnumbered chapter, and it is one token
    /// different from `\chapter{Preface}`. Left unread, the `*` becomes the
    /// first character of the heading.
    pub fn skip_optional_star(&mut self, lx: &mut Lexer) -> bool {
        let mut skipped = Vec::new();
        loop {
            let Some(t) = lx.next_token(&self.cats) else {
                lx.push_back(&skipped);
                return false;
            };
            if t.is_space() {
                skipped.push(t);
                continue;
            }
            if matches!(&t, Token::Char('*', _)) {
                return true;
            }
            lx.push_back(&[t]);
            lx.push_back(&skipped);
            return false;
        }
    }

    /// A `{...}` group's text, for a caller outside the expander.
    pub fn read_group_text_pub(&mut self, lx: &mut Lexer) -> R<String> {
        let toks = self.read_group_tokens(lx)?;
        Ok(toks.iter().map(|t| t.to_text(self.escape)).collect())
    }

    /// A `{...}` group's tokens, unexpanded.
    pub fn read_balanced_group(&mut self, lx: &mut Lexer) -> R<Vec<Token>> {
        self.read_group_tokens(lx)
    }

    pub fn compile_time_let(&mut self, lx: &mut Lexer) -> R<()> {
        self.do_let(lx)
    }

    /// Consume an advice marker, if `name` is one.
    ///
    /// The markers travel in the token stream, so every walker that reads
    /// tokens has to know them — the expander's own dispatch, and the message
    /// walker in `lower.rs`, which would otherwise render one as text.
    pub fn advice_marker(&mut self, name: &str) -> bool {
        match name {
            ADVICE_IN => {
                self.advice_depth += 1;
                true
            }
            ADVICE_OUT => {
                self.advice_depth = self.advice_depth.saturating_sub(1);
                true
            }
            _ => false,
        }
    }

    /// `\intercept{<kind>}{<pattern>}{\handler}` — register advice.
    ///
    /// At COMPILE time, like `\def`: advice changes what the macros AFTER it
    /// expand to, so a registration read at run time would be a registration
    /// that never fired. Scoped to the enclosing group, like any other
    /// assignment.
    pub fn compile_time_intercept(&mut self, lx: &mut Lexer) -> R<()> {
        let kind = self.group_text(lx)?;
        let advice = crate::intercepts::Advice::parse(&kind).ok_or_else(|| {
            TexError(format!(
                "Unknown intercept kind `{kind}'; use before, after or around"
            ))
        })?;
        let pattern = self.group_text(lx)?;
        let handler = self.group_cs_name(lx)?;
        if let Some(frame) = self.groups.last_mut() {
            frame.push(Save::Intercepts(self.intercepts.clone()));
        }
        self.intercepts
            .register(&pattern, advice, &handler)
            .map_err(TexError)
    }

    /// The characters of the next brace group, spaces and all.
    fn group_text(&mut self, lx: &mut Lexer) -> R<String> {
        let toks = self.next_group(lx)?;
        Ok(toks
            .iter()
            .filter_map(|t| match t {
                Token::Char(c, _) => Some(*c),
                Token::Cs(_) => None,
            })
            .collect())
    }

    /// The name of the single control sequence in the next brace group.
    fn group_cs_name(&mut self, lx: &mut Lexer) -> R<String> {
        let toks = self.next_group(lx)?;
        match toks.iter().find(|t| matches!(t, Token::Cs(_))) {
            Some(Token::Cs(n)) => Ok(n.name().to_string()),
            _ => Err(TexError(
                "Intercept handler must be a control sequence, as in {\\handler}".into(),
            )),
        }
    }

    /// Skip to the next `{` and read the group it opens.
    fn next_group(&mut self, lx: &mut Lexer) -> R<Vec<Token>> {
        while let Some(t) = lx.next_token(&self.cats) {
            match &t {
                _ if t.is_space() => continue,
                Token::Char(_, Cat::BeginGroup) => return self.read_balanced(lx),
                _ => return Err(TexError("Missing { for \\intercept".into())),
            }
        }
        Err(TexError("Runaway \\intercept: missing {".into()))
    }
    pub fn compile_time_begin_group(&mut self) {
        self.begin_group();
    }
    pub fn compile_time_end_group(&mut self) -> R<()> {
        self.end_group()
    }
    /// A macro carrying whichever definition prefixes are in force.
    fn new_macro(&self, params: Vec<Token>, body: Vec<Token>) -> Macro {
        Macro {
            params,
            body,
            long: self.long,
            outer: self.outer,
            protected: self.protected,
        }
    }

    /// `\long`, for a caller that is lowering rather than expanding.
    pub fn set_long_prefix(&mut self, on: bool) {
        self.long = on;
    }

    /// `\outer`, likewise.
    pub fn set_outer_prefix(&mut self, on: bool) {
        self.outer = on;
    }

    /// `\protected`, likewise.
    pub fn set_protected_prefix(&mut self, on: bool) {
        self.protected = on;
    }

    pub fn set_global_prefix(&mut self, on: bool) {
        self.global = on;
    }

    /// Whether a `\global` prefix is in force, SPENDING it.
    ///
    /// A prefix belongs to the assignment it precedes and to nothing after it
    /// (`tex.web` §1211's `prefixed_command`), so the register arms of the
    /// lowerer read it through here rather than leaving it set to colour the
    /// next assignment as well.
    pub fn take_global_prefix(&mut self) -> bool {
        std::mem::take(&mut self.global)
    }
    /// `\ifx` equality over the CURRENT meanings — decidable while lowering,
    /// because a macro's meaning is a frontend fact and not VM state.
    pub fn ifx_equal(&mut self, lx: &mut Lexer) -> R<bool> {
        let a = lx.next_token(&self.cats);
        let b = lx.next_token(&self.cats);
        Ok(self.meanings_equal(a.as_ref(), b.as_ref()))
    }
    pub fn take_file(&mut self, lx: &mut Lexer) -> Option<Token> {
        lx.next_token(&self.cats)
    }

    /// One token from whichever source the caller is reading, so a scanner the
    /// lowerer runs in BOTH contexts -- a file and a `\message` body -- needs
    /// one copy rather than two that can drift.
    pub fn take_any(&mut self, lx: &mut Lexer, pending_only: bool) -> Option<Token> {
        self.take(lx, pending_only)
    }

    pub fn scan_number_any(&mut self, lx: &mut Lexer, pending_only: bool) -> R<i64> {
        self.scan_number(lx, pending_only)
    }

    pub fn scan_dimen_any(&mut self, lx: &mut Lexer, pending_only: bool) -> R<i64> {
        self.scan_dimen(lx, pending_only)
    }

    pub fn read_relation_any(&mut self, lx: &mut Lexer, pending_only: bool) -> R<char> {
        self.read_relation(lx, pending_only)
    }
}

/// More frontend surface for the lowering pass.
impl Engine {
    /// Arm `\unless` for the next conditional, or read and clear it.
    ///
    /// The lowerer builds the run-time conditionals itself, so it needs to
    /// spend the same flag `do_conditional` spends for the ones it settles.
    pub fn set_unless(&mut self, on: bool) {
        self.unless = on;
    }
    pub fn take_unless(&mut self) -> bool {
        std::mem::take(&mut self.unless)
    }
    pub fn is_macro(&self, name: CsId) -> bool {
        matches!(self.meanings.get(&name), Some(Meaning::Macro(_)))
    }
    pub fn read_balanced_pub(&mut self, lx: &mut Lexer) -> R<Vec<Token>> {
        self.read_balanced(lx)
    }
    pub fn read_csname_pending(&mut self, lx: &mut Lexer) -> R<String> {
        self.read_csname(lx, true)
    }
    pub fn read_relation_pending(&mut self, lx: &mut Lexer) -> R<char> {
        self.read_relation(lx, true)
    }
    pub fn meanings_equal_pub(&self, a: Option<&Token>, b: Option<&Token>) -> bool {
        self.meanings_equal(a, b)
    }
    /// Define a macro with no parameters, for `\edef`'s rewritten body.
    pub fn define_macro(&mut self, name: CsId, body: Vec<Token>) {
        self.set_meaning(name, Meaning::Macro(self.new_macro(Vec::new(), body)));
    }

    /// The same, with a parameter text — validated as `\def`'s is.
    ///
    /// `\edef` takes parameters exactly as `\def` does; what differs is only
    /// when the BODY is expanded. A definition path that dropped them would
    /// leave `\edef\pair#1,#2.{…}` matching nothing and its delimiters landing
    /// in the output.
    pub fn define_macro_with_params(
        &mut self,
        name: CsId,
        params: Vec<Token>,
        body: Vec<Token>,
    ) -> R<()> {
        validate_params(&params)?;
        self.set_meaning(name, Meaning::Macro(self.new_macro(params, body)));
        Ok(())
    }
}

/// Check a macro's parameter text the way `tex.web` §476 does.
///
/// Every `#` must be followed by a digit, and the digits must run 1, 2, 3 ... in
/// order. TeX has one exception -- `#{`, a parameter delimited by the left brace
/// -- which this milestone does not implement and therefore refuses rather than
/// mis-parses.
///
/// Without this the argument reader walks off the end of the parameter list on a
/// trailing `#`: `\def\a#{...}` panicked with `range start index 2 out of range`
/// (found by `cargo fuzz run lower`).
fn validate_params(params: &[Token]) -> R<()> {
    let mut expect = b'1';
    let mut i = 0;
    while i < params.len() {
        if !matches!(params[i], Token::Char(_, Cat::Param)) {
            i += 1;
            continue;
        }
        match params.get(i + 1) {
            Some(Token::Char(c, _)) if *c as u8 == expect => {
                expect += 1;
                i += 2;
            }
            Some(Token::Char(c, _)) if c.is_ascii_digit() => {
                return Err(TexError("Parameters must be numbered consecutively".into()))
            }
            // `#` last in the parameter text is TeX's `#{` form.
            None => return Err(TexError("`#{` parameter text is not implemented".into())),
            _ => return Err(TexError("Illegal parameter number in definition".into())),
        }
    }
    Ok(())
}