texrs 0.6.8

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
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
//! 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 rustc_hash::FxHashMap;
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;

thread_local! {
    /// ยง32's `term_in` for this thread's run: the lines an embedder attached
    /// with [`with_terminal`], or `None` for the CLI, which has no terminal to
    /// read (see [`Engine::interaction`]).
    static TERMINAL: RefCell<Option<VecDeque<String>>> = const { RefCell::new(None) };
}

/// Run `f` with `input` as the terminal, line by line: what `\read16`,
/// `\read-1` and a `\read` from any closed stream take (ยง484). A run that
/// starts with a terminal starts in scroll mode, so those reads are allowed;
/// errors still never stop to ask.
pub fn with_terminal<R>(input: &str, f: impl FnOnce() -> R) -> R {
    let lines = input.lines().map(str::to_string).collect();
    let was = TERMINAL.with(|t| t.replace(Some(lines)));
    let r = f();
    TERMINAL.with(|t| t.replace(was));
    r
}

/// Whether [`with_terminal`] attached a terminal to this thread.
fn has_terminal() -> bool {
    TERMINAL.with(|t| t.borrow().is_some())
}

/// The token a list keeps for one read from the stream: ยง358's `dont_expand`
/// marker lives only in the stream, so a `\noexpand`ed control sequence is
/// itself again once something stores it.
fn unmarked(t: Token) -> Token {
    match t {
        Token::Cs(id) => Token::Cs(id.noexpand_origin().unwrap_or(id)),
        other => other,
    }
}

/// 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 {
    /// Shared, because a call reads the definition while it expands and the
    /// table can change under it: holding the definition by count is what a
    /// call costs instead of a copy of its parameter text and body.
    Macro(Rc<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),
    /// `\mathchardef\a="7123` -- a math character code. A number wherever
    /// one is scanned, like a `\chardef`; a different command for `\meaning`
    /// (ยง1295 prints `\mathchar"7123`) and for `\ifx`.
    MathCharDef(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),
    /// `\font\tenrm=cmr10` -- a font identifier (ยง1257's `set_font`), by
    /// internal font number. `\meaning` prints `select font cmr10` (ยง1261).
    Font(u16),
    /// `\attributedef\a=5` -- another name for LuaTeX's attribute register 5.
    AttributeDef(i64),
}

/// An argument as ยง392 read it, or what it held when a `\par` stopped it.
enum Arg {
    Read(Vec<Token>),
    Par(Vec<Token>),
    /// A `}` where a parameter was being read, which ยง395 reports and treats
    /// as a `\par`; carries what the argument held so far and the brace.
    ExtraBrace(Vec<Token>, Token),
}

/// ยง392's `cur_tok=par_token`: the control sequence `\par` itself, whatever it
/// means now.
fn is_par(t: &Token) -> bool {
    matches!(t, Token::Cs(n) if n.name() == "par")
}

/// Whether `toks` is a single brace group and nothing else: ยง392 counts the
/// items of a delimited argument (a group is one), and ยง400 strips braces
/// only from an argument of one item that is a group.
fn is_one_group(toks: &[Token]) -> bool {
    if !matches!(toks.first(), Some(Token::Char(_, Cat::BeginGroup))) {
        return false;
    }
    let mut depth = 0usize;
    for (i, t) in toks.iter().enumerate() {
        match t {
            Token::Char(_, Cat::BeginGroup) => depth += 1,
            Token::Char(_, Cat::EndGroup) => {
                depth = depth.saturating_sub(1);
                if depth == 0 {
                    return i == toks.len() - 1;
                }
            }
            _ => {}
        }
    }
    false
}

/// Where the lowerer is in ยง1211's `prefixed_command`.
#[derive(Clone, Copy, PartialEq, Debug, Default)]
pub enum PrefixStep {
    /// No prefix is in force.
    #[default]
    Idle,
    /// A prefix was read and the command it governs has not been.
    Waiting,
    /// The governed assignment is being lowered; its prefixes end with it.
    Running,
}

/// What the token after a prefix is (ยง1211).
enum AfterPrefix {
    /// A space or `\relax`: skipped.
    Skip,
    /// Something `get_x_token` expands, or another prefix: the wait goes on.
    Expands,
    /// An assignment; `def` is whether it is a `\def` (ยง1213).
    Assignment { def: bool },
    /// Anything else: ยง1212's error.
    Other,
}

/// Starts a report that is tracing output (ยง245), not an error: printed, but
/// not counted against the run.
pub const DIAGNOSTIC: char = '\u{1}';

/// A report that prints nothing and only records that a diagnostic went to
/// the log (`history=warning_issued`).
pub const WARNING_ISSUED: &str = "\u{2}";

/// 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),
}

/// A glue as `tex.web` ยง461 read it, before its three `<dimen>` positions are
/// collapsed to numbers.
///
/// Each of the three can be ยง453's `<factor><internal unit>` -- size10.clo's
/// `\abovedisplayskip 10\p@ \@plus2\p@ \@minus5\p@` is all three at once -- and
/// a product of a register is not a number the scanner can produce. The two
/// ORDERS are always known: an infinite component is spelt in letters, which no
/// internal unit is.
#[derive(Clone, Copy, Debug)]
pub struct GlueParts {
    pub natural: crate::dimen::ScannedDimen,
    pub stretch: crate::dimen::ScannedDimen,
    pub stretch_order: i64,
    pub shrink: crate::dimen::ScannedDimen,
    pub shrink_order: i64,
}

/// `abs(mode)` (ยง211): the kind of list being built.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ModeKind {
    Vertical,
    Horizontal,
    Math,
    /// `mode=0`: no list at all, which ยง1370 sets while a `\write` is
    /// expanded, so every mode conditional is false there.
    NoList,
}

/// What opened a group (`tex.web` ยง269's group codes).
///
/// The expander opens the simple and semi-simple ones; the lowerer opens the
/// rest where a box, an insertion, a discretionary, the output routine or a
/// formula begins its group (`src/lower/stomach.rs`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GroupKind {
    /// `simple_group`, opened by `{`.
    Simple,
    /// `hbox_group`: an `\hbox{` outside vertical mode, or one being set.
    Hbox,
    /// `adjusted_hbox_group`: an `\hbox{` in vertical mode (ยง1083).
    AdjustedHbox,
    /// `vbox_group`.
    Vbox,
    /// `vtop_group`.
    Vtop,
    /// `align_group`.
    Align,
    /// `no_align_group`.
    NoAlign,
    /// `output_group`: the `\output` routine (ยง1025).
    Output,
    /// `math_group`: a `{` subformula, a script or a nucleus (ยง1153).
    Math,
    /// `disc_group`: one of `\discretionary`'s three lists (ยง1117).
    Disc,
    /// `insert_group`: `\insert` or `\vadjust` (ยง1099).
    Insert,
    /// `vcenter_group` (ยง1167).
    VCenter,
    /// `math_choice_group`: one of `\mathchoice`'s four lists (ยง1172).
    MathChoice,
    /// `semi_simple_group`, opened by `\begingroup`.
    SemiSimple,
    /// `math_shift_group`: a formula, `$` to `$` (ยง1139).
    MathShift,
    /// `math_left_group`: `\left` to `\right` (ยง1191).
    MathLeft,
}

impl GroupKind {
    /// The group code, as `\currentgrouptype` gives it (ยง269).
    pub fn code(self) -> i64 {
        match self {
            GroupKind::Simple => 1,
            GroupKind::Hbox => 2,
            GroupKind::AdjustedHbox => 3,
            GroupKind::Vbox => 4,
            GroupKind::Vtop => 5,
            GroupKind::Align => 6,
            GroupKind::NoAlign => 7,
            GroupKind::Output => 8,
            GroupKind::Math => 9,
            GroupKind::Disc => 10,
            GroupKind::Insert => 11,
            GroupKind::VCenter => 12,
            GroupKind::MathChoice => 13,
            GroupKind::SemiSimple => 14,
            GroupKind::MathShift => 15,
            GroupKind::MathLeft => 16,
        }
    }

    /// etex.ch's `print_group`, without the level and the line.
    pub fn name(self) -> &'static str {
        match self {
            GroupKind::Simple => "simple",
            GroupKind::Hbox => "hbox",
            GroupKind::AdjustedHbox => "adjusted hbox",
            GroupKind::Vbox => "vbox",
            GroupKind::Vtop => "vtop",
            GroupKind::Align => "align",
            GroupKind::NoAlign => "no align",
            GroupKind::Output => "output",
            GroupKind::Math => "math",
            GroupKind::Disc => "disc",
            GroupKind::Insert => "insert",
            GroupKind::VCenter => "vcenter",
            GroupKind::MathChoice => "math choice",
            GroupKind::SemiSimple => "semi simple",
            GroupKind::MathShift => "math shift",
            GroupKind::MathLeft => "math left",
        }
    }

    /// Whether a `}` closes it (ยง1068): all but `\begingroup`'s, a formula's
    /// and `\left`'s, for which ยง1069 reports the `}` instead.
    pub fn closed_by_brace(self) -> bool {
        !matches!(
            self,
            GroupKind::SemiSimple | GroupKind::MathShift | GroupKind::MathLeft
        )
    }
}

/// `\the` or `\number` of a register, read where a quantity is scanned; see
/// [`Engine::take_expanded_register`].
pub struct ExpandedRegister {
    /// `\the` rather than `\number`: an integer register writes the same
    /// digits under either, a dimension `3.0pt` under one and `196608` under
    /// the other.
    pub the: bool,
    /// The slot the register lives in.
    pub slot: i64,
    /// What was read, in order, for [`Engine::put_back`].
    read: Vec<Token>,
}

/// 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(i64, char, Cat),
    /// The `\catcodetable` a group switched away from.
    CatTable(i64),
    /// One LuaTeX attribute register as it stood before a group assigned it.
    Attribute(i64, i64),
    /// 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),
    /// One integer parameter (ยง236) as it stood before a group assigned it.
    IntPar(usize, 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),
    /// The current font (ยง230's `cur_font_loc`) as it stood before a
    /// group selected another.
    Font(u16),
    /// One math family entry (ยง230's `math_font_base`): the size (text,
    /// script, scriptscript), the family, and the font it held.
    FamFont(u8, u8, u16),
}

impl Save {
    /// Whether two records restore the same entry of the same table -- which is
    /// what a global assignment to that entry has to drop from every group.
    /// The intercept registry and an `\aftergroup` token are not entries a
    /// `\global` assignment can name, so they match nothing.
    fn same_entry(&self, other: &Save) -> bool {
        match (self, other) {
            (Save::Cat(ta, a, _), Save::Cat(tb, b, _)) => ta == tb && a == b,
            (Save::CatTable(_), Save::CatTable(_)) => true,
            (Save::Attribute(a, _), Save::Attribute(b, _)) => a == b,
            (Save::Toks(a, _), Save::Toks(b, _)) => a == b,
            (Save::CharCode(ta, a, _), Save::CharCode(tb, b, _)) => ta == tb && a == b,
            (Save::IntPar(a, _), Save::IntPar(b, _)) => a == b,
            (Save::Count(a, _), Save::Count(b, _)) => a == b,
            (Save::Meaning(a, _), Save::Meaning(b, _)) => a == b,
            (Save::Font(_), Save::Font(_)) => true,
            (Save::FamFont(s, f, _), Save::FamFont(t, g, _)) => s == t && f == g,
            _ => false,
        }
    }
}

/// An open `\read` stream (ยง480): the lines not yet read.
struct ReadStream {
    lines: std::collections::VecDeque<String>,
}

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 pointer with
    /// FxHash is what makes that cheap. `tex.web` reaches `eqtb` the same way,
    /// by the pointer the hash table already produced.
    pub meanings: FxHashMap<CsId, Meaning>,
    /// Default values recorded by `\newcommand{\x}[n][default]`.
    optional_defaults: FxHashMap<CsId, Vec<Token>>,
    /// The registers, as far as the frontend can follow them; see
    /// [`crate::known`].
    pub known: crate::known::Known,
    /// The highest register number a `\count`, `\dimen`, `\skip`, `\muskip` or
    /// `\toks` may have: TeX82's 255 (ยง433's `scan_eight_bit_int`), or
    /// LuaTeX's 65535 for a run that is being luatex -- a LaTeX document, or
    /// `--luatex`. See [`Engine::register_address`].
    pub register_limit: i64,
    /// The slots registers past 255 were given, by file and number, and the
    /// way back from a slot to its register for a display.
    high_slots: FxHashMap<(crate::compiler::RegFile, i64), i64>,
    high_names: FxHashMap<i64, (crate::compiler::RegFile, i64)>,
    /// How many slots of each pool are taken, in `RegFile` order.
    high_used: [i64; 4],
    /// Commands the gullet made where the lowerer was not looking -- a
    /// `\directlua` expanded inside a `\csname` writes registers -- for the
    /// lowerer to put into the program at the next token (`take_deferred`).
    deferred: Vec<crate::ir::Cmd>,
    /// `\everyeof` as the mouth reads it when a file ends (etex.ch ยง362):
    /// shared with every file's lexer, and kept equal to the token
    /// parameter by `sync_everyeof`.
    everyeof: Rc<std::cell::RefCell<Vec<Token>>>,
    /// LuaTeX's attribute registers (`\attribute n`), each unset --
    /// [`UNUSED_ATTRIBUTE`] -- until assigned. Frontend state like the integer
    /// parameters: what the stomach attaches to a node is the value in force
    /// when the node is made, which is known while lowering.
    attributes: FxHashMap<i64, i64>,
    pub messages: Vec<String>,
    /// The line `\inputlineno` was last read on (ยง1382's `line`). A read
    /// primitive answers the line of the token that named it, so the mouth
    /// records it at that token rather than when the value is used.
    input_line: u32,
    /// ยง236's integer parameters -- `\escapechar` among them, which is
    /// why `esc()` reads here.
    pub intpars: crate::intpar::IntPars,
    /// ยง480's sixteen `\read` streams: `None` for one that is closed, which
    /// is all of them until `\openin` finds a file.
    read_streams: Vec<Option<ReadStream>>,
    /// ยง286's `mag_set`: the `\mag` the first `true` dimension used, which
    /// every later one must agree with. Zero until then.
    mag_set: i64,
    /// One frame per open group; each holds the undo records for that group.
    groups: Vec<Vec<Save>>,
    /// What opened each of `groups`, innermost last: ยง269's `cur_group`, which
    /// decides what a `}` or an `\endgroup` that does not match it is.
    group_kinds: Vec<GroupKind>,
    /// The line each of `groups` was entered on, for etex.ch's `\showgroups`
    /// (`saved(-1)`, the `line` when the group began).
    group_lines: Vec<u32>,
    /// Open conditionals, so `\else`/`\fi` know what they close.
    conds: Vec<CondState>,
    /// What opened each of `conds` and on which line (ยง489's `cur_if` and
    /// `if_line`), for ยง1335's `(\end occurred when \iftrue on line 2 was
    /// incomplete)` and e-TeX's `\currentif...`: the primitive's name,
    /// whether `\unless` negated it, and -- for an arm of a conditional the
    /// RUN decides, which the lowerer is reading and `conds` never holds --
    /// which branch that arm is (1 or -1).
    cond_info: Vec<(&'static str, bool, u32, Option<i64>)>,
    /// 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,
    prefix_step: PrefixStep,
    scaling_sites: std::collections::VecDeque<String>,
    /// 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>,
    /// Inside [`Engine::local_control`]: what `step` does there reaches no
    /// program, so an assignment only the program could make is refused.
    in_local_control: bool,
    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,
    /// `tex.web` ยง455's `em` and `ex`, in scaled points, once they have been
    /// read off a font.
    ///
    /// `None` until a dimension actually spells one of the two: resolving them
    /// opens a `.tfm`, and a run that never writes `em` must not pay for a font
    /// it never measures with. See `font_units`.
    font_units: Option<crate::tfm::FontUnits>,
    /// Font memory (ยง549-ยง551) for the fonts `\font` has loaded, which
    /// `\meaning` names and `crate::lower`'s stomach dispatch selects.
    pub fonts: crate::stomach::font::Table,
    /// The current font (ยง230's `cur_font_loc`), an internal font number;
    /// `\nullfont` (0) until a font identifier is selected (ยง232).
    pub cur_font: u16,
    /// The math families (ยง230's `math_font_base`): `\textfont`, `\scriptfont`
    /// and `\scriptscriptfont` of each of the sixteen, `\nullfont` until assigned.
    pub fam_fonts: [[u16; 16]; 3],
    /// The mode (ยง211) the lowerer follows the semantic nest in, for
    /// `\ifvmode`, `\ifhmode`, `\ifmmode` and `\ifinner` (ยง501): the kind of
    /// list and whether it is the inner variant. `None` where the lowerer
    /// does not build the lists (a LaTeX document).
    pub list_mode: Option<(ModeKind, 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>,
    /// LuaTeX's PDF backend as the document reaches it: see `crate::backend`.
    pub backend: crate::backend::Backend,
    /// Whether an undefined control sequence is what tex says it is -- an
    /// error that is reported, expands to nothing, and lets the run go on --
    /// rather than the stop an embedder's `Result` asks for. Off for the
    /// library API, on for a run that is meant to read like tex's.
    pub recover: bool,
    /// ยง82's `error_count`: errors since the last paragraph ended. tex gives up
    /// at 100, which is what ends a run that cannot stop reporting.
    pub error_count: u32,
    /// Whether that limit was reached and the run has stopped.
    pub halted: bool,
    /// ยง73's `interaction`: 0 batch, 1 nonstop, 2 scroll, 3 errorstop. texrs
    /// never stops to ask, so the four differ in what reaches the terminal:
    /// in batch mode nothing does. A run starts in nonstop mode, which is what
    /// the harnesses run luatex in. A run with a terminal attached
    /// ([`with_terminal`]) starts in scroll mode instead, so `\read` can take
    /// its lines (ยง484).
    pub interaction: i64,
    /// luatex's `is_in_csname`: how many `\csname`s are reading their names,
    /// which `\ifincsname` asks.
    in_csname: u32,
    /// luatex's `last_cs_name`: what the last `\csname`, `\begincsname` or
    /// `\ifcsname` looked up, for `\lastnamedcs`. `None` is `null_cs`.
    last_cs_name: Option<CsId>,
    /// LuaTeX's `\catcodetable`: which table `cats` is.
    pub cat_table: i64,
    /// The other tables `\savecatcodetable` and `\initcatcodetable` have made
    /// valid (textcodes.c's `catcode_heads`), by number; the current one is
    /// `cats`, and is not here.
    cat_tables: FxHashMap<i64, CatTable>,
    /// Tables in `cat_tables` that only a code assigned from Lua made
    /// (`set_cat_code` on a missing table), which `\catcodetable` may not
    /// switch to: textcodes.c leaves `catcode_valid` unset for them.
    unset_cat_tables: std::collections::HashSet<i64>,
}

/// 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";

/// The brace that ends a `\message` body, kept as the body's last token so a
/// scanner that reads up to it puts it back, as tex puts back the real one.
/// A NUL in the name keeps it out of reach of any document.
pub const MESSAGE_END: &str = "\u{0}message-end";

/// ยง222's `frozen_protection`: the control sequence `get_r_token` puts in the
/// place of a name that is missing. Its name begins with a character the mouth
/// never makes part of one, so no document can spell it.
pub const INACCESSIBLE: &str = "\u{0}inaccessible";

/// The font `em` and `ex` are measured in, and the size it is loaded at.
///
/// Named here rather than passed in because it is not a choice the caller gets
/// to make: `typeset::FontChain::load("cmr10", ..)` is what every path in this
/// engine sets a document in, and plain tex's own current font after
/// `\input plain` is the same `cmr10` at ten points. `Engine::font_units` says
/// what that costs where a document would have had another font.
const TEXT_FONT: &str = "cmr10";
const TEXT_FONT_AT: i64 = 10 * crate::dimen::UNITY;

/// 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 `\ifcase` case is running: an `\or` as well as an `\else` ends it (ยง510's
    /// `if_limit` is `or_code` rather than `else_code`).
    TakenCase,
    /// A branch was skipped to get here; `\else` must not re-enter.
    Done,
    /// The test is still being read (ยง498's `if_limit=if_code`).
    Testing,
}

#[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",
    // LuaTeX's (conditional.c): the absolute-value comparisons, whether a
    // `\csname` is being read, whether a name still means its primitive, and
    // `\ifcondition`, which expands to nothing and is a conditional only to
    // the skipper.
    "ifabsnum",
    "ifabsdim",
    "ifincsname",
    "ifprimitive",
    "ifcondition",
    "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: FxHashMap::default(),
            optional_defaults: FxHashMap::default(),
            known: crate::known::Known::default(),
            register_limit: default_register_limit(),
            high_slots: FxHashMap::default(),
            high_names: FxHashMap::default(),
            high_used: [0; 4],
            attributes: FxHashMap::default(),
            everyeof: Rc::default(),
            deferred: Vec::new(),
            messages: Vec::new(),
            input_line: 0,
            intpars: crate::intpar::IntPars::new(),
            read_streams: (0..16).map(|_| None).collect(),
            mag_set: 0,
            groups: Vec::new(),
            group_kinds: Vec::new(),
            group_lines: Vec::new(),
            conds: Vec::new(),
            cond_info: Vec::new(),
            charcodes: crate::charcodes::CharCodes::default(),
            toks: std::collections::HashMap::new(),
            global: false,
            long: false,
            outer: false,
            protected: false,
            prefix_step: PrefixStep::Idle,
            scaling_sites: std::collections::VecDeque::new(),
            intercepts: crate::intercepts::Registry::new(),
            advice_depth: 0,
            unless: false,
            mu_units: false,
            font_units: None,
            fonts: crate::stomach::font::Table::new(),
            cur_font: 0,
            fam_fonts: [[0; 16]; 3],
            list_mode: None,
            errors: Vec::new(),
            backend: crate::backend::Backend::default(),
            recover: false,
            error_count: 0,
            halted: false,
            interaction: match has_terminal() {
                true => 2,
                false => 1,
            },
            in_csname: 0,
            last_cs_name: None,
            cat_table: 0,
            cat_tables: FxHashMap::default(),
            unset_cat_tables: std::collections::HashSet::new(),
            after_group_tokens: Vec::new(),
            after_assignment: None,
            in_local_control: false,
        }
    }

    /// luatex's `local_control` for `tex.runtoks`: execute what is in front of
    /// the mouth until it is read down to `stop` tokens of pending input -- the
    /// depth before the Lua function put its tokens back -- expanding as it
    /// goes. Definitions, `\let`, the code tables, groups and the integer
    /// parameters take effect here as in the lowerer; a `\count` assignment, a
    /// count `\advance`/`\multiply`/`\divide` and `\message` are the program's
    /// in the lowerer and are refused by name, as is `\end`.
    pub fn local_control(&mut self, lx: &mut Lexer, stop: usize) -> R<()> {
        self.in_local_control = true;
        let out = (|| {
            while lx.pending.len() > stop {
                let Some(tok) = lx.next_token(&self.cats) else {
                    break;
                };
                if self.step(lx, tok)? {
                    return Err(TexError("\\end inside tex.runtoks".into()));
                }
            }
            Ok(())
        })();
        self.in_local_control = false;
        out
    }

    /// The refusal [`Self::local_control`] makes for `what`.
    fn not_in_local_control(&self, what: &str) -> R<()> {
        match self.in_local_control {
            true => Err(TexError(format!(
                "\\{what} inside tex.runtoks is not supported"
            ))),
            false => Ok(()),
        }
    }

    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, kind: GroupKind, line: u32) {
        self.groups.push(Vec::new());
        self.group_kinds.push(kind);
        self.group_lines.push(line);
        self.group_trace(false, kind, self.group_kinds.len(), line);
        // luatex's `run_left_brace` and `run_begin_group` (maincontrol.c)
        // reset two internal integers on every group they open, which
        // `\tracingassigns` shows; texrs never changes either, so both are
        // reassigned their zero.
        if self.intpar_named("tracingassigns") > 0 {
            let e = self.esc();
            self.diagnostic(&format!("{{reassigning {e}nolocalwhatsits=0}}"));
            self.diagnostic(&format!("{{reassigning {e}nolocaldirs=0}}"));
        }
    }

    /// etex.ch's `group_trace`: under `\tracinggroups`, `{entering simple group
    /// (level 1) at line 3}` as a group opens and `{leaving simple group (level
    /// 1) entered at line 3}` as it closes, once it has restored what it saved
    /// (luatex's order; see `end_group`).
    fn group_trace(&mut self, leaving: bool, kind: GroupKind, level: usize, line: u32) {
        if self.intpar_named("tracinggroups") <= 0 {
            return;
        }
        let what = kind.name();
        let (verb, at) = match leaving {
            true => ("leaving", "entered at line"),
            false => ("entering", "at line"),
        };
        let line = match line {
            0 => String::new(),
            n => format!(" {at} {n}"),
        };
        self.diagnostic(&format!("{{{verb} {what} group (level {level}){line}}}"));
    }

    /// What opened the innermost open group, or `None` at ยง269's
    /// `bottom_level`.
    /// How many groups are open, ยง1335's `cur_level-level_one`.
    pub fn group_level(&self) -> usize {
        self.group_kinds.len()
    }

    pub fn innermost_group(&self) -> Option<GroupKind> {
        self.group_kinds.last().copied()
    }

    /// `\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 no group end to wait for, and ยง280's
    /// `save_for_after` saves nothing at level one: the token is dropped.
    pub fn after_group(&mut self, tok: Token) {
        if let Some(frame) = self.groups.last_mut() {
            frame.push(Save::AfterGroup(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()));
        };
        // luatex's `unsave` traces the group AFTER restoring what it saved
        // (equivalents.c), so `\tracinggroups` is read as the group leaves
        // it -- where etex.ch reads it before.
        let left = (self.group_kinds.pop(), self.group_lines.pop());
        let level = self.group_kinds.len() + 1;
        // ยง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(table, c, cat) => match table == self.cat_table {
                    true => self.cats.set(c, cat),
                    false => {
                        if let Some(t) = self.cat_tables.get_mut(&table) {
                            t.set(c, cat);
                        }
                    }
                },
                Save::CatTable(table) => self.switch_cat_table(table),
                Save::Attribute(n, v) => {
                    self.attributes.insert(n, v);
                }
                Save::Toks(reg, was) => {
                    match was {
                        Some(v) => self.toks.insert(reg, v),
                        None => self.toks.remove(&reg),
                    };
                    self.sync_everyeof(reg);
                }
                Save::CharCode(t, c, v) => {
                    let _ = self.charcodes.set(t, c, v);
                }
                Save::IntPar(i, v) => self.store_intpar(i, v),
                Save::Count(reg, old) => self.known.set(reg, old),
                Save::Meaning(name, old) => match old {
                    Some(m) => {
                        self.meanings.insert(name, m);
                    }
                    None => {
                        self.meanings.remove(&name);
                    }
                },
                Save::Intercepts(old) => self.intercepts = old,
                Save::Font(f) => self.cur_font = f,
                Save::FamFont(s, fam, f) => self.fam_fonts[s as usize][fam as usize] = f,
                // Already collected above; it is a token to insert, not a
                // value to put back.
                Save::AfterGroup(_) => {}
            }
        }
        if let (Some(kind), Some(line)) = left {
            self.group_trace(true, kind, level, line);
        }
        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)
    }

    /// A `\global`, `\long` or `\outer` was just read: the next command is the
    /// one it governs (ยง1211).
    pub fn await_prefixed_command(&mut self) {
        self.prefix_step = PrefixStep::Waiting;
    }

    /// ยง1211 and ยง1213 for the token `tok` the lowerer is about to dispatch.
    ///
    /// Reads past what `get_x_token` would skip or expand, then judges the
    /// command the prefixes stand in front of. A command no prefix may govern
    /// is `You can't use a prefix with`, the token is read again and the
    /// prefixes are dropped; `\long` or `\outer` before anything but a
    /// definition is reported and the command goes on. Prefixes end with the
    /// command they governed, so the step after it clears them.
    ///
    /// Returns whether `tok` is consumed here.
    pub fn prefix_gate(&mut self, lx: &mut Lexer, tok: &Token) -> bool {
        match self.prefix_step {
            PrefixStep::Idle => return false,
            PrefixStep::Running => {
                self.clear_prefixes();
                return false;
            }
            PrefixStep::Waiting => {}
        }
        match self.after_prefix(tok) {
            AfterPrefix::Skip => true,
            AfterPrefix::Expands => false,
            AfterPrefix::Assignment { def } => {
                self.prefix_step = PrefixStep::Running;
                if !def && (self.long || self.outer) {
                    let msg = format!(
                        "You can't use `{0}long' or `{0}outer' with `{1}'",
                        self.esc(),
                        self.meaning_text(tok)
                    );
                    self.report(lx, &msg);
                }
                false
            }
            AfterPrefix::Other => {
                lx.back_input(std::slice::from_ref(tok));
                let msg = format!("You can't use a prefix with `{}'", self.meaning_text(tok));
                self.report(lx, &msg);
                self.clear_prefixes();
                true
            }
        }
    }

    fn clear_prefixes(&mut self) {
        self.global = false;
        self.long = false;
        self.outer = false;
        self.protected = false;
        self.prefix_step = PrefixStep::Idle;
    }

    /// What `tok` is to ยง1211's loop over the tokens after a prefix.
    fn after_prefix(&self, tok: &Token) -> AfterPrefix {
        let n = match tok {
            Token::Char(_, _) if tok.is_space() => return AfterPrefix::Skip,
            Token::Char(..) => return AfterPrefix::Other,
            Token::Cs(n) => *n,
        };
        if n.noexpand_origin().is_some() {
            return AfterPrefix::Skip;
        }
        match self.meanings.get(&n) {
            Some(Meaning::Macro(_)) => return AfterPrefix::Expands,
            Some(Meaning::Char(_, Cat::Space)) => return AfterPrefix::Skip,
            Some(Meaning::Char(..) | Meaning::CharDef(_) | Meaning::MathCharDef(_)) => {
                return AfterPrefix::Other
            }
            Some(Meaning::ToksDef(_) | Meaning::CountDef(_) | Meaning::AttributeDef(_)) => {
                return AfterPrefix::Assignment { def: false }
            }
            _ => {}
        }
        if self.is_undefined(n) {
            return AfterPrefix::Expands;
        }
        let p = self.primitive_meaning(n);
        let name = p.name();
        if name == "relax" {
            return AfterPrefix::Skip;
        }
        if matches!(name, "global" | "long" | "outer" | "protected")
            || crate::primitives::expands(name)
            || Self::is_conditional(p)
        {
            return AfterPrefix::Expands;
        }
        let def = matches!(name, "def" | "gdef" | "edef" | "xdef");
        match def || Self::is_assignment(name) || crate::primitives::is_prefixed_assignment(name) {
            true => AfterPrefix::Assignment { def },
            false => AfterPrefix::Other,
        }
    }

    /// 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.
    #[inline(never)]
    /// The report [`Self::report`] would make here, for the run to make
    /// instead if what it evaluates goes wrong: the run has no mouth, so the
    /// context has to be taken now.
    pub fn report_text(&mut self, lx: &Lexer, msg: &str) -> String {
        self.note_mouth(lx);
        format!("! {msg}.{}", self.error_context(lx).replace('\n', ""))
    }

    pub fn report(&mut self, lx: &Lexer, msg: &str) {
        self.note_mouth(lx);
        let context = self.error_context(lx);
        self.errors
            .push(format!("! {msg}.{}", context.replace('\n', "")));
        self.tally_error();
    }

    /// ยง245's `begin_diagnostic` and `end_diagnostic` around `text`: tracing
    /// output that is not an error. It reaches the terminal only when
    /// `\tracingonline` is positive; otherwise it goes to the log alone, which
    /// the terminal learns of as `history=warning_issued` -- the closing
    /// "see the transcript file" line (ยง1335).
    ///
    /// Carried in the same list as the errors, marked, so it stays in order
    /// with them and with the messages around it.
    pub fn diagnostic(&mut self, text: &str) {
        let line = match self.intpars.get(crate::intpar::TRACING_ONLINE) > 0 {
            true => format!("{DIAGNOSTIC}{text}"),
            false => WARNING_ISSUED.to_string(),
        };
        self.errors.push(line);
    }

    /// A line for the terminal that is neither an error nor tracing: what
    /// luatex's `normal_warning` prints, which `crate::backend` reports with.
    pub fn terminal_note(&mut self, text: &str) {
        self.errors.push(format!("{DIAGNOSTIC}{text}"));
    }

    /// How many reports and diagnostics are waiting; see [`Self::drain_diagnostics`].
    pub fn report_mark(&self) -> usize {
        self.errors.len()
    }

    /// Remove the tracing output (ยง245) made since `mark` and return it, leaving
    /// the errors in place. For a caller that expands the same text twice and
    /// must show the trace of only one of the passes.
    pub fn drain_diagnostics(&mut self, mark: usize) -> Vec<String> {
        let tail = self.errors.split_off(mark.min(self.errors.len()));
        let (traces, kept): (Vec<String>, Vec<String>) = tail
            .into_iter()
            .partition(|r| r.starts_with(DIAGNOSTIC) || r == WARNING_ISSUED);
        self.errors.extend(kept);
        traces
    }

    /// Put back what [`Self::drain_diagnostics`] took.
    pub fn restore_diagnostics(&mut self, traces: Vec<String>) {
        self.errors.extend(traces);
    }

    /// ยง311's `show_context`: every level of the input stack texrs keeps --
    /// a macro's body with its parameters shown as written, an argument being
    /// read, what ยง325's `back_input` and ยง327's `ins_error` put back -- above
    /// the file line.
    ///
    /// A `\message` body is read before it is expanded, so its lexer carries a
    /// [`crate::lexer::Site`]: the file line is the one the scanner had
    /// reached, and the levels of whatever the body was read from follow.
    pub fn error_context(&self, lx: &Lexer) -> String {
        use crate::lexer::LevelKind;
        // ยง311: the innermost level is always shown and the file line always
        // is; a level between them only while fewer than `\errorcontextlines`
        // levels have been (the innermost counts), and `...` once in place of
        // the rest when exactly that many have.
        let limit = crate::intpar::index("errorcontextlines").map_or(0, |i| self.intpars.get(i));
        // ยง311's `nn`, which starts at -1 so the innermost level brings it to 0.
        let mut nn = -1i64;
        let mut out = String::new();
        let mut innermost = true;
        let mut put = |text: String, out: &mut String, innermost: &mut bool| {
            if *innermost || nn < limit {
                *innermost = false;
                nn += 1;
                out.push_str(&text);
                out.push('\n');
            } else if nn == limit {
                out.push_str("...\n");
                nn += 1;
            }
        };
        let mut site = None;
        for view in lx.levels() {
            if let LevelKind::Site(s) = view.kind {
                site = Some(s.clone());
                continue;
            }
            for text in self.level_displays(view.kind, view.toks, view.read) {
                put(text, &mut out, &mut innermost);
            }
        }
        match site {
            Some(site) => {
                let body = site.body_len();
                let read = lx.body_read(body);
                for (toks, rd, kind) in site.parent_levels(read) {
                    for text in self.level_displays(&kind, &toks, rd) {
                        put(text, &mut out, &mut innermost);
                    }
                }
                out.push_str(&site.context(read));
            }
            None => out.push_str(&lx.context().unwrap_or_default()),
        }
        out
    }

    /// A token list as ยง311's display prints it: ยง358's `dont_expand` marker
    /// is a token of its own there, `\notexpanded:` in front of the control
    /// sequence it guards.
    fn context_text(&self, tokens: &[Token]) -> String {
        let mut out = String::new();
        for t in tokens {
            match t {
                Token::Cs(id) if id.noexpand_origin().is_some() => {
                    out.push_str(&self.cs_text("notexpanded:"));
                    out.push_str(&self.cs_text(id.name()));
                }
                other => out.push_str(&self.tokens_text(std::slice::from_ref(other))),
            }
        }
        out
    }

    /// The display entries one level makes, innermost first: a macro level
    /// stands for the argument being read from it as well.
    fn level_displays(
        &self,
        kind: &crate::lexer::LevelKind,
        toks: &[Token],
        read: usize,
    ) -> Vec<String> {
        use crate::lexer::LevelKind;
        match kind {
            LevelKind::Site(_) => Vec::new(),
            LevelKind::BackedUp | LevelKind::Inserted => {
                // ยง314: `<recently read>` once the list is read to its end.
                // ยง314 also labels inserted text, whatever has been read of it.
                let tag = match (matches!(kind, LevelKind::Inserted), read == toks.len()) {
                    (true, _) => "<inserted text> ",
                    (false, true) => "<recently read> ",
                    (false, false) => "<to be read again> ",
                };
                vec![Lexer::context_lines(
                    tag,
                    &self.context_text(&toks[..read]),
                    &self.context_text(&toks[read..]),
                )]
            }
            LevelKind::Macro { name, args } => self.macro_displays(*name, toks, read, args),
        }
    }

    /// ยง314's display of a macro level: `\name <parameter text>->` and the
    /// body as the DEFINITION wrote it -- `#1` where an argument goes -- split
    /// where reading has got to. An argument that is partly or wholly read is a
    /// level of its own above it (ยง390's `<argument>`).
    ///
    /// The substituted tokens in `toks` are what is read; the definition and
    /// the length of each argument say which part of the body each belongs to.
    fn macro_displays(&self, name: CsId, toks: &[Token], read: usize, args: &[u32]) -> Vec<String> {
        let Some(Meaning::Macro(m)) = self.meanings.get(&name) else {
            return vec![Lexer::context_lines(
                &self.cs_text(name.name()),
                &self.tokens_text(&toks[..read]),
                &self.tokens_text(&toks[read..]),
            )];
        };
        let mut out_idx = 0usize;
        let mut bi = 0usize;
        let mut argument: Option<(usize, usize, usize)> = None;
        let split = loop {
            let Some(tok) = m.body.get(bi) else {
                break m.body.len();
            };
            let mut span = 1usize;
            let mut width = 1usize;
            if matches!(tok, Token::Char(_, Cat::Param)) {
                match m.body.get(bi + 1) {
                    Some(Token::Char(d, _)) if d.is_ascii_digit() && *d != '0' => {
                        let idx = (*d as u8 - b'1') as usize;
                        span = args.get(idx).copied().unwrap_or(0) as usize;
                        width = 2;
                        // An argument of no tokens is read through silently.
                        if span == 0 {
                            bi += 2;
                            continue;
                        }
                        if read > out_idx && read <= out_idx + span {
                            argument = Some((out_idx, span, read - out_idx));
                            break bi + 2;
                        }
                    }
                    Some(Token::Char(_, Cat::Param)) => width = 2,
                    _ => {}
                }
            }
            if read <= out_idx {
                break bi;
            }
            out_idx += span;
            bi += width;
        };
        let mut shown = Vec::new();
        if let Some((from, span, consumed)) = argument {
            let arg = &toks[from..from + span];
            shown.push(Lexer::context_lines(
                "<argument> ",
                &self.context_text(&arg[..consumed]),
                &self.context_text(&arg[consumed..]),
            ));
        }
        let mut before = self.tokens_text(&m.params);
        before.push_str("->");
        before.push_str(&self.tokens_text(&m.body[..split]));
        shown.push(Lexer::context_lines(
            &self.cs_text(name.name()),
            &before,
            &self.tokens_text(&m.body[split..]),
        ));
        shown
    }

    /// ยง1294's `\show`: `> ` and what the token means, then the context an
    /// error shows -- `\show` ends by calling `error` -- so it lands in the
    /// stream exactly where a report does.
    pub fn show_token(&mut self, lx: &Lexer, tok: &Token) {
        self.note_mouth(lx);
        let name = match tok {
            Token::Cs(n) => format!("{}=", self.sprint_cs(*n)),
            Token::Char(c, Cat::Active) => format!("{c}="),
            Token::Char(..) => String::new(),
        };
        let meaning = match tok {
            Token::Char(c, Cat::Active) => match self.active_meaning(*c) {
                Some(id) => self.meaning_text(&Token::Cs(id)),
                None => "undefined".to_string(),
            },
            _ => self.meaning_text(tok),
        };
        let shown = format!("> {name}{meaning}.");
        let context = self.error_context(lx);
        self.errors
            .push(format!("{shown}{}", context.replace('\n', "")));
        self.tally_error();
    }

    /// e-TeX's `\showtokens` (etex.ch, `show_tokens` in ยง1293's
    /// `show_whatever`): `> `, the general text as ยง295 shows a token list,
    /// `.`, and the context, as `\show` reports.
    pub fn show_tokens(&mut self, lx: &mut Lexer) -> R<()> {
        let text = self.scan_general_text(lx)?;
        self.note_mouth(lx);
        let shown = format!("> {}.", self.tokens_shown(&text));
        let context = self.error_context(lx);
        self.errors
            .push(format!("{shown}{}", context.replace('\n', "")));
        self.tally_error();
        Ok(())
    }

    /// e-TeX's `\showgroups`: etex.ch's `show_save_groups` as a diagnostic,
    /// then ยง1298's `! OK`. Each open group, innermost first, as `### simple
    /// group (level 1) entered at line 3 ({)`, then `### bottom level`. Only
    /// the two groups the expander opens are here; a box, alignment or math
    /// group is the stomach's.
    pub fn show_groups(&mut self, lx: &Lexer) {
        let listing = self.save_groups_listing();
        self.show_whatever_ok(lx, &listing);
    }

    /// etex.ch's `show_save_groups`, as one line of text with nothing between
    /// its lines (the message stream has no line ends).
    pub fn save_groups_listing(&self) -> String {
        let mut listing = String::new();
        for (level, (kind, line)) in self
            .group_kinds
            .iter()
            .zip(&self.group_lines)
            .enumerate()
            .rev()
        {
            // etex.ch reconstructs a box's or a formula's opening text (its
            // spec, the `\setbox`); that is not kept here, so a group other
            // than these shows the token that opened it.
            let opener = match kind {
                GroupKind::SemiSimple => format!("{}begingroup", self.esc()),
                GroupKind::MathShift => "$".to_string(),
                GroupKind::MathLeft => format!("{}left", self.esc()),
                _ => "{".to_string(),
            };
            let what = kind.name();
            listing.push_str(&format!(
                "### {what} group (level {}) entered at line {line} ({opener})",
                level + 1
            ));
        }
        listing.push_str("### bottom level");
        listing
    }

    /// The end ยง1298 gives `\showbox`, `\showlists` and e-TeX's `\showgroups`
    /// and `\showifs`: the listing is a diagnostic (ยง245), then `! OK` with
    /// the context -- and ` (see the transcript file)` when the listing went
    /// to the log alone. It is not counted as an error (`decr(error_count)`).
    fn show_whatever_ok(&mut self, lx: &Lexer, listing: &str) {
        self.note_mouth(lx);
        self.diagnostic(listing);
        let pointer = match self.intpars.get(crate::intpar::TRACING_ONLINE) > 0 {
            true => "",
            false => " (see the transcript file)",
        };
        let context = self.error_context(lx);
        self.errors
            .push(format!("! OK{pointer}.{}", context.replace('\n', "")));
    }

    /// ยง82: every error counts, and the hundredth ends the run.
    fn tally_error(&mut self) {
        self.error_count += 1;
        if self.error_count >= 100 && !self.halted {
            self.halted = true;
            self.errors
                .push("(That makes 100 errors; please try again.".to_string());
        }
    }

    /// ยง346's report of each invalid character the mouth skipped, in front of
    /// anything reported after it. The mouth keeps them until asked, so every
    /// caller that is about to report or print asks first.
    ///
    /// Asked after every token the mouth hands over, and almost always with
    /// nothing to report, so that case is a look at the mouth inlined into the
    /// caller and the reporting is out of line.
    #[inline]
    pub fn note_mouth(&mut self, lx: &Lexer) {
        if lx.has_invalid() {
            self.report_invalid(lx);
        }
    }

    #[cold]
    fn report_invalid(&mut self, lx: &Lexer) {
        for context in lx.take_invalid() {
            self.errors.push(format!(
                "! Text line contains an invalid character.{}",
                context.replace('\n', "")
            ));
            self.tally_error();
        }
    }

    /// 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 `}`. It also DROPS what the
    /// open groups saved for the same entry: ยง283's `unsave` keeps the current
    /// value of an entry whose level a global assignment reset to `level_one`,
    /// so no `}` can put an older value back over a global one -- whichever
    /// kind of entry it is. A LOCAL assignment after it saves afresh, and that
    /// is the value its group restores.
    fn save(&mut self, rec: Save) {
        self.save_as(rec, self.global_defs_applied(self.global));
    }

    /// ยง1214: a positive `\globaldefs` makes every assignment global and a
    /// negative one makes every assignment local, `\global` and `\gdef`
    /// included; zero leaves the prefix to decide. Applying it twice changes
    /// nothing, so a caller that already applied it may pass the answer back.
    pub fn global_defs_applied(&self, global: bool) -> bool {
        match self.intpars.get(crate::intpar::GLOBAL_DEFS) {
            0 => global,
            g => g > 0,
        }
    }

    /// [`Self::save`] with the scope decided by the caller: ยง279's
    /// `geq_word_define` is global whatever `\globaldefs` says.
    fn save_as(&mut self, rec: Save, global: bool) {
        if global {
            for frame in &mut self.groups {
                frame.retain(|s| !s.same_entry(&rec));
            }
            return;
        }
        if self.groups.is_empty() {
            return;
        }
        if let Some(frame) = self.groups.last_mut() {
            frame.push(rec);
        }
    }

    /// ยง1257's `define(u,set_font,f)`: `name` becomes a font identifier.
    pub fn define_font_identifier(&mut self, name: CsId, f: u16, global: bool) {
        let was = std::mem::replace(&mut self.global, global);
        self.set_meaning(name, Meaning::Font(f));
        self.global = was;
    }

    /// ยง1217: selecting a font is an assignment to `cur_font_loc`, scoped
    /// by the group it is made in.
    pub fn select_font(&mut self, f: u16, global: bool) {
        let old = self.cur_font;
        self.save_as(Save::Font(old), self.global_defs_applied(global));
        self.cur_font = f;
    }

    /// ยง1234's `def_family`: `\textfont`, `\scriptfont` or `\scriptscriptfont`
    /// (`size` 0, 1, 2) of family `fam` is font `f`, scoped by the group.
    pub fn define_family(&mut self, size: u8, fam: u8, f: u16, global: bool) {
        let (s, k) = (size.min(2) as usize, (fam & 15) as usize);
        let old = self.fam_fonts[s][k];
        self.save_as(
            Save::FamFont(s as u8, k as u8, old),
            self.global_defs_applied(global),
        );
        self.fam_fonts[s][k] = f;
    }

    fn set_meaning(&mut self, name: CsId, m: Meaning) {
        let old = self.meanings.get(&name).cloned();
        // luatex's `eq_define` and `geq_define` (equivalents.c): under
        // `\tracingassigns` the entry before and after, or `reassigning` when
        // a local definition would change nothing -- the same command and the
        // same `equiv`, which for a macro is the same body, not an equal one.
        if self.intpar_named("tracingassigns") > 0 {
            let global = self.global_defs_applied(self.global);
            let same = match (&old, &m) {
                (Some(Meaning::Macro(a)), Meaning::Macro(b)) => Rc::ptr_eq(a, b),
                (Some(a), b) => a == b,
                (None, _) => false,
            };
            if same && !global {
                self.trace_entry("reassigning", name);
                return;
            }
            let verb = match global {
                true => "globally changing",
                false => "changing",
            };
            self.trace_entry(verb, name);
            self.save(Save::Meaning(name, old));
            self.meanings.insert(name, m);
            self.trace_entry("into", name);
            return;
        }
        // A global assignment wipes the saved values other groups hold (see
        // `save`), so no `}` can restore the old meaning over it.
        self.save(Save::Meaning(name, old));
        self.meanings.insert(name, m);
    }

    /// The value in register slot `slot`, as ยง413's `scan_something_internal`
    /// reads it out of `eqtb`.
    ///
    /// The table is [`crate::known`]'s, which follows every assignment the
    /// lowerer has made up to this token. A register whose value only the run
    /// has -- one a `\rustcall` assigned -- cannot be read here, and the error
    /// says so rather than answering with a value the run would contradict.
    pub fn count_value(&self, slot: i64) -> R<i64> {
        self.known.get(slot).ok_or_else(|| {
            TexError(format!(
                "Register slot {slot} is known only when the program runs"
            ))
        })
    }

    /// What ยง465's `\the` writes for the dimension or glue in `slot` (its
    /// first slot, for a glue): `print_scaled` and `pt`, or `print_spec`.
    fn slot_text(&self, slot: i64) -> R<String> {
        if !crate::compiler::is_glue_slot(slot) {
            let v = self.count_value(slot)?;
            return Ok(format!("{}pt", crate::dimen::print_scaled(v)));
        }
        let unit = match crate::compiler::is_mu_slot(slot) {
            true => "mu",
            false => "pt",
        };
        // Natural, stretch, shrink, and the two orders packed as the code
        // generator packs them (`stretch_order * 4 + shrink_order`).
        let orders = self.count_value(slot + 3)?;
        Ok(crate::glue::print_glue_in(
            unit,
            self.count_value(slot)?,
            self.count_value(slot + 1)?,
            orders / 4,
            self.count_value(slot + 2)?,
            orders % 4,
        ))
    }

    fn set_count(&mut self, reg: i64, val: i64) {
        let old = self.known.get(reg);
        self.save(Save::Count(reg, old));
        self.known.set(reg, Some(val));
    }

    /// The escape character `\escapechar` currently selects.
    pub fn esc(&self) -> crate::token::Esc {
        crate::token::Esc::from_code(self.intpars.get(crate::intpar::ESCAPE_CHAR))
    }

    /// Which ยง236 integer parameter `name` MEANS, if any: the primitive itself
    /// or a `\let` copy of it, and not a name a document has since redefined.
    pub fn intpar_cs(&self, name: CsId) -> Option<usize> {
        match self.meanings.get(&name) {
            None => crate::intpar::index(name.name()),
            Some(Meaning::Primitive(p)) => crate::intpar::index(p.name()),
            Some(_) => None,
        }
    }

    /// Assign an integer parameter, saved for the enclosing group unless the
    /// assignment is `\global` -- in which case `save` drops the values the
    /// open groups saved, so no `}` puts one back.
    /// `eq_word_define` of integer parameter `i` (ยง277): a local assignment
    /// the enclosing group undoes, as ยง1070's `normal_paragraph` makes.
    pub fn assign_intpar(&mut self, i: usize, v: i64) {
        self.set_intpar(i, v);
    }

    fn set_intpar(&mut self, i: usize, v: i64) {
        // luatex's `eq_word_define`: an equal value is `reassigning`, and is
        // not saved; see `set_meaning`.
        let trace = self.intpar_named("tracingassigns") > 0;
        if self.global_defs_applied(self.global) {
            return self.set_intpar_globally(i, v);
        }
        if self.intpars.get(i) == v {
            if trace {
                self.trace_intpar("reassigning", i);
            }
            // Not saved, but the document did assign it: a reader that takes
            // a value the document set over a default of its own (the PDF
            // backend's variables) has to see `\pdfvariable minorversion=0`.
            self.intpars.mark_assigned(i);
            return;
        }
        if trace {
            self.trace_intpar("changing", i);
        }
        self.save(Save::IntPar(i, self.intpars.get(i)));
        self.store_intpar(i, v);
        if trace {
            self.trace_intpar("into", i);
        }
    }

    /// ยง279's `geq_word_define` for an integer parameter: assigned at the
    /// outermost level, so no open group restores it.
    fn set_intpar_globally(&mut self, i: usize, v: i64) {
        let trace = self.intpar_named("tracingassigns") > 0;
        if trace {
            self.trace_intpar("globally changing", i);
        }
        self.save_as(Save::IntPar(i, self.intpars.get(i)), true);
        self.store_intpar(i, v);
        if trace {
            self.trace_intpar("into", i);
        }
    }

    /// Write an integer parameter, keeping the mouth's copy of `\endlinechar`
    /// (in the catcode table it is handed) in step with the table.
    pub fn store_intpar(&mut self, i: usize, v: i64) {
        self.intpars.set(i, v);
        if i == crate::intpar::END_LINE_CHAR {
            self.cats.set_end_line_char(v);
        }
    }

    /// `\tolerance=N` (ยง1228's `assign_int`): an optional `=` and a number.
    fn do_intpar_assign(&mut self, lx: &mut Lexer, i: usize) -> R<()> {
        self.skip_equals(lx)?;
        let v = self.scan_number(lx, false)?;
        self.set_intpar(i, v);
        Ok(())
    }

    /// The same, for a caller that is lowering. The `\global` prefix is SPENT
    /// here, as the lowerer's register arms spend it.
    pub fn compile_time_intpar(&mut self, lx: &mut Lexer, i: usize) -> R<()> {
        self.global = self.take_global_prefix();
        let out = self.do_intpar_assign(lx, i);
        self.global = false;
        out
    }

    /// `\advance\tolerance by N` and its two siblings on a parameter (ยง1238).
    fn intpar_arith(&mut self, lx: &mut Lexer, i: usize, op: Arith) -> R<()> {
        self.skip_by(lx)?;
        let val = self.scan_number(lx, false)?;
        match arith_int(self.intpars.get(i), val, op) {
            Some(v) => self.set_intpar(i, v),
            // ยง1236 reports through `error`, not `fatal_error`: the run goes
            // on and the parameter keeps the value it had.
            None => self.report(lx, "Arithmetic overflow"),
        }
        Ok(())
    }

    /// The lowerer's door to `Self::intpar_arith`: `op` is the primitive's
    /// name, which is what the lowerer holds.
    pub fn compile_time_intpar_arith(&mut self, lx: &mut Lexer, i: usize, op: &str) -> R<()> {
        let op = match op {
            "advance" => Arith::Add,
            "multiply" => Arith::Mul,
            _ => Arith::Div,
        };
        self.global = self.take_global_prefix();
        let out = self.intpar_arith(lx, i, op);
        self.global = false;
        out
    }

    /// What the gullet made for the program since the lowerer last asked.
    pub fn take_deferred(&mut self) -> Vec<crate::ir::Cmd> {
        std::mem::take(&mut self.deferred)
    }

    /// Keep the mouth's view of `\everyeof` equal to the parameter, after
    /// token register `reg` changed.
    fn sync_everyeof(&mut self, reg: i64) {
        if Some(reg) == crate::params::toks_register("everyeof") {
            *self.everyeof.borrow_mut() = self.toks.get(&reg).cloned().unwrap_or_default();
        }
    }

    /// The `\everyeof` a file's lexer inserts at the file's end; see
    /// `Lexer::insert_everyeof`.
    pub fn everyeof_handle(&self) -> Rc<std::cell::RefCell<Vec<Token>>> {
        Rc::clone(&self.everyeof)
    }

    /// LuaTeX attribute register `n` (the LuaTeX manual, "Attributes"): unset
    /// until assigned, and `\the` of an unset one is `-2147483647`, measured.
    pub fn attribute_value(&self, n: i64) -> i64 {
        self.attributes.get(&n).copied().unwrap_or(UNUSED_ATTRIBUTE)
    }

    /// The attribute register a `\attributedef` name stands for.
    pub fn attribute_of(&self, name: CsId) -> Option<i64> {
        match self.meanings.get(&name) {
            Some(Meaning::AttributeDef(n)) => Some(*n),
            _ => None,
        }
    }

    fn set_attribute(&mut self, n: i64, v: i64) {
        self.save(Save::Attribute(n, self.attribute_value(n)));
        self.attributes.insert(n, v);
    }

    /// `\attribute n = v`, or a `\attributedef` name and `= v`: an integer
    /// assignment, scoped by the group unless `\global`.
    pub fn compile_time_attribute(&mut self, lx: &mut Lexer, n: i64) -> R<()> {
        self.global = self.take_global_prefix();
        let out = self
            .skip_equals(lx)
            .and_then(|_| self.scan_number(lx, false));
        if let Ok(v) = &out {
            self.set_attribute(n, *v);
        }
        self.global = false;
        out.map(|_| ())
    }

    /// `\advance`, `\multiply` or `\divide` of attribute register `n`, as
    /// ยง1236 does it for an integer.
    pub fn compile_time_attribute_arith(&mut self, lx: &mut Lexer, n: i64, op: &str) -> R<()> {
        let op = match op {
            "advance" => Arith::Add,
            "multiply" => Arith::Mul,
            _ => Arith::Div,
        };
        self.global = self.take_global_prefix();
        let out = self.skip_by(lx).and_then(|_| self.scan_number(lx, false));
        if let Ok(by) = &out {
            match arith_int(self.attribute_value(n), *by, op) {
                Some(v) => self.set_attribute(n, v),
                None => self.report(lx, "Arithmetic overflow"),
            }
        }
        self.global = false;
        out.map(|_| ())
    }

    fn set_cat(&mut self, c: char, cat: Cat) {
        self.save(Save::Cat(self.cat_table, 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(GroupKind::Simple, lx.line());
                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 name.noexpand_origin().is_some() {
            return Ok(false);
        }
        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(GroupKind::SemiSimple, lx.line()),
            "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(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.not_in_local_control("count")?;
                self.do_count_assign(lx)?
            }
            _ if self.intpar_cs(name).is_some() => {
                let i = self.intpar_cs(name).expect("just matched");
                self.do_intpar_assign(lx, i)?
            }
            "advance" => self.do_arith(lx, Arith::Add)?,
            "multiply" => self.do_arith(lx, Arith::Mul)?,
            "divide" => self.do_arith(lx, Arith::Div)?,
            "message" => {
                self.not_in_local_control("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 โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    /// The primitive `name` MEANS, for a match on the meaning rather than the
    /// spelling.
    ///
    /// A `\let` alias means the primitive it was given, and tex matches
    /// `cur_cmd` everywhere: `\let\ifdim=\iffalse` reached the `\ifdim` arm and
    /// was refused, which is exactly how a document says "take the other
    /// branch". ยง494's `pass_text` needs the same resolution to count a nested
    /// conditional it is skipping over.
    /// The primitive a `\let` copy stands for, or the name itself.
    pub fn unaliased(&self, name: CsId) -> CsId {
        match self.meanings.get(&name) {
            Some(Meaning::Primitive(p)) => *p,
            _ => name,
        }
    }

    /// Whether `name` means the primitive `primitive` now: the primitive
    /// itself, never redefined, or a `\let` copy of it.
    pub fn means_primitive(&self, name: CsId, primitive: &str) -> bool {
        match self.meanings.get(&name) {
            Some(Meaning::Primitive(p)) => p.name() == primitive,
            None => name.name() == primitive,
            Some(_) => false,
        }
    }

    pub fn primitive_meaning(&self, name: CsId) -> CsId {
        match self.meanings.get(&name) {
            Some(Meaning::Primitive(p)) if *p != name => *p,
            _ => name,
        }
    }

    /// ยง367's `expand` of one token, for a caller outside the expander:
    /// whether `name` expanded (its expansion is then in front of the mouth).
    pub fn expand_once(&mut self, lx: &mut Lexer, name: CsId) -> R<bool> {
        self.try_expand(lx, name, false)
    }

    /// 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> {
        // ยง358: a `\noexpand`ed control sequence is `\relax` to the expander.
        if name.noexpand_origin().is_some() {
            return Ok(false);
        }
        // ยง370: a control sequence with no meaning is reported and expands to
        // nothing, wherever it is met in a scan that expands.
        if self.recover && self.is_undefined(name) {
            self.report(lx, "Undefined control sequence");
            return Ok(true);
        }
        if let Some(Meaning::Macro(_)) = self.meanings.get(&name) {
            self.expand_macro(lx, name, pending_only)?;
            return Ok(true);
        }
        let original = name;
        let name = self.primitive_meaning(name);
        // LuaTeX's expandable Lua primitives are `convert` commands: they
        // expand wherever the gullet reads -- inside `\csname`, an `\edef`, a
        // number -- and not only where the lowerer meets them at the top. What
        // a chunk assigns to a register reaches the program through `deferred`.
        if matches!(
            name.name(),
            "directlua" | "luadirect" | "luaescapestring" | "luafunction" | "luabytecode"
        ) || crate::lua::expands_in_gullet(name.name())
        {
            let mut cmds = Vec::new();
            let mut families = crate::typeset::Families::default();
            crate::lua::lower(self, lx, name.name(), &mut cmds, &mut families)?;
            self.deferred.extend(cmds);
            return Ok(true);
        }
        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)
            }
            // luatex's expand.c: "An experiment" -- `\ifcondition` read where
            // it expands is nothing at all; skipped text counts it as an `\if`.
            "ifcondition" => Ok(true),
            n if CONDITIONALS.contains(&n) => {
                self.do_conditional(lx, n, pending_only)?;
                Ok(true)
            }
            // ยง510: a branch that is running ends at the `\else` (or, for a
            // case, the `\or`) that follows it, and the rest to the `\fi` is
            // skipped. An `\else` after an `\else`, or an `\or` where no case
            // is running, is `if_limit` being too small: `Extra`, and ignored.
            "else" | "or" | "fi" if matches!(self.conds.last(), Some(CondState::Testing)) => {
                self.insert_relax(lx, original);
                Ok(true)
            }
            "else" => match self.conds.last() {
                Some(CondState::Taken | CondState::TakenCase) => {
                    self.close_cond();
                    self.skip_to(lx, false, pending_only)?;
                    Ok(true)
                }
                _ => Ok(self.extra_fi_or_else(lx, "else")),
            },
            "or" => match self.conds.last() {
                Some(CondState::TakenCase) => {
                    self.close_cond();
                    self.skip_to(lx, false, pending_only)?;
                    Ok(true)
                }
                _ => Ok(self.extra_fi_or_else(lx, "or")),
            },
            "fi" => match self.close_cond() {
                Some(_) => Ok(true),
                None => Ok(self.extra_fi_or_else(lx, "fi")),
            },
            "expandafter" => {
                self.do_expandafter(lx, pending_only)?;
                Ok(true)
            }
            // `\the` of a token register: the list is frontend state, so it
            // expands here as ยง465's `ins_the_toks` does. Any other quantity is
            // left for the context that reads it, since its value is the run's.
            "the" => match self.the_token_list(lx, pending_only)? {
                Some(list) => {
                    lx.push_back(&list);
                    Ok(true)
                }
                None => Ok(false),
            },
            // `\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) => self.sprint_cs(*n),
                        other => other.to_text(self.esc()),
                    };
                    lx.push_back(&str_toks(&text));
                }
                Ok(true)
            }
            // ยง367: the next token goes back as itself if it would not expand,
            // and as ยง358's `dont_expand` token -- `\relax` to whatever reads
            // it, the same control sequence to whatever stores it -- if it
            // would.
            "noexpand" => {
                if let Some(t) = self.take(lx, pending_only) {
                    let t = match t {
                        Token::Cs(n) if n.noexpand_origin().is_none() && self.is_expandable(n) => {
                            Token::Cs(n.noexpanded())
                        }
                        other => other,
                    };
                    // ยง367's `back_input`, so a context display shows it.
                    lx.back_input(&[t]);
                }
                Ok(true)
            }
            // `\jobname` is a `convert` primitive too (ยง470, ยง472): the job's name
            // as character tokens, which ยง464's `str_toks` makes category 12
            // except for a space, which stays a space.
            // `\romannumeral` (ยง470): the number in lowercase roman numerals,
            // as category-12 characters; zero and negatives produce nothing,
            // which is what makes `\romannumeral0` the expansion trigger it is.
            "romannumeral" => {
                let n = self.scan_number(lx, pending_only)?;
                let toks: Vec<Token> = roman_int(n)
                    .chars()
                    .map(|c| Token::Char(c, Cat::Other))
                    .collect();
                lx.push_back(&toks);
                Ok(true)
            }
            // `\fontname` (ยง470, ยง472): the name of the font the next token
            // identifies, as category-12 characters.
            "fontname" => {
                let name = self.fontname_text(lx, pending_only)?;
                lx.push_back(&str_toks(&name));
                Ok(true)
            }
            // The version strings e-TeX and LuaTeX expand to (`convert`
            // commands), as category-12 characters.
            n if constant_text(n).is_some() => {
                lx.push_back(&str_toks(constant_text(n).expect("just matched")));
                Ok(true)
            }
            "jobname" => {
                let toks: Vec<Token> = crate::lua::jobname()
                    .chars()
                    .map(|c| Token::Char(c, if c == ' ' { Cat::Space } else { Cat::Other }))
                    .collect();
                lx.push_back(&toks);
                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);
                    lx.push_back(&str_toks(&text));
                }
                Ok(true)
            }
            // etex.ch's `the_toks` for `show_tokens` (chr 2 of the `the`
            // command, ยง478 as e-TeX extends it): `\detokenize` reads a general
            // text and makes it characters. `\unexpanded` (chr 1) is the
            // general text itself; read where the gullet expands, as here, the
            // list goes back to be read like any other (ยง1381's
            // `ins_the_toks`). Inside an \edef the list is not expanded again,
            // which is `expand_edef_body`'s arm, not this one.
            "detokenize" => {
                let text = self.scan_general_text(lx)?;
                lx.push_back(&self.detokenized(&text));
                Ok(true)
            }
            "unexpanded" => {
                let text = self.scan_general_text(lx)?;
                lx.push_back(&text);
                Ok(true)
            }
            // luatex's `\expanded` (a `convert` command): the general text is
            // expanded as an \edef body is -- `scan_toks(false, true)` -- and
            // the result goes back into the input, where it is read, and
            // expanded, again. A `\noexpand` in the text protects a token
            // through the first expansion only.
            "expanded" => {
                let text = self.scan_general_text(lx)?;
                let expanded = self.expand_edef_body(&text)?;
                lx.push_back(&expanded);
                Ok(true)
            }
            "csname" => {
                let built = self.read_csname(lx, pending_only)?;
                // An undefined \csname name becomes \relax, per tex.web ยง372.
                let id = self
                    .named_cs(&built, true)
                    .expect("\\csname always makes one");
                // ยง372's `back_input`: an error in what reads it shows the
                // name as `<recently read>`.
                lx.back_input(&[Token::Cs(id)]);
                Ok(true)
            }
            // etex.ch's `\scantokens` (`pseudo_start`): the general text, written
            // as ยง295's `show_token_list` writes it, split into lines at the
            // `\newlinechar`, and read again as a file -- `\everyeof` at its
            // end. luatex's `\scantextokens` is the same with no line end
            // after the last line and nothing inserted at the end (measured).
            //
            // A context that reads only tokens already in hand -- an `\edef`
            // or `\message` body -- executes nothing while it reads, so no
            // `\catcode` can change under the text there and it is tokenised
            // whole, with the category codes now.
            "scantokens" | "scantextokens" => {
                let file = name.name() == "scantokens";
                let text = self.scan_general_text(lx)?;
                let src = self.pseudo_file_text(&text, file);
                let eof = match file {
                    true => self
                        .toks
                        .get(&crate::params::toks_register("everyeof").unwrap_or(-1))
                        .cloned()
                        .unwrap_or_default(),
                    false => Vec::new(),
                };
                match pending_only {
                    false => lx.begin_pseudo_file(&src, eof),
                    true => {
                        let mut read = Lexer::new(&src);
                        let mut toks = Vec::new();
                        while let Some(t) = read.next_token(&self.cats) {
                            toks.push(t);
                        }
                        toks.extend(eof);
                        lx.push_back(&toks);
                    }
                }
                Ok(true)
            }
            // luatex's `manufacture_csname(1)`: `\csname` that does not define
            // what it does not find, which then expands to nothing.
            "begincsname" => {
                let built = self.read_csname(lx, pending_only)?;
                if let Some(id) = self.named_cs(&built, false).filter(|_| !built.is_empty()) {
                    lx.back_input(&[Token::Cs(id)]);
                }
                Ok(true)
            }
            // `inject_last_tested_cs`: the name the last of them looked up.
            "lastnamedcs" => {
                if let Some(id) = self.last_cs_name {
                    lx.back_input(&[Token::Cs(id)]);
                }
                Ok(true)
            }
            // LuaTeX's backend: `\pdfvariable` expands to the parameter its key
            // names, `\pdffeedback` to what the backend knows.
            "pdfvariable" => {
                crate::backend::variable(self, lx)?;
                Ok(true)
            }
            "pdffeedback" => {
                crate::backend::feedback(self, lx)?;
                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 => {
                let t = lx.next_token(&self.cats);
                self.note_input_line(lx, t.as_ref());
                self.note_mouth(lx);
                t
            }
        }
    }

    /// Which of `fi`, `else` and `or` `name` means, when no conditional is open
    /// for it to end.
    pub fn stray_conditional_end(&self, name: CsId) -> Option<&'static str> {
        if !self.recover || !self.conds.is_empty() || name.noexpand_origin().is_some() {
            return None;
        }
        match self.primitive_meaning(name).name() {
            "fi" => Some("fi"),
            "else" => Some("else"),
            "or" => Some("or"),
            _ => None,
        }
    }

    /// ยง510's `Extra \fi`, `Extra \else` or `Extra \or`, reported.
    pub fn extra_conditional_end(&mut self, lx: &Lexer, kind: &str) {
        self.extra_fi_or_else(lx, kind);
    }

    /// ยง510: an `\else`, `\or` or `\fi` with no conditional open is reported
    /// and expands to nothing. Always `true`, the answer `try_expand` gives.
    fn extra_fi_or_else(&mut self, lx: &Lexer, name: &str) -> bool {
        let msg = format!("Extra {}{name}", self.esc());
        self.report(lx, &msg);
        true
    }

    /// `\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.
                // ยง368's `expand` of the token after next, whatever kind of
                // expandable command it is: `\number` and `\the` included,
                // which the contexts that read them otherwise answer.
                if !self.try_expand(lx, n, pending_only)?
                    && !self.the_or_number_expands(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);
        // ยง495's `if_line`: the line the conditional began on, before its
        // test is read.
        let line = lx.line();
        // ยง498 pushes the conditional before it reads the test, with
        // `if_limit=if_code`, so an `\or`, `\else` or `\fi` the test's own
        // scanning expands is ยง510's `insert_relax` rather than `Extra`.
        self.begin_test();
        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, "ifnum")?;
                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, "ifdim")?;
                let b = self.scan_dimen(lx, pending_only)?;
                match rel {
                    '<' => a < b,
                    '>' => a > b,
                    _ => a == b,
                }
            }
            // conditional.c's `if_abs_num_code` and `if_abs_dim_code`: each
            // side is negated if it is negative before the comparison.
            "ifabsnum" | "ifabsdim" => {
                let dimen = name == "ifabsdim";
                let a = match dimen {
                    true => self.scan_dimen(lx, pending_only)?,
                    false => self.scan_number(lx, pending_only)?,
                };
                let rel = self.read_relation(lx, pending_only, name)?;
                let b = match dimen {
                    true => self.scan_dimen(lx, pending_only)?,
                    false => self.scan_number(lx, pending_only)?,
                };
                match rel {
                    '<' => a.abs() < b.abs(),
                    '>' => a.abs() > b.abs(),
                    _ => a.abs() == b.abs(),
                }
            }
            // `is_in_csname`: true while a `\csname`, `\ifcsname` or
            // `\begincsname` is reading its name.
            "ifincsname" => self.in_csname > 0,
            // `if_primitive_code`: the next token, unexpanded, is a control
            // sequence whose meaning is still the primitive of its name.
            "ifprimitive" => match self.take(lx, pending_only) {
                Some(Token::Cs(n)) => self.means_its_primitive(n),
                _ => false,
            },
            "ifodd" => self.scan_number(lx, pending_only)? % 2 != 0,
            "ifdefined" => {
                let t = self.take(lx, pending_only);
                self.if_def_truth(t.as_ref())
            }
            // 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.named_cs(&built, false).is_some()
            }
            "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` compares CHARACTER CODES after expansion and `\ifcat`
            // CATEGORIES; see `if_operand` for what each operand reads as.
            "if" | "ifcat" => {
                let a = self.if_operand(lx, pending_only)?;
                let b = self.if_operand(lx, pending_only)?;
                Self::if_operands_match(name, 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"
            }
            // ยง501: true when the stream is closed, which every one is until
            // `\openin` finds a file and again once `\read` runs it out.
            "ifeof" => {
                let n = self.scan_stream_number(lx, pending_only)?;
                self.read_stream_closed(n)
            }
            "ifcase" => {
                let n = self.scan_number(lx, pending_only)?;
                return self.do_ifcase(lx, n, pending_only, line);
            }
            // ยง501: the mode the lowerer is following; `\ifinner` is
            // `mode<0`.
            "ifvmode" | "ifhmode" | "ifmmode" | "ifinner" if self.list_mode.is_some() => {
                self.mode_test(name)
            }
            other => return Err(TexError(format!("Unsupported conditional \\{other}"))),
        };
        let name = CONDITIONALS
            .iter()
            .find(|c| **c == name)
            .copied()
            .unwrap_or("if");
        self.enter_decided(lx, truth != negated, pending_only, (name, negated, line))
    }

    /// ยง498's `push_cond` with `if_limit=if_code`: a conditional whose test is
    /// being read. It stays on the condition stack, BELOW any conditional
    /// its test expanded and left open (expl3's `\if:w #4 \__..._base:N #2`
    /// does, by design), and is decided in place there by `enter_decided`.
    /// The lowerer reads the test of an `\ifnum` itself, and opens it through
    /// this too.
    pub fn begin_test(&mut self) {
        self.conds.push(CondState::Testing);
    }

    /// The test of the conditional most recently begun was read for a branch
    /// the RUN takes (the lowerer's run-time `\ifnum`), so it leaves the
    /// expander's stack; a message body's own conditionals do the same.
    pub fn end_test(&mut self) {
        if let Some(at) = self.testing_at() {
            self.conds.remove(at);
        }
    }

    /// Where the conditional whose test is being read sits.
    fn testing_at(&self) -> Option<usize> {
        self.conds
            .iter()
            .rposition(|c| matches!(c, CondState::Testing))
    }

    /// Where the description of `conds[at]` goes in `cond_info`, which holds
    /// one entry per decided conditional, in stack order, among the run-time
    /// arms the lowerer is in.
    fn info_slot(&self, at: usize) -> usize {
        let k = self.conds[..at]
            .iter()
            .filter(|c| !matches!(c, CondState::Testing))
            .count();
        self.cond_info
            .iter()
            .enumerate()
            .filter(|(_, c)| c.3.is_none())
            .nth(k)
            .map_or(self.cond_info.len(), |(i, _)| i)
    }

    /// ยง498's `change_if_limit` on the conditional at `at`: decided, it is
    /// now `state` (and described in `cond_info` from now on).
    fn settle_cond(&mut self, at: usize, state: CondState, info: (&'static str, bool, u32)) {
        let was_testing = matches!(self.conds[at], CondState::Testing);
        self.conds[at] = state;
        if was_testing {
            let slot = self.info_slot(at);
            self.cond_info.insert(slot, (info.0, info.1, info.2, None));
        }
    }

    /// ยง510's `insert_relax`: an `\or`, `\else` or `\fi` met while a test is
    /// still being read goes back, behind a `\relax` that ends whatever the
    /// test was scanning, and is read again once the test is decided.
    fn insert_relax(&mut self, lx: &mut Lexer, end: CsId) {
        let relax = Token::Cs(CsId::intern("relax").noexpanded());
        lx.back_input(&[relax, Token::Cs(end)]);
    }

    /// ยง498's ending, once the test is decided: a true test runs on into its
    /// own text and leaves the conditional open for its `\else` or `\fi`; a
    /// false one skips (ยง494's `pass_text`) to the `\else`, whose text then
    /// runs, or past the `\fi`.
    fn enter_decided(
        &mut self,
        lx: &mut Lexer,
        truth: bool,
        pending_only: bool,
        (name, negated, line): (&'static str, bool, u32),
    ) -> R<()> {
        let info = (name, negated, line);
        let at = match self.testing_at() {
            Some(at) => at,
            None => {
                self.conds.push(CondState::Testing);
                self.conds.len() - 1
            }
        };
        if truth {
            self.settle_cond(at, CondState::Taken, info);
            return Ok(());
        }
        self.settle_cond(at, CondState::Done, info);
        // ยง500's false test: skip, and at each `\else`, `\or` or `\fi` ask
        // whose it is. Ours when ours is the innermost open conditional: an
        // `\else` starts the text that runs, a `\fi` ends it all, an `\or`
        // is `Extra`. One a conditional the test left open owns is passed
        // over, its `\fi` closing it.
        loop {
            let stop = self.pass_text(lx, pending_only)?;
            if self.conds.len() == at + 1 {
                match stop {
                    Stop::Else => return Ok(()),
                    Stop::Fi => {
                        self.close_cond();
                        return Ok(());
                    }
                    Stop::Or => {
                        let msg = format!("Extra {}or", self.esc());
                        self.report(lx, &msg);
                    }
                }
            } else if matches!(stop, Stop::Fi) {
                self.close_cond();
            }
        }
    }

    fn close_cond(&mut self) -> Option<CondState> {
        if let Some(at) = self.cond_info.iter().rposition(|c| c.3.is_none()) {
            self.cond_info.remove(at);
        }
        self.conds.pop()
    }

    /// The lowerer is reading branch `branch` (1 the true text, -1 the
    /// `\else` text) of a conditional the run decides; until
    /// [`Self::leave_runtime_arm`] it counts as open for `\currentiflevel` and
    /// its siblings, as the conditional is open in tex while that text runs.
    pub fn enter_runtime_arm(
        &mut self,
        (name, negated, line): (&'static str, bool, u32),
        branch: i64,
    ) {
        self.cond_info.push((name, negated, line, Some(branch)));
    }

    pub fn leave_runtime_arm(&mut self) {
        if let Some(at) = self.cond_info.iter().rposition(|c| c.3.is_some()) {
            self.cond_info.remove(at);
        }
    }

    /// e-TeX's `\currentiflevel`, `\currentiftype` and `\currentifbranch`
    /// (etex.ch, luatex's numbering of the conditionals, measured): how many
    /// conditionals are open; the innermost one's code, negative under
    /// `\unless`; and whether its true text (1) or its `\else` text (-1) is
    /// running. The test of a conditional is read before it is entered here,
    /// so inside its own test the conditional does not count yet.
    fn current_if(&self, what: &str) -> i64 {
        let Some(&(name, negated, _, arm)) = self.cond_info.last() else {
            return 0;
        };
        match what {
            "currentiflevel" => self.cond_info.len() as i64,
            "currentiftype" => {
                let code = CONDITIONAL_CODES
                    .iter()
                    .position(|c| *c == Some(name))
                    .map_or(0, |i| i as i64 + 1);
                if negated {
                    -code
                } else {
                    code
                }
            }
            _ => match arm {
                Some(branch) => branch,
                None => match self.conds.last() {
                    Some(CondState::Done) => -1,
                    Some(_) => 1,
                    None => 0,
                },
            },
        }
    }

    /// ยง1335's note for each conditional `\end` found open, innermost first:
    /// `(\end occurred when \iftrue on line 2 was incomplete)`.
    pub fn open_conditional_notes(&self) -> Vec<String> {
        let e = self.esc();
        let luatex = self.is_luatex();
        self.cond_info
            .iter()
            .rev()
            .enumerate()
            .map(|(depth, (name, negated, line, _))| {
                // luatex 1.24.0 names only the innermost conditional; each
                // outer one prints as `\if` (measured): its `final_cleanup`
                // reads `cur_if` from the condition node's subtype, which does
                // not hold it.
                let (name, negated) = match luatex && depth > 0 {
                    true => ("if", &false),
                    false => (*name, negated),
                };
                let unless = match negated {
                    true => format!("{e}unless"),
                    false => String::new(),
                };
                let on = match line {
                    0 => String::new(),
                    n => format!(" on line {n}"),
                };
                format!("({e}end occurred when {unless}{e}{name}{on} was incomplete)")
            })
            .collect()
    }

    /// A conditional in running text whose test the LOWERER decided -- an
    /// `\ifnum` over registers whose values it has followed (`crate::known`).
    /// From here on it is the expander's like any other, so its `\else` and
    /// `\fi` are met on the one condition stack. `truth` already carries any
    /// `\unless`.
    pub fn enter_decided_file(
        &mut self,
        lx: &mut Lexer,
        truth: bool,
        opened_by: (&'static str, bool, u32),
    ) -> R<()> {
        self.enter_decided(lx, truth, false, opened_by)
    }

    /// `\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, line: u32) -> R<()> {
        let info = ("ifcase", false, line);
        let at = match self.testing_at() {
            Some(at) => at,
            None => {
                self.conds.push(CondState::Testing);
                self.conds.len() - 1
            }
        };
        if n == 0 {
            self.settle_cond(at, CondState::TakenCase, info);
            return Ok(());
        }
        self.settle_cond(at, CondState::Done, info);
        let mut remaining = n;
        while remaining != 0 {
            let stop = self.pass_text(lx, pending_only)?;
            // A boundary of a conditional the selector's scan left open is
            // passed over, its `\fi` closing it (ยง509's `cond_ptr<>save_cond_ptr`).
            if self.conds.len() != at + 1 {
                if matches!(stop, Stop::Fi) {
                    self.close_cond();
                }
                continue;
            }
            match stop {
                // 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 => return Ok(()),
                // The conditional ended before the case was reached.
                Stop::Fi => {
                    self.close_cond();
                    return Ok(());
                }
            }
        }
        self.conds[at] = CondState::TakenCase;
        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 };
            // ยง494 matches `cur_cmd`, which is the MEANING: `\let\ifx\iffalse`
            // is an `if_test` everywhere a spelt-out `\iffalse` is. Matching the
            // SPELLING counted no `\newif` switch, and LaTeX writes every one of
            // its own conditionals that way -- so `\if@compatibility \if@twocolumn
            // ... \else ... \fi \else` in size10.clo took the INNER `\else` as
            // the outer one's, and the outer `\else` was then `Extra \else`.
            let n = self.primitive_meaning(*n);
            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),
                _ => {}
            }
        }
    }

    /// ยง503: the relation of an `\ifnum` or `\ifdim` (`test`), the first
    /// non-blank token after expansion. It must be a `<`, `=` or `>` of
    /// category 12; anything else is `Missing = inserted`, put back to be
    /// read again, and the relation is `=`.
    fn read_relation(&mut self, lx: &mut Lexer, pending_only: bool, test: &str) -> R<char> {
        loop {
            let Some(t) = self.take(lx, pending_only) else {
                return Err(TexError(format!("Missing = inserted for \\{test}")));
            };
            match &t {
                t if self.is_spacer(t) => continue,
                Token::Char(c @ ('<' | '=' | '>'), Cat::Other) => return Ok(*c),
                Token::Cs(n) if self.try_expand(lx, *n, pending_only)? => continue,
                _ => {
                    lx.back_input(&[t]);
                    let msg = format!("Missing = inserted for {}{test}", self.esc());
                    self.report(lx, &msg);
                    return Ok('=');
                }
            }
        }
    }

    /// `\ifx` equality: same meaning, or the same character token.
    fn meanings_equal(&self, a: Option<&Token>, b: Option<&Token>) -> bool {
        match (a, b) {
            // ยง507: every `\noexpand`ed token is the one command (`\relax`, 257).
            (Some(Token::Cs(x)), Some(Token::Cs(y)))
                if x.noexpand_origin().is_some() || y.noexpand_origin().is_some() =>
            {
                x.noexpand_origin().is_some() && y.noexpand_origin().is_some()
            }
            (Some(Token::Cs(x)), Some(Token::Cs(y))) => {
                match (self.meanings.get(x), self.meanings.get(y)) {
                    // A name with no entry, or a `\let` copy of one, is the
                    // primitive of that name or undefined; two undefined names
                    // are the same command (ยง507 compares `undefined_cs` with
                    // itself), so `\ifx\a\b` over two of them is true while
                    // `\ifx\relax\undefined` is false.
                    (None | Some(Meaning::Primitive(_)), None | Some(Meaning::Primitive(_)))
                        if !self.is_primitive_name(self.unbound_name(*x))
                            || !self.is_primitive_name(self.unbound_name(*y)) =>
                    {
                        !self.is_primitive_name(self.unbound_name(*x))
                            && !self.is_primitive_name(self.unbound_name(*y))
                    }
                    (None, None) => x == y,
                    (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,
        }
    }

    /// One operand of `\if` or `\ifcat`, as `tex.web` ยง506 reads it: expand
    /// until an unexpandable token, then take its character code and its
    /// command. A control sequence `\let` to a character stands for that
    /// character -- `\let\x=a` makes `\if\x a` true -- and any other one reads
    /// as code 256 and command `\relax`, which `None` stands for here, so every
    /// such control sequence compares equal to every other.
    fn if_operand(&mut self, lx: &mut Lexer, pending_only: bool) -> R<(u32, Option<Cat>)> {
        loop {
            let Some(t) = self.take(lx, pending_only) else {
                return Err(TexError("Missing token for \\if".into()));
            };
            // An active character is a control sequence in every way that
            // matters here: ยง506's `get_x_token_or_active_char` expands it if
            // it is a macro, and otherwise takes what it MEANS. One with no
            // meaning stays the active character it is.
            let t = match t {
                Token::Char(c, Cat::Active) => match self.active_meaning(c) {
                    Some(id) => Token::Cs(id),
                    None => t,
                },
                _ => t,
            };
            match &t {
                Token::Char(c, cat) => return Ok((*c as u32, Some(*cat))),
                // ยง358: `\noexpand` turns an EXPANDABLE token into one that
                // means `\relax` (and ยง506 then makes an active character the
                // character it is); an unexpandable one is unaffected.
                Token::Cs(n) if self.primitive_meaning(*n).name() == "noexpand" => {
                    let Some(next) = self.take(lx, pending_only) else {
                        return Err(TexError("Missing token for \\if".into()));
                    };
                    return Ok(match next {
                        Token::Char(c, Cat::Active) => match self.active_meaning(c) {
                            Some(id) if !self.is_expandable(id) => self.cs_operand(id),
                            _ => (c as u32, Some(Cat::Active)),
                        },
                        Token::Char(c, cat) => (c as u32, Some(cat)),
                        Token::Cs(m) => self.cs_operand(m),
                    });
                }
                Token::Cs(n) => {
                    let n = *n;
                    if self.try_expand(lx, n, pending_only)? {
                        continue;
                    }
                    return Ok(self.cs_operand(n));
                }
            }
        }
    }

    /// What an unexpanded control sequence is to `\if` and `\ifcat` (ยง506): a
    /// `\let` copy of a character is that character, and anything else is
    /// `\relax` with code 256.
    fn cs_operand(&self, name: CsId) -> (u32, Option<Cat>) {
        match self.meanings.get(&name) {
            Some(Meaning::Char(c, cat)) => (*c as u32, Some(*cat)),
            _ => (256, None),
        }
    }

    /// Whether `name` would expand (ยง366): a macro, an expandable primitive,
    /// or a name with no meaning at all, which tex expands to report it.
    pub fn is_expandable(&self, name: CsId) -> bool {
        // A `token.set_lua` name without "protected" expands like `\directlua`.
        if crate::lua::expands_in_gullet(name.name()) {
            return true;
        }
        match self.meanings.get(&name) {
            Some(Meaning::Macro(_)) => true,
            Some(Meaning::Primitive(p)) => Self::expandable_primitive(p.name()),
            None => !self.is_primitive_name(name) || Self::expandable_primitive(name.name()),
            Some(_) => false,
        }
    }

    /// The primitive `name` is a `\let` copy of, when that primitive expands;
    /// `name` itself otherwise. A scanner that dispatches on names asks this
    /// first, so `\let\foo\detokenize` makes `\foo` the primitive where it
    /// expands, as tex's `cur_cmd` makes it.
    pub fn expandable_alias(&self, name: CsId) -> CsId {
        match self.meanings.get(&name) {
            Some(Meaning::Primitive(p)) if *p != name && Self::expandable_primitive(p.name()) => *p,
            _ => name,
        }
    }

    fn expandable_primitive(name: &str) -> bool {
        CONDITIONALS.contains(&name) || crate::primitives::expands(name)
    }

    /// ยง507: `\if` decides on the codes, `\ifcat` on the commands.
    fn if_operands_match(name: &str, a: (u32, Option<Cat>), b: (u32, Option<Cat>)) -> bool {
        match name {
            "ifcat" => a.1 == b.1,
            _ => a.0 == b.0,
        }
    }

    /// `\if`/`\ifcat` for a `\message` body, which reads its tokens pending:
    /// whether the two operands match.
    pub fn if_pending(&mut self, work: &mut Lexer, name: &str) -> R<bool> {
        let a = self.if_operand(work, true)?;
        let b = self.if_operand(work, true)?;
        Ok(Self::if_operands_match(name, a, b))
    }

    // โ”€โ”€ definitions โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    /// `tex.web` ยง448's leading signs: any number of `+` and `-` in any order,
    /// spaces between them, and an odd count of minus signs is a negative.
    ///
    /// Split from the digits because ยง449 looks for an INTERNAL dimension
    /// between the two -- `-\p@` is a sign and a whole dimension with no digits
    /// anywhere in it. The token that ends the run goes back.
    fn scan_optional_signs(&mut self, lx: &mut Lexer, pending_only: bool) -> R<i64> {
        let mut sign = 1i64;
        loop {
            let Some(t) = self.take(lx, pending_only) else {
                return Err(TexError("Missing number, treated as zero".into()));
            };
            match &t {
                t if self.is_spacer(t) => continue,
                Token::Char('-', _) => sign = -sign,
                Token::Char('+', _) => {}
                other => {
                    lx.push_back(std::slice::from_ref(other));
                    return Ok(sign);
                }
            }
        }
    }

    /// ยง452's `<factor>`: an integer part and a fraction already scaled to
    /// 65536ths, with the sign already off the stream.
    fn scan_factor(&mut self, lx: &mut Lexer, pending_only: bool) -> R<(i64, i64)> {
        let Some(mut cur) = self.take(lx, pending_only) else {
            return Ok((0, 0));
        };
        // 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,
                // ยง455 reads the factor's tokens with `get_x_token`, so a
                // control sequence EXPANDS here instead of surviving into the
                // unit scan. With `\def\ff{.7}`, `\ff\bbb` is the same
                // dimension `.7\bbb` is; without the expansion the `\ff`
                // reaches the unit scan, which spells no letters out of a
                // control sequence and reports ยง454's illegal unit.
                //
                // One that will NOT expand ends the factor exactly as any
                // other non-digit does, and goes back untouched for ยง453's
                // `<internal unit>` -- that is how `10\p@` still works.
                Token::Cs(n) => {
                    let n = *n;
                    if !self.try_expand(lx, n, pending_only)? {
                        lx.back_input(std::slice::from_ref(&cur));
                        break;
                    }
                }
                other => {
                    lx.back_input(std::slice::from_ref(other));
                    break;
                }
            }
            match self.take(lx, pending_only) {
                Some(t) => cur = t,
                None => break,
            }
        }
        // ยง448: a factor that does not open with a digit or a point is read
        // by ยง440's `scan_int` -- a `"`, `'` or `` ` `` constant, or ยง446's
        // missing number for anything else. What ended the scan above was put
        // back, so `scan_number` reads it again.
        if whole.is_empty() && !seen_point {
            return Ok((self.scan_number(lx, pending_only)?, 0));
        }
        let int: i64 = whole.parse().unwrap_or(0);
        Ok((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.
    ///
    /// `em` and `ex` are NOT here, and the reason is the order ยง453 reads its
    /// units in: `scan_font_unit` is ยง455 and runs ahead of `true` and of every
    /// spelling this table holds.
    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),
        }
    }

    /// `tex.web` ยง455's second half: `em` and `ex`, and the optional space
    /// after one. `None`, with nothing consumed, when neither is there.
    ///
    /// Its POSITION is as load-bearing as its arithmetic. ยง455 runs before
    /// ยง453 reaches `true`, and before `pt`, so `1true em` is not a dimension
    /// at all: `true` comes off the stream and then the physical units are
    /// tried against `em`, none matches, and the scan stops. Measured, on
    /// `tex` 3.141592653 --
    ///
    /// ```text
    /// ! Illegal unit of measure (pt inserted).
    /// l.16 \dimen0=1true e
    ///                     m
    /// ```
    ///
    /// -- so putting this after the `true` keyword would accept a dimension the
    /// reference engine refuses. `mu` mode skips it outright, which is ยง455's
    /// own `if mu then goto not_found`.
    ///
    /// Unlike every other unit the factor is not CONVERTED but multiplied:
    /// ยง455 finishes with `nx_plus_y(save_cur_val,v,xn_over_d(v,f,0200000))`,
    /// which is `dimen::scale_by_factor` and is the same product ยง453 forms
    /// with an internal dimension. That is why `.5em` is half a quad and not
    /// half a scaled point.
    fn scan_font_unit(&mut self, lx: &mut Lexer, pending_only: bool) -> R<Option<i64>> {
        if self.mu_units {
            return Ok(None);
        }
        let v = match self.scan_keyword(lx, "em", pending_only)? {
            true => self.font_units(lx).quad,
            false => match self.scan_keyword(lx, "ex", pending_only)? {
                true => self.font_units(lx).x_height,
                false => return Ok(None),
            },
        };
        // ยง455's own "Scan an optional space", which every finite unit gets.
        if let Some(t) = self.take(lx, pending_only) {
            if !self.is_spacer(&t) {
                lx.push_back(std::slice::from_ref(&t));
            }
        }
        Ok(Some(v))
    }

    /// The two parameters ยง455 reads out of `font_info`, for the font in force.
    ///
    /// The font in force is `cmr10` at its design size, and that is a statement
    /// about this engine rather than a default: the mouth has no font-selection
    /// primitive at all -- there is no `\font`, no `\fontdimen`, no
    /// `\selectfont` -- so one font is in force for the whole run, and
    /// `typeset.rs` sets every document in `cmr10` whatever its class options
    /// said. Nothing is invented: both numbers come out of the installed
    /// `cmr10.tfm` through ยง571's own arithmetic.
    ///
    /// It is also the right font for the case this was built for. Measured with
    /// `latex` on `\documentclass{article}`: `\the\font` in the preamble is
    /// `\OT1/cmr/m/n/10`, `\the\fontdimen6\font` is `10.00002pt` and
    /// `\the\fontdimen5\font` is `4.30554pt` -- so every `em` article.cls
    /// writes is cmr10's, and so is every `em` in a fontspec document's class
    /// file, because `\setmainfont` comes after `\documentclass`.
    ///
    /// Where it is NOT right, and both are measured rather than guessed:
    ///   * `\documentclass[12pt]` puts cmr12 in force by the end of the class,
    ///     where `\the\fontdimen6\font` is `11.74988pt`. Reaching that would
    ///     take a type size the preamble is preloaded before this engine knows
    ///     (`\documentclass` is lowered after `latex::preamble` has already
    ///     run) AND a typesetter that sets in cmr12, which this one does not.
    ///   * `\setmainfont{Helvetica}` makes `1em` `10.0pt` and `1ex` `5.20996pt`
    ///     in xelatex -- the at-size, and OS/2's `sxHeight` over the head
    ///     table's `unitsPerEm`. That needs a current font in the mouth, which
    ///     is the thing this engine has not got.
    fn font_units(&mut self, lx: &Lexer) -> crate::tfm::FontUnits {
        if let Some(f) = self.font_units {
            return f;
        }
        let f = crate::tfm::FontUnits::of_tfm(TEXT_FONT, TEXT_FONT_AT);
        if f.is_none() {
            // ยง561's message for a font that will not load, reported once and
            // not once per `em`, because tex reports it where the font is
            // loaded and then measures with `null_font` (ยง552) for the rest of
            // the run. The control sequence tex names in front of it is left
            // out: this engine binds no name to the font, and writing one would
            // be reporting a `\font` command that was never given.
            self.report(
                lx,
                &format!("Font {TEXT_FONT} not loadable: Metric (TFM) file not found"),
            );
        }
        let f = f.unwrap_or(crate::tfm::FontUnits::NULL);
        self.font_units = Some(f);
        f
    }

    /// The unit ยง456 (`mu`) or ยง458 (`pt` and the rest) reads, as keywords in
    /// tex's order. None there is ยง459's `Illegal unit of measure`, reported
    /// with what ended the scan put back, and the unit inserted in its place.
    fn scan_physical_unit(&mut self, lx: &mut Lexer, pending_only: bool) -> R<&'static str> {
        let units: &[&'static str] = match self.mu_units {
            true => &["mu"],
            false => &["pt", "in", "pc", "cm", "mm", "bp", "dd", "cc", "sp"],
        };
        for unit in units {
            if self.scan_keyword(lx, unit, pending_only)? {
                return Ok(unit);
            }
        }
        let inserted = units[0];
        self.report(
            lx,
            &format!("Illegal unit of measure ({inserted} inserted)"),
        );
        Ok(inserted)
    }

    /// ยง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()),
        }
    }

    /// `tex.web` ยง455's `<internal unit>`: the register a factor scales, if a
    /// register is what stands where the unit would.
    ///
    /// Nothing is consumed when it is not, so the unit scan that follows sees an
    /// untouched stream -- `10pt` must still read as ten points after this has
    /// looked at the `p`. `lower.rs`'s `peek_glue_register` is the same
    /// save-and-restore, one position further out.
    ///
    /// ยง455 reads the internal value at the level the scanner is in: a `mu`
    /// scan takes a math glue and a dimension scan takes a dimension or the
    /// natural width of a glue (ยง430's coercion). Mixing them is `mu_error` in
    /// tex, and is simply not a unit here -- the caller then reports ยง454's
    /// illegal unit, which is what tex's recovery leaves behind anyway.
    ///
    /// ยง455 asks for the next "non-blank non-call" token and ยง449 for the next
    /// "non-blank non-sign" one, and both phrases mean `get_x_token`: a macro
    /// standing here EXPANDS, and what it expands to is what is looked at. That
    /// is what makes `\baselineskip\baselinestretch\baselineskip` the identity
    /// LaTeX relies on -- article.cls:116 leaves `\baselinestretch` EMPTY, so
    /// the register is the first thing the scan really sees and ยง449 takes it
    /// as the whole dimension. Without the expansion the empty macro ended the
    /// number instead, the factor was no digits at all, and the assignment
    /// zeroed the very register it was copying.
    fn peek_internal_unit(&mut self, lx: &mut Lexer, pending_only: bool) -> R<Option<i64>> {
        let mut eaten = Vec::new();
        loop {
            let Some(t) = self.take(lx, pending_only) else {
                lx.push_back(&eaten);
                return Ok(None);
            };
            if self.is_spacer(&t) {
                eaten.push(t);
                continue;
            }
            // An expandable name is not the answer either way: what it expands
            // to is read next, and an expansion that produced nothing leaves
            // the scan looking straight past it. A register -- spelt `\dimen`
            // or bound by `\dimendef` -- does not expand, so the test below
            // still sees it.
            if let Token::Cs(n) = &t {
                if self.try_expand(lx, *n, pending_only)? {
                    continue;
                }
            }
            if let Token::Cs(n) = &t {
                let spelt = crate::compiler::RegFile::of_name(n.name())
                    .filter(|f| *f != crate::compiler::RegFile::Count);
                // `\wd n`, `\ht n`, `\dp n` (ยง420) and the stomach's internal
                // dimensions (ยง424) are slots the program writes
                // (`crate::stomach::Mirror`), so they are internal units too.
                let stomach = match n.name() {
                    "wd" | "ht" | "dp" => {
                        let which = match n.name() {
                            "wd" => crate::stomach::BoxDimen::Wd,
                            "ht" => crate::stomach::BoxDimen::Ht,
                            _ => crate::stomach::BoxDimen::Dp,
                        };
                        let b = self.scan_register_any(lx, pending_only)?;
                        Some(crate::stomach::box_dimen_slot(b as u16, which))
                    }
                    other => crate::stomach::Internal::of_name(other)
                        .filter(|i| i.is_dimen())
                        .map(|i| i.slot()),
                };
                if let Some(reg) = stomach {
                    if !self.mu_units {
                        return Ok(Some(reg));
                    }
                }
                let reg = match spelt {
                    Some(file) => Some(self.scan_register_slot(lx, pending_only, file)?),
                    // A `\dimendef`, `\skipdef` or `\muskipdef` name is the
                    // register it was given, in every position the spelt-out
                    // form works -- and `10\p@` is that position.
                    None => match self.numeric_cs(*n) {
                        Some(NumericCs::Register(r)) if !crate::compiler::is_count_slot(r) => {
                            Some(r)
                        }
                        _ => None,
                    },
                };
                if let Some(reg) = reg {
                    let is_mu = crate::compiler::is_mu_slot(reg);
                    if is_mu == self.mu_units {
                        return Ok(Some(reg));
                    }
                }
            }
            eaten.push(t);
            lx.push_back(&eaten);
            return Ok(None);
        }
    }

    /// 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.
    ///
    /// A caller that reads an `i64` has nowhere to put ยง453's other shape, so
    /// `10\p@` is ยง454's illegal unit here exactly as it was before the shape
    /// existed. `scan_dimen_parts` is the same scan for a caller that can carry
    /// the product.
    pub fn scan_dimen(&mut self, lx: &mut Lexer, pending_only: bool) -> R<i64> {
        let parts = self.scan_dimen_parts(lx, pending_only)?;
        self.dimen_value(lx, parts)
    }

    /// ยง453's product, when the internal quantities in it are registers whose
    /// values [`crate::known`] has followed: `10\p@` is ten of whatever `\p@`
    /// holds now. ยง455's `attach_sign` reports a product out of range as
    /// `Dimension too large` and goes on with the largest dimension, which is
    /// what the run's own `b_scale_dimen` does with the same numbers.
    fn dimen_value(&mut self, lx: &Lexer, parts: crate::dimen::ScannedDimen) -> R<i64> {
        use crate::dimen::{CountUnit, ScannedDimen};
        let (int, frac, unit) = match parts {
            ScannedDimen::Constant(v) => return Ok(v),
            ScannedDimen::Scaled { int, frac, reg } => (int, frac, self.count_value(reg)?),
            ScannedDimen::ByCount { factor, sign, unit } => {
                let unit = match unit {
                    CountUnit::Register(r) => self.count_value(r)?,
                    CountUnit::Points(sp) => sp,
                };
                let factor = self.count_value(factor)?;
                (if sign < 0 { -factor } else { factor }, 0, unit)
            }
        };
        // The site was recorded for the lowerer, which carries a product it
        // cannot form to the run; this one is formed here, so it is spent.
        self.scaling_sites.pop_back();
        match crate::dimen::scale_by_factor_checked(int, frac, unit) {
            Ok(v) => Ok(v),
            Err(clamped) => {
                self.report(lx, "Dimension too large");
                Ok(clamped)
            }
        }
    }

    /// `scan_dimen`, with ยง453's `<factor><internal unit>` carried out whole
    /// rather than collapsed to a number.
    pub fn scan_dimen_parts(
        &mut self,
        lx: &mut Lexer,
        pending_only: bool,
    ) -> R<crate::dimen::ScannedDimen> {
        let d = self.scan_dimen_parts_inner(lx, pending_only)?;
        self.note_scaling(lx, &d);
        Ok(d)
    }

    /// Where ยง455 would find a product `Dimension too large`: right after the
    /// dimension that holds it has been read. Kept for the lowerer, which
    /// carries it to the run (see `Lowerer::note_scaling_site`).
    fn note_scaling(&mut self, lx: &Lexer, d: &crate::dimen::ScannedDimen) {
        if matches!(
            d,
            crate::dimen::ScannedDimen::Scaled { .. } | crate::dimen::ScannedDimen::ByCount { .. }
        ) {
            let site = self.error_context(lx);
            self.scaling_sites.push_back(site);
        }
    }

    /// The context display kept for the oldest product not yet claimed.
    pub fn next_scaling_site(&mut self) -> Option<String> {
        self.scaling_sites.pop_front()
    }

    /// Forget products no one claimed, before a scan whose products will be.
    pub fn clear_scaling_sites(&mut self) {
        self.scaling_sites.clear();
    }

    fn scan_dimen_parts_inner(
        &mut self,
        lx: &mut Lexer,
        pending_only: bool,
    ) -> R<crate::dimen::ScannedDimen> {
        use crate::dimen::ScannedDimen;
        // `\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 self.unaliased(*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)
                    .map(ScannedDimen::Constant);
            }
        }
        let sign = self.scan_optional_signs(lx, pending_only)?;
        // ยง465: `\the` of a dimension register writes it as ยง103 prints it,
        // the digits and `pt`, which ยง448 reads back as the same scaled points
        // -- the register, whole, and ยง453's optional space after its unit.
        if let Some(reg) = self.take_expanded_register(lx, pending_only)? {
            let dimension = !crate::compiler::is_count_slot(reg.slot)
                && !crate::compiler::is_glue_slot(reg.slot);
            if reg.the && dimension {
                if let Some(t) = self.take(lx, pending_only) {
                    if !self.is_spacer(&t) {
                        lx.push_back(std::slice::from_ref(&t));
                    }
                }
                return Ok(ScannedDimen::Scaled {
                    int: sign,
                    frac: 0,
                    reg: reg.slot,
                });
            }
            self.put_back(lx, reg);
        }
        // ยง449: an internal dimension standing where the NUMBER goes is the
        // whole dimension. `\@plus\p@` in size10.clo is one `\p@` and not none
        // of it, which is a factor of exactly one.
        if let Some(reg) = self.peek_internal_unit(lx, pending_only)? {
            return Ok(ScannedDimen::Scaled {
                int: sign,
                frac: 0,
                reg,
            });
        }
        // ยง449's `or fetch an internal integer': what stands where the factor
        // goes may be an internal INTEGER, and then it IS the factor and the
        // unit scan goes on behind it. A count register's value is a slot, so
        // the product has to wait; a `\chardef`'d constant is a number and
        // needs nothing new.
        let internal = self.peek_internal_int(lx, pending_only)?;
        let by_count = match internal {
            Some(NumericCs::Register(r)) => Some(r),
            _ => None,
        };
        let (int, frac) = match internal {
            // A register's value is not here yet, so the written factor is left
            // at one and the register carries the whole of it.
            Some(NumericCs::Register(_)) => (1, 0),
            Some(NumericCs::Value(v)) => (v, 0),
            None => self.scan_factor(lx, pending_only)?,
        };
        // ยง453 looks for an internal dimension BEFORE `true` and before any
        // spelt-out unit: `10\p@` is ten of whatever `\p@` holds, and no letter
        // of a unit has been read yet when it is found.
        if let Some(reg) = self.peek_internal_unit(lx, pending_only)? {
            // The sign rides on both halves of the factor. ยง453 negates the
            // whole product at `attach_sign` and ยง107 truncates toward zero, so
            // negating the factor instead gives the same integer.
            return Ok(match by_count {
                Some(factor) => ScannedDimen::ByCount {
                    factor,
                    sign,
                    unit: crate::dimen::CountUnit::Register(reg),
                },
                None => ScannedDimen::Scaled {
                    int: sign * int,
                    frac: sign * frac,
                    reg,
                },
            });
        }
        // ยง455's other half, in ยง455's own place: `em` and `ex` are settled
        // here, ahead of `true` and of every physical unit. Unlike an internal
        // dimension the value IS known -- it is a number a font file states, not
        // a VM slot -- so the product is formed now and a constant comes back.
        if let Some(v) = self.scan_font_unit(lx, pending_only)? {
            return Ok(match by_count {
                Some(factor) => ScannedDimen::ByCount {
                    factor,
                    sign,
                    unit: crate::dimen::CountUnit::Points(v),
                },
                // ยง455's `nx_plus_y` raises ยง460's error rather than clamping
                // quietly, so the product is formed whole and range-checked.
                None => {
                    let sp = int
                        .saturating_mul(v)
                        .saturating_add(crate::dimen::xn_over_d(v, frac, crate::dimen::UNITY));
                    ScannedDimen::Constant(sign * self.in_dimen_range(lx, sp))
                }
            });
        }
        // `tex.web` ยง453 takes an optional `true` in front of the unit, and
        // ยง457 divides the factor by the magnification ratio before the unit
        // converts it -- integer part and fraction, with the remainder carried.
        let (mut int, mut frac) = (int, frac);
        if self.scan_keyword(lx, "true", pending_only)? {
            let mag = self.prepare_mag(lx);
            if mag != 1000 {
                if by_count.is_some() {
                    return Err(TexError(
                        "Unsupported `true' unit after a count register under \\mag".into(),
                    ));
                }
                let whole = int * 1000;
                int = whole / mag;
                let f = (1000 * frac + crate::dimen::UNITY * (whole % mag)) / mag;
                int += f / crate::dimen::UNITY;
                frac = f % crate::dimen::UNITY;
            }
        }
        // ยง456 and ยง458: each unit is a keyword, tried in tex's order, so a
        // token that ends no unit is put back by the last `scan_keyword` and
        // ยง459 reports it -- and then goes on in points (or `mu`), as if
        // the unit had been written.
        let unit = self.scan_physical_unit(lx, pending_only)?;
        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 !self.is_spacer(&t) {
                lx.back_input(std::slice::from_ref(&t));
            }
        }
        Ok(match by_count {
            // `sp` is ONE of the unit, because the factor stood in a register
            // and `int` was left at one for it.
            Some(factor) => ScannedDimen::ByCount {
                factor,
                sign,
                unit: crate::dimen::CountUnit::Points(sp),
            },
            None => ScannedDimen::Constant(sign * self.in_dimen_range(lx, sp)),
        })
    }

    /// ยง460: a dimension of 16384pt or more is `Dimension too large`, reported
    /// where the scan stopped and replaced by `max_dimen`.
    fn in_dimen_range(&mut self, lx: &Lexer, sp: i64) -> i64 {
        if sp.abs() <= crate::dimen::MAX_DIMEN {
            return sp;
        }
        self.report(lx, "Dimension too large");
        crate::dimen::MAX_DIMEN
    }

    /// ยง288's `prepare_mag`, which every `true` unit runs first: `\mag` may not
    /// change once a true dimension has used it, and must be 1 to 32768.
    fn prepare_mag(&mut self, lx: &Lexer) -> i64 {
        let mag = self.intpars.get(crate::intpar::MAG);
        if self.mag_set > 0 && mag != self.mag_set {
            self.report(
                lx,
                &format!(
                    "Incompatible magnification ({mag}); the previous value will be retained ({})",
                    self.mag_set
                ),
            );
            self.set_intpar_globally(crate::intpar::MAG, self.mag_set);
        }
        let mag = self.intpars.get(crate::intpar::MAG);
        if mag <= 0 || mag > 32768 {
            self.report(
                lx,
                &format!("Illegal magnification has been changed to 1000 ({mag})"),
            );
            self.set_intpar_globally(crate::intpar::MAG, 1000);
        }
        self.mag_set = self.intpars.get(crate::intpar::MAG);
        self.mag_set
    }

    /// ยง577's `scan_font_ident` and ยง472's `font_name_code`: the name of the font
    /// the next non-blank, non-call token identifies.
    ///
    /// The identifiers are `\nullfont`, `\font` (the current font), a name
    /// `\font` defined (ยง1257), and the three family tables, whose entries are
    /// `\nullfont` until a `\textfont` assignment fills one -- which texrs does
    /// not make yet. Anything else is `Missing font identifier`, read again,
    /// and `\nullfont` used. The answer is ยง472's: the file name, and ` at
    /// Xpt` when the font is not at its design size.
    pub fn fontname_text(&mut self, lx: &mut Lexer, pending_only: bool) -> R<String> {
        let tok = loop {
            let Some(t) = self.take(lx, pending_only) else {
                return Err(TexError("Missing font identifier".into()));
            };
            match t {
                t if t.is_space() => continue,
                Token::Cs(n) if self.try_expand(lx, n, pending_only)? => continue,
                t => break t,
            }
        };
        let mut font = 0u16;
        let family = match tok {
            Token::Cs(n) if matches!(self.meanings.get(&n), Some(Meaning::Font(_))) => {
                if let Some(Meaning::Font(f)) = self.meanings.get(&n) {
                    font = *f;
                }
                false
            }
            Token::Cs(n) => match self.primitive_meaning(n).name() {
                "font" => {
                    font = self.cur_font;
                    false
                }
                "nullfont" => false,
                "textfont" | "scriptfont" | "scriptscriptfont" => true,
                _ => {
                    lx.back_input(&[tok]);
                    self.report(lx, "Missing font identifier");
                    false
                }
            },
            Token::Char(..) => {
                lx.back_input(&[tok]);
                self.report(lx, "Missing font identifier");
                false
            }
        };
        if family {
            let size = match tok {
                Token::Cs(n) => match self.primitive_meaning(n).name() {
                    "textfont" => 0,
                    "scriptfont" => 1,
                    _ => 2,
                },
                Token::Char(..) => 0,
            };
            let fam = self.scan_stream_number(lx, pending_only)?;
            font = self.fam_fonts[size][fam & 15];
        }
        Ok(self.fonts.describe(font))
    }

    /// The slot a register reference names, reading the register number after
    /// `\count`, `\dimen`, `\skip` or `\muskip`; `None`, with nothing consumed,
    /// when `name` is not one. The reference comes back respelt as well -- the
    /// name, then the number read and the space that ends it -- for a caller
    /// that has to put it back.
    pub fn register_slot(
        &mut self,
        lx: &mut Lexer,
        name: CsId,
        pending_only: bool,
    ) -> R<Option<(i64, Vec<Token>)>> {
        let file = crate::compiler::RegFile::of_name(name.name());
        let mut spelt = vec![Token::Cs(name)];
        // A box dimension is three slots per register (`crate::stomach`).
        if let Some(which) = match name.name() {
            "wd" => Some(crate::stomach::BoxDimen::Wd),
            "ht" => Some(crate::stomach::BoxDimen::Ht),
            "dp" => Some(crate::stomach::BoxDimen::Dp),
            _ => None,
        } {
            let reg = self.scan_register_any(lx, pending_only)?;
            spelt.extend(reg.to_string().chars().map(|c| Token::Char(c, Cat::Other)));
            spelt.push(Token::Char(' ', Cat::Space));
            return Ok(Some((
                crate::stomach::box_dimen_slot(reg as u16, which),
                spelt,
            )));
        }
        // ยง413's internal quantities the stomach computes are slots it writes.
        // `\outputpenalty` is left to the integer parameters.
        if let Some(i) = crate::stomach::Internal::of_name(name.name()) {
            if i != crate::stomach::Internal::OutputPenalty
                && i != crate::stomach::Internal::LastSkip
            {
                return Ok(Some((i.slot(), spelt)));
            }
        }
        let mut spelt = vec![Token::Cs(name)];
        if let Some(file) = file {
            let reg = self.scan_register_number(lx, pending_only)?;
            spelt.extend(reg.to_string().chars().map(|c| Token::Char(c, Cat::Other)));
            spelt.push(Token::Char(' ', Cat::Space));
            return Ok(Some((self.register_address(file, reg)?, spelt)));
        }
        // A `\countdef`, `\dimendef`, `\skipdef` or `\muskipdef` name is that
        // register, in every position the spelt-out form works.
        match self.numeric_cs(name) {
            Some(NumericCs::Register(r)) => Ok(Some((r, spelt))),
            _ => Ok(None),
        }
    }

    /// `\the` or `\number` and the register after it; `None`, with nothing
    /// consumed, when that is not what comes next.
    ///
    /// Both are expandable (ยง465, ยง470), so where a number, a dimension or a
    /// glue is scanned the scan reads the characters they produce. Those are
    /// the register's value written out, and ยง103's `print_scaled` writes a
    /// dimension so that reading it back gives the same scaled points -- so
    /// what the scan makes of them is, in most positions, the register itself,
    /// a slot whose value is the run's. Which positions is the caller's
    /// question: it has the next tokens to look at, and [`Self::put_back`]
    /// undoes the read when the characters would not be the register alone.
    pub fn take_expanded_register(
        &mut self,
        lx: &mut Lexer,
        pending_only: bool,
    ) -> R<Option<ExpandedRegister>> {
        let Some(prefix) = self.take(lx, pending_only) else {
            return Ok(None);
        };
        let the = match &prefix {
            Token::Cs(n) if n.name() == "the" => true,
            Token::Cs(n) if n.name() == "number" => false,
            _ => {
                lx.push_back(&[prefix]);
                return Ok(None);
            }
        };
        let Some(name) = self.take(lx, pending_only) else {
            lx.push_back(&[prefix]);
            return Ok(None);
        };
        let Token::Cs(cs) = name else {
            lx.push_back(&[prefix, name]);
            return Ok(None);
        };
        match self.register_slot(lx, cs, pending_only)? {
            Some((slot, spelt)) => {
                let mut read = vec![prefix];
                read.extend(spelt);
                Ok(Some(ExpandedRegister { the, slot, read }))
            }
            None => {
                lx.push_back(&[prefix, name]);
                Ok(None)
            }
        }
    }

    /// Undo [`Self::take_expanded_register`]: the prefix and the register go
    /// back as they were read, for the scanner to read as characters.
    pub fn put_back(&self, lx: &mut Lexer, reg: ExpandedRegister) {
        lx.push_back(&reg.read);
    }

    /// Whether the next token, which stays where it is, is a character that
    /// ยง445's digit loop or ยง452's decimal fraction would go on reading into
    /// the number in front of it.
    ///
    /// Both read with `get_x_token`, so a macro there is expanded to see what
    /// it begins with, as the scan itself would. Only a macro: a conditional
    /// belongs to whichever pass owns it, as in ยง445's radix loop below.
    pub fn number_continues(
        &mut self,
        lx: &mut Lexer,
        pending_only: bool,
        fraction: bool,
    ) -> R<bool> {
        let Some(t) = self.peek_past_macros(lx, pending_only)? else {
            return Ok(false);
        };
        Ok(match t {
            Token::Char(c, Cat::Other) => {
                c.is_ascii_digit() || (fraction && matches!(c, '.' | ','))
            }
            _ => false,
        })
    }

    /// Whether a glue's written form would be read on past its end: ยง461's
    /// `plus` and `minus` and ยง454's further `l` of a `fil` are keywords, which
    /// ยง407 matches in either case after any spaces. So a letter next, even
    /// one a macro there begins with, may belong to the glue in front of it.
    pub fn glue_continues(&mut self, lx: &mut Lexer, pending_only: bool) -> R<bool> {
        let mut spaces = Vec::new();
        let next = loop {
            match self.peek_past_macros(lx, pending_only)? {
                Some(t) if t.is_space() => {
                    let _ = self.take(lx, pending_only);
                    spaces.push(t);
                }
                other => break other,
            }
        };
        lx.push_back(&spaces);
        Ok(matches!(next, Some(Token::Char(c, _)) if c.is_ascii_alphabetic()))
    }

    /// The next token once every macro in front of it has been expanded, left
    /// where it is.
    fn peek_past_macros(&mut self, lx: &mut Lexer, pending_only: bool) -> R<Option<Token>> {
        loop {
            let Some(t) = self.take(lx, pending_only) else {
                return Ok(None);
            };
            if let Token::Cs(n) = t {
                if self.is_macro(n) {
                    self.expand_macro(lx, n, pending_only)?;
                    continue;
                }
            }
            lx.push_back(std::slice::from_ref(&t));
            return Ok(Some(t));
        }
    }

    /// `tex.web` ยง449's internal INTEGER in the factor's place, if one is what
    /// stands there. Nothing is consumed when it is not.
    ///
    /// Only the factor position calls this. ยง455's `<internal unit>` wants a
    /// dimension or a glue and an integer is not one, which is why
    /// `peek_internal_unit` keeps its own test: `10\count0` is ยง454's illegal
    /// unit in tex too, measured.
    fn peek_internal_int(&mut self, lx: &mut Lexer, pending_only: bool) -> R<Option<NumericCs>> {
        let mut eaten = Vec::new();
        loop {
            let Some(t) = self.take(lx, pending_only) else {
                lx.push_back(&eaten);
                return Ok(None);
            };
            if t.is_space() {
                eaten.push(t);
                continue;
            }
            if let Token::Cs(n) = &t {
                let n = *n;
                // `\the` or `\number` of a register writes its digits (ยง465,
                // ยง470), which are the factor -- an integer's are, while a
                // dimension's `3.0pt` under `\the` is the whole dimension and
                // read above -- unless the digits go on in what follows.
                if matches!(n.name(), "the" | "number") {
                    lx.push_back(std::slice::from_ref(&t));
                    if let Some(reg) = self.take_expanded_register(lx, pending_only)? {
                        let integer = !reg.the || crate::compiler::is_count_slot(reg.slot);
                        if integer && !self.number_continues(lx, pending_only, true)? {
                            return Ok(Some(NumericCs::Register(reg.slot)));
                        }
                        self.put_back(lx, reg);
                    }
                    lx.push_back(&eaten);
                    return Ok(None);
                }
                // ยง449 reads this position with `get_x_token`, as everywhere
                // else in the scan.
                if self.try_expand(lx, n, pending_only)? {
                    continue;
                }
                // ยง413's internal integers are all factors here, the code
                // tables and the ยง236 parameters with the rest: `\catcode`\a pt`
                // is 11pt. Their values are frontend state, known now.
                let table = crate::charcodes::Table::from_name(n.name());
                let found = match n.name() {
                    "count" => Some(NumericCs::Register(self.scan_register_slot(
                        lx,
                        pending_only,
                        crate::compiler::RegFile::Count,
                    )?)),
                    "catcode" => {
                        let c = self.scan_char_code(lx, pending_only)?;
                        Some(NumericCs::Value(self.cats.get(c) as i64))
                    }
                    _ if table.is_some() => {
                        let c = self.scan_char_code(lx, pending_only)?;
                        let table = table.expect("just matched");
                        Some(NumericCs::Value(self.charcodes.get(table, c)))
                    }
                    _ if self.intpar_cs(n).is_some() => {
                        let i = self.intpar_cs(n).expect("just matched");
                        Some(NumericCs::Value(self.intpars.get(i)))
                    }
                    // A `\countdef` name is its register and a `\chardef` or
                    // `\mathchardef` one is its number; both are internal
                    // integers in ยง449's sense.
                    _ => match self.numeric_cs(n) {
                        Some(NumericCs::Register(r)) if crate::compiler::is_count_slot(r) => {
                            Some(NumericCs::Register(r))
                        }
                        Some(NumericCs::Value(v)) => Some(NumericCs::Value(v)),
                        _ => None,
                    },
                };
                if let Some(found) = found {
                    return Ok(Some(found));
                }
            }
            eaten.push(t);
            lx.push_back(&eaten);
            return Ok(None);
        }
    }

    /// `\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<()> {
        // ยง1288 reads its text with `scan_toks(false, false)`, whose left
        // brace is ยง403's: found by EXPANDING, so `\uppercase\expandafter{`
        // reaches the brace through the `\expandafter`.
        self.scan_left_brace(lx)?;
        let group = self.read_balanced(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")
            };
            // An active character is a command (ยง296 prints its meaning as a
            // control sequence's), not a character of category 13.
            if *cat == Cat::Active {
                return match self.active_meaning(*c) {
                    Some(id) => self.meaning_text(&Token::Cs(id)),
                    None => "undefined".to_string(),
                };
            }
            return Self::char_meaning(*c, *cat);
        };
        // ยง358: read where tex reads, it is `\relax`.
        if name.noexpand_origin().is_some() {
            return format!("{}relax", self.esc());
        }
        match self.meanings.get(name) {
            Some(Meaning::Char(c, cat)) => Self::char_meaning(*c, *cat),
            Some(Meaning::CharDef(v)) => format!("{}char\"{v:X}", self.esc()),
            Some(Meaning::MathCharDef(v)) => format!("{}mathchar\"{v:X}", self.esc()),
            Some(Meaning::CountDef(r)) => self.register_name(*r),
            Some(Meaning::ToksDef(r)) => format!("{}toks{r}", self.esc()),
            Some(Meaning::AttributeDef(r)) => format!("{}attribute{r}", self.esc()),
            Some(Meaning::Font(f)) => format!("select font {}", self.fonts.describe(*f)),
            Some(Meaning::Primitive(p)) => self.unbound_meaning(*p),
            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_str(&self.esc().to_string());
                        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 => self.unbound_meaning(*name),
        }
    }

    /// The name whose unredefined meaning `name` carries: itself when the
    /// table has nothing for it, the source of a `\let` copy of a primitive
    /// or of an undefined name, and `name` again for anything else.
    fn unbound_name(&self, name: CsId) -> CsId {
        match self.meanings.get(&name) {
            Some(Meaning::Primitive(p)) => *p,
            _ => name,
        }
    }

    /// ยง372: a name `\csname` builds that has no meaning is made `\relax`, so it
    /// is defined from then on.
    pub fn define_if_undefined(&mut self, built: &str) {
        let id = CsId::intern(built);
        if self.is_undefined(id) {
            self.meanings
                .insert(id, Meaning::Primitive(CsId::intern("relax")));
        }
    }

    /// Whether `name` means nothing at all: no definition, no primitive, and no
    /// `\let` copy of either.
    pub fn is_undefined(&self, name: CsId) -> bool {
        // A `\noexpand`ed name is `\relax`, whatever it was.
        if name.noexpand_origin().is_some() {
            return false;
        }
        match self.meanings.get(&name) {
            // A `\let` copy of a name is what that name is.
            Some(Meaning::Primitive(p)) if *p != name => self.is_undefined(*p),
            Some(Meaning::Primitive(_)) | None => !crate::primitives::is_known_name(name.name()),
            Some(_) => false,
        }
    }

    /// etex.ch's `if_def_code`: `get_next`, then `eq_type(cur_cs) <>
    /// undefined_cs`. A primitive nothing has redefined is defined, and so is a
    /// character that is not active -- its `cur_cs` is zero, whose `eq_type`
    /// is not `undefined_cs`; measured, `\ifdefined a` is true in luatex. An
    /// active character is whatever its meaning is.
    pub fn if_def_truth(&self, t: Option<&Token>) -> bool {
        match t {
            Some(Token::Cs(n)) => !self.is_undefined(*n),
            Some(Token::Char(c, Cat::Active)) => self
                .active_meaning(*c)
                .is_some_and(|id| !self.is_undefined(id)),
            Some(Token::Char(..)) => true,
            None => false,
        }
    }

    /// Whether a name the table holds nothing for is a primitive rather than
    /// undefined -- the question [`Self::unbound_meaning`] answers in words.
    fn is_primitive_name(&self, name: CsId) -> bool {
        self.unbound_meaning(name) != "undefined"
    }

    /// The meaning of a name the table holds nothing for: the primitive it is
    /// from the start, or `undefined`. A `\let` copy of such a name reads the
    /// same answer, so `\let\x\nullfont` is `select font nullfont` and
    /// `\let\x\undefined` is `undefined` (ยง1221 copies `eqtb[cur_cs]`, which
    /// for a name never defined is `undefined_cs`).
    fn unbound_meaning(&self, name: CsId) -> String {
        // A ยง236 parameter is a primitive whether or not the corpus has an
        // entry of its own for it.
        if crate::intpar::index(name.name()).is_some() {
            return format!("{}{}", self.esc(), name.name());
        }
        // Every other TeX82 primitive, whether or not texrs executes it.
        if crate::primitives::is_primitive(name.name()) {
            return crate::primitives::meaning(name.name(), &self.esc().to_string());
        }
        // A primitive TeX82 has not got: luatex's `print_cmd_chr` prints every
        // one of them as its own escaped name -- measured over the whole table
        // by `scripts/primitive-census.sh`.
        if crate::primitives::luatex_command(name.name()).is_some() {
            return format!("{}{}", self.esc(), name.name());
        }
        match crate::corpus::lookup(&format!("\\{}", name.name())) {
            Some(_) => format!("{}{}", self.esc(), 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.esc();
        if let Some(name) = crate::params::name_of_slot(slot) {
            return format!("{e}{name}");
        }
        if let Some((file, n)) = self.pooled_register(slot) {
            return format!("{e}{}{n}", file.name());
        }
        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.
    ///
    /// A `\global` in front belongs to this assignment and to nothing after it
    /// (ยง1211), so it is spent here whether or not the assignment succeeds.
    pub fn do_toks_assign(&mut self, lx: &mut Lexer, reg: i64) -> R<()> {
        let out = self.toks_assign(lx, reg);
        self.spend_prefixes(out)
    }

    fn 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 {
                        let list = self.read_balanced(lx)?;
                        // ยง1226: an `\output` routine is stored with its braces,
                        // so `\the\output` writes them back.
                        // An empty one is no routine at all, and has no braces.
                        match Some(reg) == crate::params::toks_register("output")
                            && !list.is_empty()
                        {
                            true => {
                                let mut braced = vec![Token::Char('{', Cat::BeginGroup)];
                                braced.extend(list);
                                braced.push(Token::Char('}', Cat::EndGroup));
                                braced
                            }
                            false => list,
                        }
                    };
                }
                // `\toks1=\toks0` copies, and `\toks1=\toksA` copies through a
                // name defined by \toksdef -- or a token parameter, `\everypar`.
                Token::Cs(n) => {
                    let n = *n;
                    let from = match n.name() {
                        "toks" => self.scan_number(lx, false)?,
                        _ => match self.toks_cs(n) {
                            Some(r) => r,
                            // ยง1226 reads the next non-blank non-relax token
                            // with `get_x_token`, so anything expandable before
                            // the brace expands: `\toks2=\expandafter{\the\toks1}`.
                            _ if self.primitive_meaning(n).name() == "relax" => continue,
                            _ if self.try_expand(lx, n, false)? => continue,
                            _ => {
                                lx.back_input(&[t]);
                                self.report(lx, "Missing { inserted");
                                break self.read_balanced(lx)?;
                            }
                        },
                    };
                    break self.toks.get(&from).cloned().unwrap_or_default();
                }
                _ => {
                    lx.back_input(&[t]);
                    self.report(lx, "Missing { inserted");
                    break self.read_balanced(lx)?;
                }
            }
        };
        // ยง1226 stores an empty list as `null`, so two empty assignments are
        // the same `equiv`; any other list is a new one.
        let global = self.global_defs_applied(self.global);
        let trace = self.intpar_named("tracingassigns") > 0;
        let empty_before = self.toks.get(&reg).is_none_or(|t| t.is_empty());
        if trace && !global && value.is_empty() && empty_before {
            self.trace_toks("reassigning", reg);
            return Ok(());
        }
        if trace {
            self.trace_toks(
                if global {
                    "globally changing"
                } else {
                    "changing"
                },
                reg,
            );
        }
        self.save(Save::Toks(reg, self.toks.get(&reg).cloned()));
        self.toks.insert(reg, value);
        self.sync_everyeof(reg);
        if trace {
            self.trace_toks("into", reg);
        }
        Ok(())
    }

    /// ยง577's `scan_font_ident`: blanks skipped with expansion, then `\font`,
    /// `\nullfont`, a name `\font` defined, or `\textfont`, `\scriptfont` or
    /// `\scriptscriptfont` and a family, as the internal font number. Anything
    /// else is put back and is `Missing font identifier`, with `\nullfont`.
    pub fn scan_font_ident(&mut self, lx: &mut Lexer, pending_only: bool) -> R<u16> {
        let t = loop {
            let Some(t) = self.take(lx, pending_only) else {
                return Ok(0);
            };
            match t {
                Token::Cs(n) if self.try_expand(lx, n, pending_only)? => continue,
                t if t.is_space() => continue,
                t => break t,
            }
        };
        if let Token::Cs(n) = t {
            if let Some(Meaning::Font(f)) = self.meanings.get(&n) {
                return Ok(*f);
            }
            let size = match self.primitive_meaning(n).name() {
                "font" => return Ok(self.cur_font),
                "nullfont" => return Ok(0),
                "textfont" => Some(0),
                "scriptfont" => Some(1),
                "scriptscriptfont" => Some(2),
                _ => None,
            };
            if let Some(size) = size {
                let fam = self.scan_number(lx, pending_only)?;
                return Ok(self.fam_fonts[size][(fam & 15) as usize]);
            }
        }
        match pending_only {
            true => lx.push_back(&[t]),
            false => lx.back_input(&[t]),
        }
        self.report(lx, "Missing font identifier");
        Ok(0)
    }

    /// ยง578's `find_font_dimen`: `\fontdimen n f`, as the font and the
    /// parameter number. Writing past the last parameter of the font loaded
    /// last makes room for it; past any other font's is ยง579's error, and
    /// reads parameter 1 of `\nullfont`.
    pub fn find_font_dimen(
        &mut self,
        lx: &mut Lexer,
        writing: bool,
        pending_only: bool,
    ) -> R<(u16, u16)> {
        let n = self.scan_number(lx, pending_only)?;
        let f = self.scan_font_ident(lx, pending_only)?;
        let last = self.fonts.fonts.len().saturating_sub(1) as u16;
        let have = self.fonts.get(f).params.len() as i64;
        let fits = n > 0 && (n <= have || (writing && f == last && f != 0));
        if !fits {
            let esc = self.esc().to_string();
            let id = self.fonts.get(f).id_text.clone();
            self.report(
                lx,
                &format!("Font {esc}{id} has only {have} fontdimen parameters"),
            );
            return Ok((0, 1));
        }
        if n > have {
            if let Some(font) = self.fonts.get_mut(f) {
                font.params.resize(n as usize, 0);
            }
        }
        Ok((f, n as u16))
    }

    /// `\the\fontdimen n f`, `\the\hyphenchar f` and `\the\skewchar f`
    /// (ยง425, ยง578), as ยง465 prints them, after `what`: font memory is the
    /// lowerer's, so the value is known while lowering. `None` for anything
    /// else, with nothing read.
    pub fn the_font_quantity(
        &mut self,
        lx: &mut Lexer,
        what: &str,
        pending_only: bool,
    ) -> R<Option<String>> {
        Ok(match what {
            "fontdimen" => {
                let (f, n) = self.find_font_dimen(lx, false, pending_only)?;
                let v = self.fonts.get(f).param(n as usize);
                Some(format!("{}pt", crate::dimen::print_scaled(v)))
            }
            "hyphenchar" | "skewchar" => {
                let f = self.scan_font_ident(lx, pending_only)?;
                let font = self.fonts.get(f);
                let value = match what {
                    "hyphenchar" => font.hyphen_char,
                    _ => font.skew_char,
                };
                Some(value.to_string())
            }
            _ => None,
        })
    }

    /// ยง501's `if_vmode_code`..`if_inner_code` over the mode the lowerer is
    /// following (`list_mode`): `\ifinner` is `mode<0`.
    pub fn mode_test(&self, name: &str) -> bool {
        let (kind, inner) = self.list_mode.unwrap_or((ModeKind::Vertical, false));
        match name {
            "ifvmode" => kind == ModeKind::Vertical,
            "ifhmode" => kind == ModeKind::Horizontal,
            "ifmmode" => kind == ModeKind::Math,
            _ => inner,
        }
    }

    /// A token list as text, by `tex.web` ยง292's `show_token_list`: a character
    /// is itself, and a control sequence is ยง262's `print_cs`. Shared by
    /// `\meaning`, `\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) => out.push_str(&self.cs_text(id.name())),
            }
        }
        out
    }

    /// The same text as ยง294's `show_token_list` prints it into a message:
    /// a macro-parameter character comes out DOUBLED (`mac_param: print(c);
    /// print(c)`), so `\message{\the\toks0}` over `a#b` prints `a##b`.
    pub fn tokens_shown(&self, tokens: &[Token]) -> String {
        let mut out = String::new();
        for t in tokens {
            match t {
                Token::Char(c, Cat::Param) => {
                    out.push(*c);
                    out.push(*c);
                }
                Token::Char(c, _) => out.push(*c),
                Token::Cs(id) => out.push_str(&self.cs_text(id.name())),
            }
        }
        out
    }

    /// `\the\toks<n>` as a message shows it; see [`Engine::tokens_shown`].
    pub fn toks_shown(&self, reg: i64) -> String {
        self.toks
            .get(&reg)
            .map(|t| self.tokens_shown(t))
            .unwrap_or_default()
    }

    /// ยง263's `sprint_cs`, which `\string` writes: the escape character and
    /// the name with no space after it, and `\csname\endcsname` for the null
    /// control sequence.
    pub fn sprint_cs(&self, name: CsId) -> String {
        let e = self.esc();
        let name = name.noexpand_origin().unwrap_or(name);
        match name.name() {
            "" => format!("{e}csname{e}endcsname"),
            n => format!("{e}{n}"),
        }
    }

    /// ยง262's `print_cs`: the escape character and the name, then a space
    /// after every multi-letter name and after a one-character name whose
    /// character is currently a LETTER -- `\A ` and, under
    /// `\makeatletter`, `\@ `, but `\1` and `\^^M` bare. The null control
    /// sequence prints as `\csname\endcsname `. `\string` is ยง263's
    /// `sprint_cs` instead, which never adds the space.
    pub fn cs_text(&self, name: &str) -> String {
        if name == MESSAGE_END {
            return "}".to_string();
        }
        if name == INACCESSIBLE {
            return format!("{}inaccessible ", self.esc());
        }
        let name = name
            .strip_prefix(crate::token::NOEXPAND_PREFIX)
            .unwrap_or(name);
        // ยง262: an active character prints as the character itself, no
        // escape and no trailing space -- `~->body' in ยง314's macro level.
        if let Some(c) = Self::active_char_of(name) {
            return c.to_string();
        }
        let e = self.esc();
        let mut chars = name.chars();
        match (chars.next(), chars.next()) {
            (None, _) => format!("{e}csname{e}endcsname "),
            (Some(c), None) if self.cats.get(c) != Cat::Letter => format!("{e}{name}"),
            _ => format!("{e}{name} "),
        }
    }

    pub fn toks_text(&self, reg: i64) -> String {
        match self.toks.get(&reg) {
            Some(tokens) => self.tokens_text(tokens),
            None => String::new(),
        }
    }

    /// 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),
            // A token parameter (ยง230) is a token list, by its own name or by
            // a `\let` copy of it.
            None => crate::params::toks_register(name.name()),
            Some(Meaning::Primitive(p)) => crate::params::toks_register(p.name()),
            _ => None,
        }
    }

    /// e-TeX's `\numexpr` (`dimen` false) or `\dimexpr`, read after the
    /// primitive, where the expander needs the value now: luatex's
    /// `scan_expr` (scanning.c), on the values this side knows. The lowerer's
    /// `Lowerer::expr` is the same procedure for an expression the run
    /// evaluates; both take their arithmetic from `crate::etex_arith`.
    pub fn scan_expr(&mut self, lx: &mut Lexer, pending_only: bool, dimen: bool) -> R<i64> {
        let e = self.expr_level(lx, pending_only, dimen, false)?;
        Ok(match e {
            crate::etex_arith::ERROR => {
                self.report(lx, "Arithmetic overflow");
                0
            }
            v => v,
        })
    }

    /// One level of `scan_expr`, up to the end or, `nested`, to its `)`.
    fn expr_level(
        &mut self,
        lx: &mut Lexer,
        pending_only: bool,
        dimen: bool,
        nested: bool,
    ) -> R<i64> {
        use crate::etex_arith::{apply, Op, INFINITY, MAX_DIMEN};
        let max = if dimen { MAX_DIMEN } else { INFINITY };
        let (mut r, mut e) = (None::<Op>, 0i64);
        let (mut s, mut t, mut n) = (None::<Op>, 0i64, 0i64);
        loop {
            // A factor after `*` or `/` is an integer, whatever the level.
            let factor_dimen = dimen && s.is_none();
            let f = match self.next_x_nonblank(lx, pending_only)? {
                Some(Token::Char('(', Cat::Other)) => {
                    self.expr_level(lx, pending_only, factor_dimen, true)?
                }
                other => {
                    if let Some(tok) = other {
                        lx.back_input(&[tok]);
                    }
                    match factor_dimen {
                        true => self.scan_dimen(lx, pending_only)?,
                        false => self.scan_number(lx, pending_only)?,
                    }
                }
            };
            let next = self.next_x_nonblank(lx, pending_only)?;
            let mut o = match &next {
                Some(Token::Char('+', Cat::Other)) => Some(Op::Add),
                Some(Token::Char('-', Cat::Other)) => Some(Op::Sub),
                Some(Token::Char('*', Cat::Other)) => Some(Op::Mul),
                Some(Token::Char('/', Cat::Other)) => Some(Op::Div),
                _ => None,
            };
            if o.is_none() {
                match next {
                    Some(Token::Char(')', Cat::Other)) if nested => {}
                    Some(tok) if nested => {
                        lx.back_input(&[tok]);
                        self.report(lx, "Missing ) inserted for expression");
                    }
                    Some(tok) if !self.means_relax(&tok) => lx.back_input(&[tok]),
                    _ => {}
                }
            }
            // Make sure that `f` is in the proper range.
            let bound = if !dimen || s.is_some() { INFINITY } else { max };
            let f = apply(Op::Check, bound, &[f]);
            match s {
                None => t = f,
                Some(Op::Mul) if o == Some(Op::Div) => {
                    n = f;
                    o = Some(Op::Scale);
                }
                Some(Op::Scale) => t = apply(Op::Scale, max, &[t, n, f]),
                Some(op) => t = apply(op, max, &[t, f]),
            }
            match o {
                Some(Op::Mul | Op::Div | Op::Scale) => s = o,
                _ => {
                    s = None;
                    e = match r {
                        None => t,
                        Some(add_or_sub) => apply(add_or_sub, max, &[e, t]),
                    };
                    r = o;
                }
            }
            if o.is_none() {
                return Ok(e);
            }
        }
    }

    /// 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)> {
        match self.scan_dimen_or_fil_parts(lx, pending_only)? {
            (crate::dimen::ScannedDimen::Constant(v), order) => Ok((v, order)),
            (
                crate::dimen::ScannedDimen::Scaled { .. }
                | crate::dimen::ScannedDimen::ByCount { .. },
                _,
            ) => Err(self.illegal_unit()),
        }
    }

    /// The same, with ยง453's `<factor><internal unit>` carried out whole.
    ///
    /// An infinite component is never scaled by a register: `fil` is spelt in
    /// letters and an internal unit is a control sequence, so the two shapes
    /// cannot both match and the order that comes back with a `Scaled` is
    /// always the finite one.
    pub fn scan_dimen_or_fil_parts(
        &mut self,
        lx: &mut Lexer,
        pending_only: bool,
    ) -> R<(crate::dimen::ScannedDimen, i64)> {
        let (d, order) = self.scan_dimen_or_fil_parts_inner(lx, pending_only)?;
        self.note_scaling(lx, &d);
        Ok((d, order))
    }

    fn scan_dimen_or_fil_parts_inner(
        &mut self,
        lx: &mut Lexer,
        pending_only: bool,
    ) -> R<(crate::dimen::ScannedDimen, i64)> {
        use crate::dimen::ScannedDimen;
        let sign = self.scan_optional_signs(lx, pending_only)?;
        // ยง449, as in `scan_dimen_parts`: `\@plus\p@` is one `\p@`, and an
        // internal dimension is always finite.
        if let Some(reg) = self.peek_internal_unit(lx, pending_only)? {
            return Ok((
                ScannedDimen::Scaled {
                    int: sign,
                    frac: 0,
                    reg,
                },
                0,
            ));
        }
        // ยง449's internal integer in the factor's place, as in
        // `scan_dimen_parts`. An infinite component cannot be one: `fil` is
        // spelt in letters, so the order that comes back is still zero.
        let internal = self.peek_internal_int(lx, pending_only)?;
        let by_count = match internal {
            Some(NumericCs::Register(r)) => Some(r),
            _ => None,
        };
        let (int, frac) = match internal {
            Some(NumericCs::Register(_)) => (1, 0),
            Some(NumericCs::Value(v)) => (v, 0),
            None => self.scan_factor(lx, pending_only)?,
        };
        if let Some(reg) = self.peek_internal_unit(lx, pending_only)? {
            return Ok((
                match by_count {
                    Some(factor) => ScannedDimen::ByCount {
                        factor,
                        sign,
                        unit: crate::dimen::CountUnit::Register(reg),
                    },
                    None => ScannedDimen::Scaled {
                        int: sign * int,
                        frac: sign * frac,
                        reg,
                    },
                },
                0,
            ));
        }
        // ยง455's `em` and `ex`, which are finite by construction: a quad is a
        // number, so the order that comes back with one is always zero.
        if let Some(v) = self.scan_font_unit(lx, pending_only)? {
            return Ok((
                match by_count {
                    Some(factor) => ScannedDimen::ByCount {
                        factor,
                        sign,
                        unit: crate::dimen::CountUnit::Points(v),
                    },
                    None => ScannedDimen::Constant(
                        crate::dimen::scale_by_factor(sign * int, sign * frac, v)
                            .clamp(-crate::dimen::MAX_DIMEN, crate::dimen::MAX_DIMEN),
                    ),
                },
                0,
            ));
        }
        // ยง453: `fil`, then one order further for each `l` after it, each read
        // by ยง407's `scan_keyword` -- so a space may stand before an `l`
        // (`1 fil l` is `fill`), and an `l` past `filll` is an error that
        // keeps the order where it is.
        let mut order = 0;
        let mut unit = "";
        if self.scan_keyword(lx, "fil", pending_only)? {
            order = 1;
            while self.scan_keyword(lx, "l", pending_only)? {
                match order {
                    3 => self.report(lx, "Illegal unit of measure (replaced by filll)"),
                    _ => order += 1,
                }
            }
        } else {
            // ยง453's optional `true`, AFTER `fil` was looked for, as 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)?;
            // ยง456 and ยง458: `mu` alone in math units, otherwise the physical
            // units in ยง458's order, each a keyword of its own; ยง459 reports
            // none and goes on in points (or `mu`).
            unit = self.scan_physical_unit(lx, pending_only)?;
        }
        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 !self.is_spacer(&t) {
                lx.push_back(std::slice::from_ref(&t));
            }
        }
        Ok((
            match by_count {
                Some(factor) => ScannedDimen::ByCount {
                    factor,
                    sign,
                    unit: crate::dimen::CountUnit::Points(sp),
                },
                None => ScannedDimen::Constant(
                    (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) -> R<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 Ok(false);
                };
                if self.is_spacer(&t) && seen.is_empty() {
                    continue;
                }
                // ยง407 reads each letter with `get_x_token`, so a keyword may
                // arrive through a MACRO. latex.ltx spells its glue
                // `\@plus2\p@` with `\def\@plus{plus}`, and every standard
                // class writes every glue that way -- unexpanded, the `plus`
                // was never seen, the stretch was silently dropped, and the
                // rest of the line was left in the document to be read as text.
                if let Token::Cs(n) = &t {
                    let n = *n;
                    if self.try_expand(lx, n, pending_only)? {
                        continue;
                    }
                }
                let matched = matches!(&t, Token::Char(c, _)
                    if c.eq_ignore_ascii_case(&want));
                if !matched {
                    // ยง407: `back_input` of the token that failed, then
                    // `back_list` of the letters that matched, above it.
                    lx.back_input(&[t]);
                    if !seen.is_empty() {
                        lx.back_input(&seen);
                    }
                    return Ok(false);
                }
                seen.push(t);
                break;
            }
        }
        Ok(true)
    }

    /// e-TeX's `\glueexpr` (or `\muexpr`, under `mu_units`), read after the
    /// primitive: luatex's `scan_expr` at `glue_val_level`, on the values this
    /// side knows. Factors are glue; a factor after `*` or `/` is an integer.
    pub fn scan_glue_expr(&mut self, lx: &mut Lexer) -> R<crate::glue::Glue> {
        let mut error = false;
        let e = self.glue_expr_level(lx, false, &mut error)?;
        if error {
            self.report(lx, "Arithmetic overflow");
            return Ok(crate::etex_arith::glue_error());
        }
        Ok(e)
    }

    /// One level of the glue `scan_expr`, up to the end or, `nested`, to its
    /// `)`. `error` is `arith_error`: once set, the result is zero.
    fn glue_expr_level(
        &mut self,
        lx: &mut Lexer,
        nested: bool,
        error: &mut bool,
    ) -> R<crate::glue::Glue> {
        use crate::etex_arith::{self as arith, Op, INFINITY};
        use crate::glue::Glue;
        // A factor is a glue at the start of a term and an integer after `*`
        // or `/`; `Factor` is which it was.
        enum Factor {
            Glue(Glue),
            Int(i64),
        }
        let (mut r, mut e) = (None::<Op>, Glue::default());
        let (mut s, mut t, mut n) = (None::<Op>, Glue::default(), 0i64);
        loop {
            let opened = match self.next_x_nonblank(lx, false)? {
                Some(Token::Char('(', Cat::Other)) => true,
                other => {
                    if let Some(tok) = other {
                        lx.back_input(&[tok]);
                    }
                    false
                }
            };
            let f = match (s.is_none(), opened) {
                (true, true) => Factor::Glue(self.glue_expr_level(lx, true, error)?),
                (true, false) => {
                    let (natural, stretch, stretch_order, shrink, shrink_order) =
                        self.scan_glue(lx)?;
                    Factor::Glue(Glue {
                        natural,
                        stretch,
                        stretch_order,
                        shrink,
                        shrink_order,
                    })
                }
                (false, true) => Factor::Int(self.expr_level(lx, false, false, true)?),
                (false, false) => Factor::Int(self.scan_number(lx, false)?),
            };
            let next = self.next_x_nonblank(lx, false)?;
            let mut o = match &next {
                Some(Token::Char('+', Cat::Other)) => Some(Op::Add),
                Some(Token::Char('-', Cat::Other)) => Some(Op::Sub),
                Some(Token::Char('*', Cat::Other)) => Some(Op::Mul),
                Some(Token::Char('/', Cat::Other)) => Some(Op::Div),
                _ => None,
            };
            if o.is_none() {
                match next {
                    Some(Token::Char(')', Cat::Other)) if nested => {}
                    Some(tok) if nested => {
                        lx.back_input(&[tok]);
                        self.report(lx, "Missing ) inserted for expression");
                    }
                    Some(tok) if !self.means_relax(&tok) => lx.back_input(&[tok]),
                    _ => {}
                }
            }
            // Make sure the factor is in range, and apply it to the term.
            let mut failed = |ok: bool| {
                if !ok {
                    *error = true;
                }
            };
            match (s, f) {
                (None, Factor::Glue(g)) => {
                    t = match arith::check_glue(g) {
                        Some(g) => g,
                        None => {
                            failed(false);
                            arith::glue_error()
                        }
                    };
                    if o.is_some() {
                        t = arith::normalize_glue(t);
                    }
                }
                (Some(op), Factor::Int(f)) => {
                    let f = match arith::apply(Op::Check, INFINITY, &[f]) {
                        arith::ERROR => {
                            failed(false);
                            0
                        }
                        f => f,
                    };
                    let applied = match op {
                        Op::Mul if o == Some(Op::Div) => {
                            n = f;
                            o = Some(Op::Scale);
                            Some(t)
                        }
                        Op::Scale => arith::scale_glue(Op::Scale, t, &[n, f]),
                        op => arith::scale_glue(op, t, &[f]),
                    };
                    t = match applied {
                        Some(g) => g,
                        None => {
                            failed(false);
                            arith::glue_error()
                        }
                    };
                }
                _ => unreachable!("a glue opens a term and an integer follows * or /"),
            }
            match o {
                Some(Op::Mul | Op::Div | Op::Scale) => s = o,
                _ => {
                    s = None;
                    e = match r {
                        None => t,
                        Some(add_or_sub) => match arith::add_glue(e, t, add_or_sub == Op::Sub) {
                            Some(g) => g,
                            None => {
                                failed(false);
                                arith::glue_error()
                            }
                        },
                    };
                    r = o;
                }
            }
            if o.is_none() {
                return Ok(e);
            }
        }
    }

    /// Read dimensions in math units (`mu`) from now on, or stop; the old
    /// setting is returned. `\mkern`'s width is ยง1061's `scan_dimen(mu,..)`.
    pub fn set_mu_units(&mut self, on: bool) -> bool {
        std::mem::replace(&mut self.mu_units, on)
    }

    /// 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
    }

    /// `scan_muglue`, with ยง453's `<factor><internal unit>` carried out whole.
    pub fn scan_muglue_parts(&mut self, lx: &mut Lexer) -> R<GlueParts> {
        self.mu_units = true;
        let got = self.scan_glue_parts(lx);
        self.mu_units = false;
        got
    }

    /// `<dimen> [plus <dimen|fil>] [minus <dimen|fil>]` โ€” a glue.
    ///
    /// A caller that reads numbers gets ยง454's illegal unit for a component
    /// only the VM can compute, exactly as it did before that shape was
    /// scannable; `scan_glue_parts` is the same scan for a caller that can
    /// carry a product.
    pub fn scan_glue(&mut self, lx: &mut Lexer) -> R<(i64, i64, i64, i64, i64)> {
        let g = self.scan_glue_parts(lx)?;
        // A component written with an internal dimension is that register's
        // value, which the followed registers give when it is known.
        let natural = self.dimen_value(lx, g.natural);
        let stretch = self.dimen_value(lx, g.stretch);
        let shrink = self.dimen_value(lx, g.shrink);
        match (natural, stretch, shrink) {
            (Ok(n), Ok(st), Ok(sh)) => Ok((n, st, g.stretch_order, sh, g.shrink_order)),
            _ => Err(self.illegal_unit()),
        }
    }

    /// The same, with each of the three `<dimen>` positions carried out whole.
    pub fn scan_glue_parts(&mut self, lx: &mut Lexer) -> R<GlueParts> {
        // `\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 && self.unaliased(*n).name() == "muexpr")
                    || (!mu && self.unaliased(*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(GlueParts {
                    natural: crate::dimen::ScannedDimen::Constant(g.natural),
                    stretch: crate::dimen::ScannedDimen::Constant(g.stretch),
                    stretch_order: g.stretch_order,
                    shrink: crate::dimen::ScannedDimen::Constant(g.shrink),
                    shrink_order: g.shrink_order,
                });
            }
        }
        let zero = (crate::dimen::ScannedDimen::Constant(0), 0);
        let natural = self.scan_dimen_parts(lx, false)?;
        let (stretch, stretch_order) = match self.scan_keyword(lx, "plus", false)? {
            true => self.scan_dimen_or_fil_parts(lx, false)?,
            false => zero,
        };
        let (shrink, shrink_order) = match self.scan_keyword(lx, "minus", false)? {
            true => self.scan_dimen_or_fil_parts(lx, false)?,
            false => zero,
        };
        Ok(GlueParts {
            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 character an [`Self::active_cs`] name stands for.
    fn active_char_of(name: &str) -> Option<char> {
        let mut chars = name.strip_prefix("active:")?.chars();
        match (chars.next(), chars.next()) {
            (Some(c), None) => Some(c),
            _ => None,
        }
    }

    /// 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> {
        self.get_r_token(lx, false)
    }

    /// ยง1215's `get_r_token`: the next non-blank token, which must be a control
    /// sequence or an active character. Anything else is `Missing control
    /// sequence inserted`: the token is read again, `\inaccessible` is
    /// inserted in front of it, and the definition goes on naming that.
    pub fn get_r_token(&mut self, lx: &mut Lexer, pending_only: bool) -> R<CsId> {
        loop {
            let Some(t) = self.take(lx, pending_only) else {
                return Err(TexError("Missing control sequence inserted".into()));
            };
            match t {
                t if t.is_space() => continue,
                Token::Cs(name) => return Ok(name),
                Token::Char(c, Cat::Active) => return Ok(Self::active_cs(c)),
                t => {
                    lx.back_input(&[t]);
                    lx.insert_input(&[Token::Cs(CsId::intern(INACCESSIBLE))]);
                    self.report(lx, "Missing control sequence inserted");
                }
            }
        }
    }

    /// 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)));
                }
                // ยง476: parameters are numbered 1 to 9 in order. A tenth is
                // reported and dropped with the token after it; a wrong
                // number is reported, put back to be read again as text, and
                // the parameter takes the number it should have had.
                let count = params
                    .iter()
                    .filter(|p| matches!(p, Token::Char(_, Cat::Param)))
                    .count() as u8;
                if count == 9 {
                    self.report(lx, "You already have nine parameters");
                    continue;
                }
                let want = char::from(b'1' + count);
                if !matches!(next, Token::Char(c, _) if c == want) {
                    lx.back_input(&[next]);
                    self.report(lx, "Parameters must be numbered consecutively");
                }
                params.push(t);
                params.push(Token::Char(want, Cat::Other));
                continue;
            }
            params.push(t);
        }
    }

    /// ยง473's body of a `\def`, read to its matching `}` with ยง479's check on
    /// each `#`: `##` and `#1` up to the parameter count stand, and anything
    /// else is `Illegal parameter number in definition of \a`, the token put
    /// back to be read again and the `#` kept as a macro parameter character
    /// (`##` in texrs's spelling of one).
    fn read_def_body(&mut self, lx: &mut Lexer, name: CsId, params: &[Token]) -> R<Vec<Token>> {
        let count = params
            .iter()
            .filter(|p| matches!(p, Token::Char(_, Cat::Param)))
            .count() as u32;
        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);
                    }
                }
                Token::Char(_, Cat::Param) => {
                    let Some(next) = lx.next_token(&self.cats) else {
                        break;
                    };
                    let legal = match next {
                        Token::Char(_, Cat::Param) => true,
                        Token::Char(c, _) => c.to_digit(10).is_some_and(|d| d >= 1 && d <= count),
                        Token::Cs(_) => false,
                    };
                    out.push(t);
                    match legal {
                        true => out.push(next),
                        false => {
                            lx.back_input(&[next]);
                            let msg = format!(
                                "Illegal parameter number in definition of {}",
                                self.sprint_cs(name)
                            );
                            self.report(lx, &msg);
                            out.push(t);
                        }
                    }
                    continue;
                }
                _ => {}
            }
            out.push(unmarked(t));
        }
        Err(TexError("Runaway argument".into()))
    }

    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_def_body(lx, name, &params)?;
        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(Rc::new(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.esc())).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(Rc::new(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.
    /// ยง403's `scan_left_brace`: skip blanks and `\relax`, expanding as it
    /// goes, and consume the left brace that must come next.
    fn scan_left_brace(&mut self, lx: &mut Lexer) -> R<()> {
        loop {
            let Some(t) = lx.next_token(&self.cats) else {
                return Err(TexError("Missing { inserted".into()));
            };
            match t {
                t if self.is_spacer(&t) => continue,
                Token::Char(_, Cat::BeginGroup) => return Ok(()),
                Token::Cs(n) if self.primitive_meaning(n).name() == "relax" => continue,
                Token::Cs(n) if self.try_expand(lx, n, false)? => continue,
                // ยง403: report, put the token back to be read again, and go on
                // as if the brace had been there.
                t => {
                    lx.back_input(&[t]);
                    self.report(lx, "Missing { inserted");
                    return Ok(());
                }
            }
        }
    }

    /// etex.ch's `scan_general_text`, the argument of `\detokenize`,
    /// `\unexpanded`, `\expanded` and `\scantokens`: ยง473's `scan_toks`, whose
    /// ยง403 `scan_left_brace` EXPANDS until it meets the brace -- so
    /// `\detokenize\expandafter{\x}` reads `\x`'s replacement, and a blank or
    /// `\relax` in front of the brace is passed over. Anything else is
    /// `Missing { inserted`, read again as the first token of the text.
    pub fn scan_general_text(&mut self, lx: &mut Lexer) -> R<Vec<Token>> {
        self.scan_left_brace(lx)?;
        self.read_balanced(lx)
    }

    /// The tokens `\detokenize` makes of `toks`: ยง295's `show_token_list`
    /// spelling (a parameter character doubled, a space after a control word),
    /// turned back into characters by ยง464's `str_toks`, which makes a space
    /// a space and everything else category 12.
    pub fn detokenized(&self, toks: &[Token]) -> Vec<Token> {
        str_toks(&self.tokens_shown(toks))
    }

    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.
    /// Record the line an `\inputlineno` token was read on.
    fn note_input_line(&mut self, lx: &Lexer, t: Option<&Token>) {
        if let Some(Token::Cs(n)) = t {
            if n.name() == "inputlineno" {
                self.input_line = lx.line();
            }
        }
    }

    /// The read-only integers of e-TeX and LuaTeX (`last_item` commands) whose
    /// value is known while lowering: the version numbers, which luatex 1.24.0
    /// gives as `\eTeXversion` 2, `\eTeXminorversion` 2 and `\luatexversion`
    /// 124 (measured), and etex.ch's `\currentgrouplevel` (`cur_level -
    /// level_one`) and `\currentgrouptype` (`cur_group`, ยง269's code, 0 outside
    /// every group).
    fn last_item_value(&self, primitive: &str) -> Option<i64> {
        match primitive {
            "eTeXversion" => Some(2),
            "eTeXminorversion" => Some(2),
            "luatexversion" => Some(124),
            "interactionmode" => Some(self.interaction),
            "catcodetable" => Some(self.cat_table),
            "currentiflevel" | "currentiftype" | "currentifbranch" => {
                Some(self.current_if(primitive))
            }
            "currentgrouplevel" => Some(self.group_level() as i64),
            "currentgrouptype" => Some(self.innermost_group().map_or(0, GroupKind::code)),
            // The backend's last items (`crate::backend`): what the last
            // `\saveimageresource` and `\saveboxresource` numbered.
            "lastsavedimageresourceindex" => Some(i64::from(self.backend.last_image)),
            "lastsavedimageresourcepages" => Some(self.backend.last_image_pages),
            "lastsavedboxresourceindex" => Some(i64::from(self.backend.last_box)),
            _ => None,
        }
    }

    pub fn numeric_cs(&self, name: CsId) -> Option<NumericCs> {
        match self.meanings.get(&name) {
            Some(Meaning::CharDef(v) | Meaning::MathCharDef(v)) => Some(NumericCs::Value(*v)),
            Some(Meaning::CountDef(r)) => Some(NumericCs::Register(*r)),
            Some(Meaning::AttributeDef(n)) => Some(NumericCs::Value(self.attribute_value(*n))),
            // eTeX's `\inputlineno` (etex.ch `input_line_no_code`) is a
            // read-only integer: the line it was read on.
            None if name.name() == "inputlineno" => {
                Some(NumericCs::Value(i64::from(self.input_line)))
            }
            // `\catcodetable` reads as the table in force (`assign_int`).
            None if name.name() == "catcodetable" => Some(NumericCs::Value(self.cat_table)),
            Some(Meaning::Primitive(p)) if p.name() == "catcodetable" => {
                Some(NumericCs::Value(self.cat_table))
            }
            None if self.last_item_value(name.name()).is_some() => {
                self.last_item_value(name.name()).map(NumericCs::Value)
            }
            Some(Meaning::Primitive(p)) if self.last_item_value(p.name()).is_some() => {
                self.last_item_value(p.name()).map(NumericCs::Value)
            }
            // A dimension or glue parameter (ยง247, ยง224) is a register, by
            // its own name or by a `\let` copy of it.
            None => crate::params::register_slot(name.name()).map(NumericCs::Register),
            Some(Meaning::Primitive(p)) => {
                crate::params::register_slot(p.name()).map(NumericCs::Register)
            }
            _ => 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 out = self.numeric_def(lx, kind);
        self.spend_prefixes(out)
    }

    fn numeric_def(&mut self, lx: &mut Lexer, kind: &str) -> R<()> {
        let name = self.get_r_token(lx, false)?;
        // ยง1224's `define(p, relax, 256)`: the name means `\relax` while its
        // number is read, so reading it there finds `\relax` -- and
        // `\tracingassigns` shows both definitions.
        self.set_meaning(name, Meaning::Primitive(CsId::intern("relax")));
        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.
        // A LuaTeX-ranged run (`register_limit`) has 65536 registers and
        // every Unicode character: `\countdef\e=65535` and `\chardef\b=1114111`
        // are accepted there and the next number past each is the same
        // report, measured.
        let chars = match self.register_limit > 255 {
            true => 0x10FFFF,
            false => 255,
        };
        let (limit, what) = match kind {
            "mathchardef" => (32767, "mathchar"),
            "dimendef" | "skipdef" | "muskipdef" | "toksdef" | "attributedef" => {
                (self.register_limit, "register code")
            }
            "chardef" => (chars, "character code"),
            _ => (self.register_limit, "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, with its own range and
            // its own command.
            "chardef" => Meaning::CharDef(v),
            "mathchardef" => Meaning::MathCharDef(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(self.register_address(crate::compiler::RegFile::Dimen, 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),
            "attributedef" => Meaning::AttributeDef(v),
            "skipdef" => {
                Meaning::CountDef(self.register_address(crate::compiler::RegFile::Skip, v)?)
            }
            // 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(self.register_address(crate::compiler::RegFile::MuSkip, v)?)
            }
            _ => Meaning::CountDef(self.register_address(crate::compiler::RegFile::Count, v)?),
        };
        self.set_meaning(name, meaning);
        Ok(())
    }

    fn do_futurelet(&mut self, lx: &mut Lexer, pending_only: bool) -> R<()> {
        let name = self.get_r_token(lx, pending_only)?;
        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)?;
        // ยง1221: spaces, then an optional other-character `=` followed by ONE
        // optional space, then the source token. So `\let\b==` lets `\b` be
        // the second `=`, and `\let\sptoken= ` followed by a space lets it be
        // that space.
        let mut src = lx.next_token(&self.cats);
        while src.as_ref().is_some_and(Token::is_space) {
            src = lx.next_token(&self.cats);
        }
        if matches!(src, Some(Token::Char('=', Cat::Other))) {
            src = lx.next_token(&self.cats);
            if src.as_ref().is_some_and(Token::is_space) {
                src = lx.next_token(&self.cats);
            }
        }
        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(unmarked(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())));
        };
        // ยง401: with `\tracingmacros` positive the call is shown before its
        // arguments are read.
        let traced = self.recover && self.intpars.get(crate::intpar::TRACING_MACROS) > 0;
        if traced {
            let shown = format!(
                "{}{}->{}",
                self.cs_text(name.name()),
                self.tokens_text(&m.params),
                self.tokens_text(&m.body)
            );
            self.diagnostic(&shown);
        }
        // `\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];
                let rest = m.params.get(2..).unwrap_or(&[]);
                match self.match_params(lx, name, rest, m.long, pending_only)? {
                    Some(more) => args.extend(more),
                    None => return Ok(()),
                }
                args
            }
            None => match self.match_params(lx, name, &m.params, m.long, pending_only)? {
                Some(args) => args,
                None => return Ok(()),
            },
        };
        // ยง400: each argument as it was read.
        if traced {
            for (n, arg) in args.iter().enumerate() {
                let shown = format!("#{}<-{}", n + 1, self.tokens_shown(arg));
                self.diagnostic(&shown);
            }
        }
        // Room for the body and every argument once, which bounds what a body
        // that names each parameter once becomes, so it is built without growing.
        let substituted: usize = args.iter().map(Vec::len).sum();
        let mut out = Vec::with_capacity(m.body.len() + substituted);
        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 plain = out.len();
        let out = self.weave_advice(name, out)?;
        // Advice rewrites the expansion, so the body no longer lines up with
        // the definition and the level is left out of the display.
        match out.len() == plain {
            true => lx.push_macro(name, args.iter().map(|a| a.len() as u32).collect(), out),
            false => 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"
            ))),
        }
    }

    /// ยง389-ยง399's arguments of a call to `name`, or `None` when the call was
    /// abandoned: a `\par` in an argument of a macro that is not `\long` is
    /// ยง396's runaway, reported, the `\par` put back, and no expansion.
    fn match_params(
        &mut self,
        lx: &mut Lexer,
        name: CsId,
        params: &[Token],
        long: bool,
        pending_only: bool,
    ) -> R<Option<Vec<Vec<Token>>>> {
        // LuaTeX's `\suppresslongerror` (expand.c, `macro_call`): a `\par` in
        // an argument is no runaway while it is positive, `\long` or not.
        let long = long || self.intpar_named("suppresslongerror") > 0;
        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, long, pending_only)?,
                false => self.read_delimited(lx, &delim, long, pending_only)?,
            };
            match arg {
                Arg::Read(arg) => args.push(arg),
                Arg::Par(partial) => {
                    self.paragraph_ended(lx, name, &partial);
                    return Ok(None);
                }
                // ยง395: the brace goes back, a `\par` is INSERTED in front of
                // it, and the scan reads that at once -- the white lie that
                // makes even a `\long` macro's call a runaway.
                Arg::ExtraBrace(partial, brace) => {
                    lx.back_input(&[brace]);
                    lx.insert_input(&[Token::cs("par")]);
                    let msg = format!("Argument of {} has an extra }}", self.sprint_cs(name));
                    self.report(lx, &msg);
                    lx.pending.pop();
                    self.paragraph_ended(lx, name, &partial);
                    return Ok(None);
                }
            }
            i += 2 + delim.len();
        }
        Ok(Some(args))
    }

    /// ยง396: `Runaway argument?` and what the argument had so far (ยง306),
    /// then `Paragraph ended before \a was complete` with the `\par` put back
    /// to be read again.
    fn paragraph_ended(&mut self, lx: &mut Lexer, name: CsId, partial: &[Token]) {
        self.note_mouth(lx);
        // ยง306 shows the list to `error_line-10` characters, then `\ETC.`.
        const LIMIT: usize = 79 - 10;
        let mut shown = String::new();
        for t in partial {
            if shown.chars().count() >= LIMIT {
                shown.push_str(&format!("{}ETC.", self.esc()));
                break;
            }
            shown.push_str(&self.tokens_shown(std::slice::from_ref(t)));
        }
        self.errors.push(format!("Runaway argument?{shown}"));
        lx.back_input(&[Token::cs("par")]);
        let msg = format!(
            "Paragraph ended before {} was complete",
            self.sprint_cs(name)
        );
        self.report(lx, &msg);
    }

    /// 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, long: bool, pending_only: bool) -> R<Arg> {
        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_group_arg(lx, t, long, pending_only),
                Token::Char(_, Cat::EndGroup) => Ok(Arg::ExtraBrace(Vec::new(), t)),
                t if is_par(&t) && !long => Ok(Arg::Par(Vec::new())),
                other => Ok(Arg::Read(vec![unmarked(other)])),
            };
        }
    }

    /// ยง399: an undelimited argument that is a group, read to its matching
    /// `}` without the outer braces. The runaway it can be shows the `{`.
    fn read_group_arg(
        &mut self,
        lx: &mut Lexer,
        open: Token,
        long: bool,
        pending_only: bool,
    ) -> R<Arg> {
        let mut depth = 1usize;
        // The braces are not part of the argument, so the `{` is not kept in
        // front of it to be taken out again: only a runaway shows it.
        let mut out = Vec::new();
        loop {
            let t = match pending_only {
                true => lx.pending.pop(),
                false => self.take(lx, false),
            };
            let Some(t) = t else {
                return Err(TexError("Runaway argument".into()));
            };
            match &t {
                Token::Char(_, Cat::BeginGroup) => depth += 1,
                Token::Char(_, Cat::EndGroup) => {
                    depth -= 1;
                    if depth == 0 {
                        return Ok(Arg::Read(out));
                    }
                }
                t if is_par(t) && !long => {
                    out.insert(0, open);
                    return Ok(Arg::Par(out));
                }
                _ => {}
            }
            out.push(unmarked(t));
        }
    }

    fn read_delimited(
        &mut self,
        lx: &mut Lexer,
        delim: &[Token],
        long: bool,
        pending_only: bool,
    ) -> R<Arg> {
        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(unmarked(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());
                // ยง400 strips the braces only when the argument is ONE item
                // (ยง392's `m`, which counts a group as one) and that item is a
                // group: `{x}` loses them, `{x}{y}` and `{x} ` keep them.
                if is_one_group(&out) {
                    out.remove(0);
                    out.pop();
                }
                return Ok(Arg::Read(out));
            }
            // ยง392 tests `\par` AFTER the delimiter, so a macro delimited by
            // `\par` (`\def\a#1\par{..}`) is ended by one, and before the
            // brace count, so it is a runaway at any depth.
            if is_par(&t) && !long {
                out.pop();
                return Ok(Arg::Par(out));
            }
            match &t {
                Token::Char(_, Cat::BeginGroup) => depth += 1,
                Token::Char(_, Cat::EndGroup) if depth == 0 => {
                    out.pop();
                    return Ok(Arg::ExtraBrace(out, t));
                }
                Token::Char(_, Cat::EndGroup) => depth -= 1,
                _ => {}
            }
        }
    }

    // โ”€โ”€ assignments โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    /// The character one of the six code tables is being asked about.
    ///
    /// `tex.web` ยง434's `scan_char_num`: a number from 0 to 255, or `Bad
    /// character code` reported and 0 used in its place -- whether the code is
    /// the character an assignment changes or the one a code table is read at.
    /// One copy because six callers want it -- the two writers, `\the`, and
    /// ยง413's reader in `scan_number`.
    fn scan_char_code(&mut self, lx: &mut Lexer, pending_only: bool) -> R<char> {
        let mut ch = self.scan_number(lx, pending_only)?;
        // ยง434's `scan_char_num`, over the characters this run has: 256 for
        // TeX82, every Unicode scalar value for LuaTeX (`Bad character code
        // (1114112)` there, measured).
        let last = match self.register_limit > 255 {
            true => 0x10FFFF,
            false => 255,
        };
        let valid = (0..=last).contains(&ch) && char::from_u32(ch as u32).is_some();
        if !valid {
            self.report(lx, &format!("Bad character code ({ch})"));
            ch = 0;
        }
        Ok(char::from_u32(ch as u32).unwrap_or('\0'))
    }

    fn do_catcode(&mut self, lx: &mut Lexer) -> R<()> {
        let c = self.scan_char_code(lx, false)?;
        self.skip_equals(lx)?;
        let mut val = self.scan_number(lx, false)?;
        // ยง1232: a code past the table's range is reported and 0 stored.
        if let Some(msg) = crate::charcodes::invalid_in_range(val, 15) {
            self.report(lx, &msg);
            val = 0;
        }
        let cat = cat_from_i64(val).expect("0..15 is a category");
        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 c = self.scan_char_code(lx, false)?;
        self.skip_equals(lx)?;
        let mut val = self.scan_number(lx, false)?;
        // ยง1232: a code past the table's range is reported and 0 stored.
        if let Some(msg) = table.invalid(val) {
            self.report(lx, &msg);
            val = 0;
        }
        self.save(Save::CharCode(table, c, self.charcodes.get(table, c)));
        self.charcodes.set(table, c, val).map_err(TexError)
    }

    /// 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<()> {
        let out = self.do_charcode(lx, table);
        self.spend_prefixes(out)
    }

    /// 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 c = self.scan_char_code(lx, false)?;
        Ok(self.charcodes.get(table, c))
    }

    /// What the CATCODE table says about a character, for `\the`.
    ///
    /// Separate from `charcode_value` only because the catcode table is not one
    /// of `charcodes`'s five: it is `cats`, which the lexer reads on every
    /// token. ยง413 lists it beside the other five all the same.
    pub fn catcode_value(&mut self, lx: &mut Lexer) -> R<i64> {
        let c = self.scan_char_code(lx, false)?;
        Ok(self.cats.get(c) as i64)
    }

    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 let Some(i) = self.intpar_cs(what) {
            return self.intpar_arith(lx, i, op);
        }
        if what.name() != "count" {
            return Err(TexError(format!("Unsupported register \\{}", what.name())));
        }
        self.not_in_local_control("count")?;
        let reg = self.scan_number(lx, false)?;
        self.skip_by(lx)?;
        let val = self.scan_number(lx, false)?;
        let cur = self.count_value(reg)?;
        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(())
    }

    /// `tex.web` ยง1240's optional `by`, read as ยง407's `scan_keyword` reads it.
    ///
    /// The keyword is OPTIONAL, so a stream that does not spell it has to come
    /// back exactly as it was -- ยง407 ends a failed match with
    /// `back_list(link(backup_head))`, which puts back the WHOLE list it read.
    /// Restoring a saved `pending` and then pushing the offending token as well
    /// put that token back twice whenever it had come from `pending` in the
    /// first place, and the duplicate was read as the next thing the scanner
    /// wanted. `\divide\@tempdima\baselineskip` is the form that finds it:
    /// size10.clo:134 and latex.ltx:10261's
    /// `\def\@settopoint#1{\divide#1\p@\multiply#1\p@}` both write the divisor
    /// with no `by`, and the doubled `\p@` became `! Missing number, found
    /// \p@.`
    fn skip_by(&mut self, lx: &mut Lexer) -> R<()> {
        // Only the letters that MATCHED go in here, which is ยง407's backup list
        // exactly: a space in front of the keyword is dropped rather than
        // stored, and the token that ended the match goes on the end.
        let mut eaten: Vec<Token> = Vec::new();
        for want in ['b', 'y'] {
            let t = loop {
                let Some(t) = lx.next_token(&self.cats) else {
                    lx.push_back(&eaten);
                    return Ok(());
                };
                // A space is skipped while nothing has matched yet (ยง407's
                // `p = backup_head`); once a letter has, it is a mismatch,
                // because the letters of a keyword are adjacent.
                if t.is_space() && eaten.is_empty() {
                    continue;
                }
                break t;
            };
            eaten.push(t);
            if !matches!(&t, Token::Char(c, _) if c.eq_ignore_ascii_case(&want)) {
                // ยง407: `back_input` of the token that failed, then
                // `back_list` of the letters that matched, above it.
                let (matched, failed) = eaten.split_at(eaten.len() - 1);
                lx.back_input(failed);
                if !matched.is_empty() {
                    lx.back_input(matched);
                }
                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 self.is_spacer(t) => continue,
                Token::Char('=', _) => return Ok(()),
                other => {
                    // ยง405: anything else is put back to be read again.
                    lx.back_input(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 self.is_spacer(t) => 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()));
            };
            // ยง442: a control sequence of more than one character is no code at
            // all -- `Improper alphabetic constant`, the token read again, and
            // the code of `"0"` in its place.
            let code = match t {
                Token::Char(c, _) => u32::from(c) as i64,
                Token::Cs(n) if n.name().chars().count() == 1 => {
                    n.name().chars().next().map_or(0, |c| u32::from(c) as i64)
                }
                Token::Cs(_) => {
                    lx.back_input(std::slice::from_ref(&t));
                    self.report(lx, "Improper alphabetic constant");
                    return Ok(sign * i64::from(b'0'));
                }
            };
            // ยง442: "Scan an optional space" -- one space after the constant
            // is absorbed, and reading for it is what reads the NEXT line when
            // the constant ends one (so that line keeps the old `\endlinechar`
            // in `\endlinechar=`\Q`).
            //
            // ยง442 reads it with `get_x_token`, so what follows the constant
            // expands first: expl3's `\romannumeral-`0` runs the expansion
            // behind it to its first unexpandable token, which is the whole
            // of how its `f`-type arguments work.
            loop {
                match self.take(lx, pending_only) {
                    Some(Token::Cs(n)) if self.digit_position_expands(lx, n, pending_only)? => {
                        continue
                    }
                    Some(t) if self.is_spacer(&t) => {}
                    Some(t) => lx.back_input(std::slice::from_ref(&t)),
                    None => {}
                }
                break;
            }
            return Ok(sign * code);
        }
        if let Token::Cs(name) = &cur {
            // A `\let` copy of a primitive is that primitive here (ยง1221):
            // expl3 reads every number through `\__int_eval:w`, which is
            // `\numexpr` under another name.
            let name = self.unaliased(*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_register_slot(lx, pending_only, crate::compiler::RegFile::Count)?;
                return Ok(sign * self.count_value(reg)?);
            }
            if name.name() == "attribute" {
                let n = self.scan_register_number(lx, pending_only)?;
                return Ok(sign * self.attribute_value(n));
            }
            // `tex.web` ยง413: each of the six code tables is an INTERNAL
            // INTEGER, so `\catcode`\@' stands wherever a number is scanned and
            // not only on the left of an assignment. It is the whole of what
            // stopped `ltxcmds.sty' -- and so `bookmark', `kvoptions' and every
            // other package that requires it -- which opens
            //
            //     \begingroup\catcode61\catcode48\catcode32=10\relax
            //
            // `=' is given whatever catcode `0' has BEFORE the space is made a
            // space, so the line reads correctly under any catcode regime the
            // caller left behind. Without this the second \catcode was a
            // command where a number was wanted: `! Missing number, found
            // \catcode.'
            //
            // The table is the engine's own -- catcodes are frontend state
            // here, which is why `compile_time_catcode' exists -- so the answer
            // is known while lowering, exactly as a `\chardef' constant is.
            if name.name() == "catcode" {
                let c = self.scan_char_code(lx, pending_only)?;
                return Ok(sign * self.cats.get(c) as i64);
            }
            if let Some(table) = crate::charcodes::Table::from_name(name.name()) {
                let c = self.scan_char_code(lx, pending_only)?;
                return Ok(sign * self.charcodes.get(table, c));
            }
            // ยง413: a ยง236 parameter is an internal integer too.
            if let Some(i) = self.intpar_cs(name) {
                return Ok(sign * self.intpars.get(i));
            }
            // 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_value(r)?);
                }
                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)?);
            }
            // ยง470's `\number` and ยง478's `\the` are EXPANDABLE primitives, so
            // they stand wherever a number is scanned -- ยง440's `scan_int`
            // reads through `get_x_token`, which expands. They are not in
            // `try_expand` because the two token-producing callers answer them
            // themselves, before the gullet sees them; here the characters they
            // produce are pushed back and the scan resumes on the digits.
            //
            // `amsmath.sty:32` is `\def\do#1{\catcode\number`#1=\number\catcode`#1}`
            // and its `\do\"` on line 39 is what the package opens with.
            if name.name() == "number" || name.name() == "the" {
                let text = self.read_the(lx, name.name() == "number", pending_only)?;
                let toks: Vec<Token> = text.chars().map(|c| Token::Char(c, Cat::Other)).collect();
                lx.push_back(&toks);
                return Ok(sign * self.scan_number(lx, pending_only)?);
            }
            // ยง446: anything else is no number at all. An internal quantity
            // texrs cannot read, or an undefined name, still stops the run.
            let prim = self.primitive_meaning(name);
            // ยง413: a token list or a font family is an internal quantity of
            // the wrong kind here, which is the same "Missing number" with
            // the token put back as for any other command.
            let wrong_kind = prim.name() == "toks"
                || self.toks_cs(name).is_some()
                || matches!(prim.name(), "textfont" | "scriptfont" | "scriptscriptfont");
            if !wrong_kind
                && (crate::primitives::is_internal_quantity(prim.name())
                    || self.meaning_text(&cur) == "undefined")
            {
                return Err(TexError(format!("Missing number, found \\{}", name.name())));
            }
            lx.back_input(&[cur]);
            return Ok(self.missing_number(lx));
        }
        // 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 self.is_spacer(other) && any => break,
                    // ยง445 reads each digit with `get_x_token`: whatever
                    // expands after the first digits expands and the constant
                    // goes on.
                    Token::Cs(n) if self.digit_position_expands(lx, *n, pending_only)? => {}
                    other => {
                        // ยง444: what ends the constant is read again.
                        lx.back_input(std::slice::from_ref(other));
                        break;
                    }
                }
            }
            if !any {
                return Ok(self.missing_number(lx));
            }
            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 self.is_spacer(other) && any => break,
                // ยง445 reads each digit with `get_x_token`: `\count1=1\d`
                // over `\def\d{23}` is 123, and `0\ifx\a\b\else 1\fi` is 01 --
                // latex.ltx's `\IncludeInRelease` builds its test that way.
                Token::Cs(n) if self.digit_position_expands(lx, *n, pending_only)? => {}
                other => {
                    // ยง444: what ends the constant is read again.
                    lx.back_input(std::slice::from_ref(other));
                    break;
                }
            }
            match self.take(lx, pending_only) {
                Some(t) => cur = t,
                None => break,
            }
        }
        if !any {
            return Ok(self.missing_number(lx));
        }
        Ok(sign * value)
    }

    /// Expand `n`, met where ยง445 reads the next digit with `get_x_token`,
    /// and say whether it expanded. A macro, a conditional, `\csname` and the
    /// rest of ยง366's expandable commands do; `\the` and `\number` put back the
    /// characters ยง465 and ยง470 make of their operand, which the digit loop
    /// then reads.
    fn digit_position_expands(&mut self, lx: &mut Lexer, n: CsId, pending_only: bool) -> R<bool> {
        // A name with no meaning ends the constant here and is reported where
        // it is executed; the frontend's own markers (a message body's end)
        // have none, and must end it.
        let defined = match self.meanings.get(&n) {
            Some(Meaning::Macro(_)) => true,
            Some(Meaning::Primitive(p)) => Self::expandable_primitive(p.name()),
            None => self.is_primitive_name(n) && Self::expandable_primitive(n.name()),
            Some(_) => false,
        };
        if defined && self.try_expand(lx, n, pending_only)? {
            return Ok(true);
        }
        self.the_or_number_expands(lx, n, pending_only)
    }

    /// `\the` or `\number` read by `get_x_token`: the characters ยง465 and
    /// ยง470 make of the operand go back to be read. Whether `n` was one.
    fn the_or_number_expands(&mut self, lx: &mut Lexer, n: CsId, pending_only: bool) -> R<bool> {
        let prim = self.primitive_meaning(n);
        if matches!(prim.name(), "the" | "number") && !self.is_macro(n) {
            let text = self.read_the(lx, prim.name() == "number", pending_only)?;
            lx.push_back(&str_toks(&text));
            return Ok(true);
        }
        Ok(false)
    }

    /// ยง446's astonishment that no number was here: reported, with what was
    /// read instead already put back to be read again, and zero in its place.
    fn missing_number(&mut self, lx: &Lexer) -> i64 {
        self.report(lx, "Missing number, treated as zero");
        0
    }

    /// 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;
        // ยง444's `m`: 2^31 over the radix, which for ten is the quotient
        // 214748364 and for eight and sixteen is EXACT -- `"7FFFFFFF` reaches
        // 0x7FFFFFF < 2^27 before its last digit and is in range. `infinity
        // / radix` is one less than that for both, and refused it.
        let m = match radix {
            10 => 214748364,
            8 => 0o2000000000,
            _ => 0o1000000000,
        };
        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> {
        self.scan_left_brace(lx)?;
        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 {
                // ยง367: `\noexpand` makes the token after it unexpandable. Both
                // stay, so the pass that freezes the body sees the marker too.
                Token::Cs(name) if name.name() == "noexpand" => {
                    out.push(t);
                    if let Some(next) = work.pending.pop() {
                        out.push(next);
                    }
                }
                // `\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),
                    }
                }
                // An active character is a control sequence to the expander
                // (ยง366), so `\edef\x{~}` calls the macro `~` means.
                Token::Char(c, Cat::Active) => {
                    let name = Self::active_cs(*c);
                    match matches!(
                        self.meanings.get(&name),
                        Some(Meaning::Macro(m)) if !m.protected
                    ) {
                        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 = 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 {
                // ยง367: the token after `\noexpand` goes into the body as itself.
                Token::Cs(name) if name.name() == "noexpand" => {
                    if let Some(next) = lx.pending.pop() {
                        out.push(next);
                    }
                }
                // ยง478: `\the\toks` in an `\edef` body is the list itself, put
                // in the body without being expanded again.
                Token::Cs(name) if name.name() == "the" => match self.the_token_list(lx, true)? {
                    Some(list) => out.extend(as_body(&list)),
                    None => out.push(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(unmarked(t));
                    }
                }
                Token::Char(c, Cat::Active) => {
                    let name = Self::active_cs(*c);
                    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()));
            }
            // An active character expands like a control sequence (ยง366).
            let name = match &t {
                Token::Cs(name) => self.expandable_alias(*name),
                Token::Char(c, Cat::Active) => Self::active_cs(*c),
                _ => {
                    out.push(t);
                    continue;
                }
            };
            // ยง367: the token after `\noexpand` goes into the body as itself,
            // so `\edef\b{\noexpand\a}` defines a call of `\a`.
            // A `\let` copy is the primitive it copies (expl3's `\exp_not:N`
            // is `\noexpand`); a macro is never one of these.
            let prim = match self.meanings.get(&name) {
                Some(Meaning::Primitive(p)) => *p,
                Some(_) => CsId::intern(""),
                None => name,
            };
            if prim.name() == "noexpand" {
                if let Some(next) = lx.pending.pop() {
                    out.push(next);
                }
                continue;
            }
            // `\unexpanded{...}` is the one thing that stops this pass: its
            // general text goes into the body AS TOKENS (etex.ch: in an \edef
            // the list `the_toks` makes is not expanded again), so a macro
            // inside it is called when the body runs rather than now. Like
            // ยง478's list it goes in as it stands, so a parameter character in
            // it is a character of the body and never starts a parameter:
            // `as_body` writes it the way a stored body says that (luatex:
            // `\edef\y{a\unexpanded{#}b}` is `macro:->a##b`). expl3 builds its
            // `\c__char_..._tl` constants out of a catcode-6 `^^@` exactly so.
            // `\expanded` is the gullet's, in `try_expand`.
            if prim.name() == "unexpanded" {
                let group = self.scan_general_text(&mut lx)?;
                out.extend(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 prim.name() == "the" || prim.name() == "number" {
                let name = prim;
                // ยง478's token-list arm produces TOKENS, and ยง366 puts them in
                // the body without expanding them again. Characters would be a
                // different macro: see `the_token_list`.
                if name.name() == "the" {
                    if let Some(list) = self.the_token_list(&mut lx, true)? {
                        out.extend(list);
                        continue;
                    }
                }
                let text = self.read_the(&mut lx, name.name() == "number", true)?;
                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(unmarked(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 = 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()));
            }
            // A `\let` copy of an expandable primitive is that primitive.
            let t = match t {
                Token::Cs(n) => Token::Cs(self.expandable_alias(n)),
                other => other,
            };
            match &t {
                // ยง367: a `\noexpand`ed token is printed, not expanded.
                Token::Cs(name) if name.name() == "noexpand" => {
                    if let Some(next) = lx.pending.pop() {
                        out.push_str(&self.tokens_shown(&[next]));
                    }
                }
                Token::Cs(name) if name.name() == "the" || name.name() == "number" => {
                    let n = self.read_the(lx, name.name() == "number", true)?;
                    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) => self.sprint_cs(*n),
                            other => other.to_text(self.esc()),
                        });
                    }
                }
                Token::Cs(name) => {
                    let name = *name;
                    if !self.try_expand(lx, name, true)? {
                        out.push_str(&t.to_text(self.esc()));
                    }
                }
                other => out.push_str(&other.to_text(self.esc())),
            }
        }
        lx.pending = saved;
        Ok(out)
    }

    /// ยง478's `token_list` arm: `\the` of a TOKEN register produces the list
    /// itself. `None` -- with the stream left exactly as it was -- when what
    /// follows is any other quantity.
    ///
    /// Separate from `read_the` because the SHAPE of the answer differs, and
    /// ยง366 is why that matters: the tokens are inserted into the `\edef` body
    /// without being expanded again, so a macro inside the register survives as
    /// a call. Rendering them as characters instead froze the SPELLING --
    /// `\edef\x{\the\toks0}` over `\toks0={\inner-x}` gave `\x` the eight
    /// characters `\inner -x` where tex gives it the macro and a later `\x`
    /// prints what `\inner` means then.
    fn the_token_list(&mut self, lx: &mut Lexer, pending_only: bool) -> R<Option<Vec<Token>>> {
        let Some(t) = self.take(lx, pending_only) else {
            return Ok(None);
        };
        let Token::Cs(what) = t else {
            lx.push_back(&[t]);
            return Ok(None);
        };
        // An expression's value is computed here (the operands it reads are
        // the followed registers), so its `\the` is ยง478's characters too.
        if matches!(
            self.unaliased(what).name(),
            "numexpr" | "dimexpr" | "glueexpr" | "muexpr"
        ) {
            lx.push_back(&[Token::Cs(what)]);
            let text = self.read_the(lx, false, pending_only)?;
            return Ok(Some(str_toks(&text)));
        }
        let reg = match what.name() {
            "toks" => self.scan_register_number(lx, pending_only)?,
            _ => match self.toks_cs(what) {
                Some(r) => r,
                None => {
                    lx.push_back(&[Token::Cs(what)]);
                    return Ok(None);
                }
            },
        };
        Ok(Some(self.toks.get(&reg).cloned().unwrap_or_default()))
    }

    /// `tex.web` ยง478's `the_toks`, and `\number<n>` which takes a bare number.
    ///
    /// ยง478 asks `\the` what SHAPE its operand has and writes the value in that
    /// shape: an internal integer becomes its digits, a token register becomes
    /// the tokens themselves. Only `\the\count<n>` was written here, which is
    /// one internal integer out of the several ยง413 lists -- and the missing
    /// ones are what three packages open with. `graphics.sty:34` writes
    /// `\the\catcode`, `amstext.sty:62` writes `\the\toks@`.
    ///
    /// So the integer case is handed to `scan_number`, which is already the
    /// authority on ยง413's internal integers everywhere else a number is
    /// scanned: the six code tables, a `\chardef` or `\countdef` name,
    /// `\numexpr`, and `\count` itself. That is not a widening of what texrs
    /// KNOWS, only of where it is willing to look it up.
    ///
    /// A quantity `scan_number` cannot evaluate errors here, which is the
    /// honest answer: a dimension, a glue or a box lives in a VM slot at run
    /// time rather than in this table, so there is no value to write. Every
    /// caller treats the error as "not frozen" and falls back.
    fn read_the(&mut self, lx: &mut Lexer, bare: bool, pending_only: bool) -> R<String> {
        if bare {
            return Ok(self.scan_number(lx, pending_only)?.to_string());
        }
        // ยง465: the quantity is read with `get_x_token`, so a macro that
        // stands for one expands first.
        let tok = loop {
            let Some(t) = self.take(lx, pending_only) else {
                return Err(TexError("You can't use \\the here".into()));
            };
            match t {
                Token::Cs(n) if self.try_expand(lx, n, pending_only)? => continue,
                t => break t,
            }
        };
        if self.cant_use_after_the(lx, &tok) {
            return Ok("0".into());
        }
        let Token::Cs(what) = tok else {
            return Err(TexError("You can't use \\the here".into()));
        };
        // ยง478's `token_list` arm: the tokens, not a number. A token register
        // is frontend state like a macro body -- see the `toks` field -- so it
        // is as knowable here as a catcode is.
        if what.name() == "toks" {
            let reg = self.scan_register_number(lx, pending_only)?;
            return Ok(self.toks_text(reg));
        }
        if let Some(reg) = self.toks_cs(what) {
            return Ok(self.toks_text(reg));
        }
        // etex.ch's `last_item` arms for the three expressions: `\dimexpr` is a
        // `dimen_val`, `\glueexpr` a `glue_val` and `\muexpr` a `mu_val`, each
        // printed as ยง465 prints its level.
        match self.unaliased(what).name() {
            "dimexpr" => {
                let v = self.scan_expr(lx, pending_only, true)?;
                return Ok(format!("{}pt", crate::dimen::print_scaled(v)));
            }
            expr @ ("glueexpr" | "muexpr") => {
                let mu = expr == "muexpr";
                let outer = std::mem::replace(&mut self.mu_units, mu);
                let g = self.scan_glue_expr(lx);
                self.mu_units = outer;
                let g = g?;
                let unit = if mu { "mu" } else { "pt" };
                return Ok(crate::glue::print_glue_in(
                    unit,
                    g.natural,
                    g.stretch,
                    g.stretch_order,
                    g.shrink,
                    g.shrink_order,
                ));
            }
            _ => {}
        }
        // ยง425 and ยง578: a font's quantities are the lowerer's font memory.
        let name = self.primitive_meaning(what).name();
        if let Some(text) = self.the_font_quantity(lx, name, pending_only)? {
            return Ok(text);
        }
        // ยง465's `dimen_val`, `glue_val` and `mu_val` arms: a dimension is
        // written by ยง103's `print_scaled` and `pt`, a glue by ยง178's
        // `print_spec` -- `pt` or, for a math glue, `mu`. The values are the
        // slots [`crate::known`] follows; one only the run knows is refused by
        // `count_value`, and the caller falls back on the error.
        let is_dimen = match what.name() {
            "dimen" | "skip" | "muskip" => true,
            _ => matches!(
                self.numeric_cs(what),
                Some(NumericCs::Register(r)) if !crate::compiler::is_count_slot(r)
            ),
        };
        if is_dimen {
            let Some((slot, _)) = self.register_slot(lx, what, pending_only)? else {
                return Err(TexError(format!("Unsupported \\the\\{}", what.name())));
            };
            return self.slot_text(slot);
        }
        // ยง478's `int_val` arm. The name goes back so `scan_number` reads the
        // whole quantity, `\catcode`\* and `\numexpr...\relax` included.
        lx.push_back(&[Token::Cs(what)]);
        match self.scan_number(lx, pending_only) {
            Ok(v) => Ok(v.to_string()),
            // Say WHICH quantity has no value here rather than passing on the
            // scanner's "missing number": the name is the whole of what a
            // reader needs to know to port the next one.
            Err(_) => Err(TexError(format!("Unsupported \\the\\{}", what.name()))),
        }
    }

    /// ยง428: `\the` (or `\showthe`) in front of a command that is no internal
    /// quantity -- a character, or a primitive outside ยง413's
    /// `min_internal..max_internal` such as `\relax` or `\end`. tex reports
    /// `You can't use `<print_cmd_chr>' after \the`, keeps the token consumed,
    /// and uses zero. Returns whether `tok` was such a command, the report
    /// made.
    ///
    /// Only a TeX82 primitive is judged: a name this engine adds (e-TeX's,
    /// LuaTeX's) keeps the path it had, so an extension is never refused here
    /// for not being in ยง413's list.
    pub fn cant_use_after_the(&mut self, lx: &Lexer, tok: &Token) -> bool {
        if !self.not_internal(tok) {
            return false;
        }
        let msg = format!(
            "You can't use `{}' after {}the",
            self.meaning_text(tok),
            self.esc()
        );
        self.report(lx, &msg);
        true
    }

    /// Whether `tok`, met where ยง413 wants an internal quantity, is a command
    /// tex knows is none (see [`Self::cant_use_after_the`]).
    fn not_internal(&self, tok: &Token) -> bool {
        let n = match tok {
            Token::Char(c, Cat::Active) => match self.active_meaning(*c) {
                Some(id) => return self.not_internal(&Token::Cs(id)),
                None => return false,
            },
            Token::Char(..) => return true,
            Token::Cs(n) => *n,
        };
        // ยง358: a `\noexpand`ed name is `\relax` where it is read.
        if n.noexpand_origin().is_some() {
            return true;
        }
        match self.meanings.get(&n) {
            Some(Meaning::Char(..)) => true,
            Some(Meaning::Primitive(_)) | None => {
                let p = self.primitive_meaning(n);
                crate::primitives::is_primitive(p.name())
                    && !crate::primitives::is_internal_quantity(p.name())
                    && !crate::primitives::expands(p.name())
                    && !Self::is_conditional(p)
            }
            _ => false,
        }
    }

    /// ยง372: the characters up to `\endcsname`, expanding as it goes. Anything
    /// else unexpandable is `Missing \endcsname inserted`, the token put back
    /// to be read again, and the name ends there.
    fn read_csname(&mut self, lx: &mut Lexer, pending_only: bool) -> R<String> {
        self.in_csname += 1;
        let name = self.read_csname_inner(lx, pending_only);
        self.in_csname -= 1;
        name
    }

    fn read_csname_inner(&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()));
            };
            let expandable = match &t {
                Token::Char(c, Cat::Active) => Some(Self::active_cs(*c)),
                Token::Cs(n) => Some(*n),
                Token::Char(..) => None,
            };
            match (&t, expandable) {
                // ยง372 ends the name at the COMMAND `end_cs_name`, whatever it
                // is spelt: expl3 ends every name with `\cs_end:`, a `\let`
                // copy of `\endcsname`.
                (Token::Cs(n), _) if self.means_primitive(*n, "endcsname") => return Ok(name),
                (Token::Char(c, cat), _) if *cat != Cat::Active => name.push(*c),
                (_, Some(id)) if self.try_expand(lx, id, pending_only)? => {}
                // ยง372 reads with `get_x_token`, so `\the` and `\number` give
                // their characters here too: `\csname x@\the\language\endcsname`.
                (_, Some(id)) if self.the_or_number_expands(lx, id, pending_only)? => {}
                _ => {
                    lx.back_input(&[t]);
                    self.report(lx, "Missing \\endcsname inserted");
                    return Ok(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<()> {
        let out = self.do_def(lx, kind);
        self.spend_prefixes(out)
    }

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

    /// 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, test: &str) -> R<char> {
        self.read_relation(lx, false, test)
    }

    /// `\ifcase` at the top of a file with a selector known while lowering:
    /// ยง509's case selection, with the cases that lose skipped unlowered.
    pub fn ifcase_file(&mut self, lx: &mut Lexer, n: i64, line: u32) -> R<()> {
        self.do_ifcase(lx, n, false, line)
    }

    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 -- and where
    /// in the file each token of the body ended: ยง473 expands a message's text
    /// while it reads it, so an error met in the text is displayed at the
    /// position the scanner had reached. The last token is [`MESSAGE_END`].
    pub fn read_message_body_sited(
        &mut self,
        lx: &mut Lexer,
    ) -> R<(Vec<Token>, crate::lexer::Site)> {
        self.scan_left_brace(lx)?;
        // ยง473: `\message` reads its text with `scan_toks(false, true)`,
        // EXPANDING as it goes, so a brace that `\string` turns into an other
        // character is never counted -- `\message{\string{}` prints `{`. A
        // plain balanced read counted it and ran away. The same holds for
        // `\meaning`, and for the two operands of `\ifx`: each takes its
        // tokens unexpanded, braces included.
        let mut depth = 1usize;
        let mut out = Vec::new();
        let mut ends = vec![lx.pos()];
        let mut lens = vec![lx.pending.len()];
        // How many following tokens the last one read takes for itself.
        let mut raw = 0usize;
        while let Some(t) = lx.next_token(&self.cats) {
            self.note_input_line(lx, Some(&t));
            if raw > 0 {
                raw -= 1;
                out.push(t);
                ends.push(lx.pos());
                lens.push(lx.pending.len());
                continue;
            }
            match &t {
                Token::Char(_, Cat::BeginGroup) => depth += 1,
                Token::Char(_, Cat::EndGroup) => {
                    depth -= 1;
                    if depth == 0 {
                        out.push(Token::cs(MESSAGE_END));
                        ends.push(lx.pos());
                        lens.push(lx.pending.len());
                        let site = lx.site(ends, lens);
                        return Ok((out, site));
                    }
                }
                Token::Cs(n) => match self.primitive_meaning(*n).name() {
                    "string" | "meaning" => raw = 1,
                    "ifx" => raw = 2,
                    _ => {}
                },
                _ => {}
            }
            out.push(t);
            ends.push(lx.pos());
            lens.push(lx.pending.len());
        }
        Err(TexError("Runaway argument".into()))
    }
}

/// 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<()> {
        let out = self.do_futurelet(lx, false);
        self.spend_prefixes(out)
    }

    /// `\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.esc())).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.esc())).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.esc())).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<()> {
        let out = self.do_let(lx);
        self.spend_prefixes(out)
    }

    /// 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, kind: GroupKind, line: u32) {
        self.begin_group(kind, line);
    }
    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;
    }

    /// End an assignment the lowerer handed over: `tex.web` ยง1211's prefixes
    /// belong to the one command they precede, so a `\global` the lowerer set
    /// in front of `\def` must not stand in front of the NEXT assignment too.
    /// Left set, it made every later `\def` global, and a group no longer
    /// undid any of them.
    fn spend_prefixes<T>(&mut self, out: R<T>) -> R<T> {
        self.global = false;
        out
    }

    /// 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 {
        let prefix = std::mem::take(&mut self.global);
        self.global_defs_applied(prefix)
    }
    /// `\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)
    }

    /// "Get the next non-blank non-call token" (ยง406), as `scan_expr` reads
    /// its parentheses and operators: `get_x_token` until something that is
    /// neither a space nor expandable. The brace that ends a `\message` body
    /// is returned as it is, for the caller to put back.
    pub fn next_x_nonblank(&mut self, lx: &mut Lexer, pending_only: bool) -> R<Option<Token>> {
        loop {
            let Some(t) = self.take(lx, pending_only) else {
                return Ok(None);
            };
            if self.is_spacer(&t) {
                continue;
            }
            let name = match t {
                Token::Cs(n) if n.name() == MESSAGE_END => return Ok(Some(t)),
                Token::Cs(n) => n,
                Token::Char(c, Cat::Active) => Self::active_cs(c),
                _ => return Ok(Some(t)),
            };
            if !self.try_expand(lx, name, pending_only)? {
                return Ok(Some(t));
            }
        }
    }

    /// Whether `t` is `relax_cmd` where it is read: `\relax` or a `\let` copy
    /// of it, or ยง358's `dont_expand` token, which reads as `\relax`.
    /// Whether `t`'s command is ยง207's `spacer`: a space token, or a control
    /// sequence `\let` to one (`\let\sp= `, expl3's `\exp_stop_f:`). The
    /// scanners that skip blanks or absorb an optional space test the
    /// command, so both count there; ยง393's argument reader and ยง1215's
    /// `get_r_token` compare the token itself and take only the first.
    pub fn is_spacer(&self, t: &Token) -> bool {
        match t {
            Token::Cs(n) => matches!(self.meanings.get(n), Some(Meaning::Char(_, Cat::Space))),
            t => t.is_space(),
        }
    }

    pub fn means_relax(&self, t: &Token) -> bool {
        match t {
            Token::Cs(n) => {
                n.noexpand_origin().is_some() || self.primitive_meaning(*n).name() == "relax"
            }
            _ => false,
        }
    }

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

    /// ยง433's `scan_eight_bit_int`: a register number, `Bad register code`
    /// and zero in its place when it is outside 0..255.
    ///
    /// Reported where the number ends, so the token that ended it is the
    /// `<to be read again>` of the display, as tex has it.
    /// A register number for one of the slot files or for `\toks`: ยง433's
    /// scan, against this run's [`Engine::register_limit`] -- 255 for TeX82,
    /// 65535 for LuaTeX, which reports a number outside its range the same
    /// way (`Bad register code`, zero used).
    pub fn scan_register_number(&mut self, lx: &mut Lexer, pending_only: bool) -> R<i64> {
        let n = self.scan_number(lx, pending_only)?;
        match (0..=self.register_limit).contains(&n) {
            true => Ok(n),
            false => {
                self.report(lx, &format!("Bad register code ({n})"));
                Ok(0)
            }
        }
    }

    /// A register of `file`, scanned and turned into its slot.
    pub fn scan_register_slot(
        &mut self,
        lx: &mut Lexer,
        pending_only: bool,
        file: crate::compiler::RegFile,
    ) -> R<i64> {
        let n = self.scan_register_number(lx, pending_only)?;
        self.register_address(file, n)
    }

    /// The slot register `reg` of `file` lives in.
    ///
    /// Registers 0 to 255 have the slots `crate::compiler` lays out for them.
    /// One past 255 -- which only a LuaTeX run can name -- is given the next
    /// slot of its file's pool the first time it is named, and keeps it: a
    /// slot is where the run keeps the value, so the same register must always
    /// be the same slot.
    pub fn register_address(&mut self, file: crate::compiler::RegFile, reg: i64) -> R<i64> {
        if reg < 256 {
            return Ok(file.low_base() + reg * file.stride());
        }
        if let Some(&slot) = self.high_slots.get(&(file, reg)) {
            return Ok(slot);
        }
        let (base, size) = file.high_pool();
        let used = &mut self.high_used[file as usize];
        if *used >= size {
            return Err(TexError(format!(
                "TeX capacity exceeded, sorry [\\{} registers past 255={size}]",
                file.name()
            )));
        }
        let slot = base + *used * file.stride();
        *used += 1;
        self.high_slots.insert((file, reg), slot);
        self.high_names.insert(slot, (file, reg));
        Ok(slot)
    }

    /// Put back the pooled registers a format carried, replacing any this
    /// engine has given out.
    pub fn restore_pooled(
        &mut self,
        pooled: impl IntoIterator<Item = (i64, crate::compiler::RegFile, i64)>,
    ) {
        self.high_slots.clear();
        self.high_names.clear();
        self.high_used = [0; 4];
        for (slot, file, reg) in pooled {
            self.high_slots.insert((file, reg), slot);
            self.high_names.insert(slot, (file, reg));
            let (base, _) = file.high_pool();
            let next = (slot - base) / file.stride() + 1;
            let used = &mut self.high_used[file as usize];
            *used = (*used).max(next);
        }
    }

    /// The register a pooled slot was given to, for a display.
    pub fn pooled_register(&self, slot: i64) -> Option<(crate::compiler::RegFile, i64)> {
        self.high_names.get(&slot).copied()
    }

    /// Every pooled register and its slot, in slot order: what a format has to
    /// carry so that a register is the same slot after it is loaded.
    pub fn pooled_registers(&self) -> Vec<(i64, crate::compiler::RegFile, i64)> {
        let mut out: Vec<_> = self
            .high_names
            .iter()
            .map(|(slot, (file, reg))| (*slot, *file, *reg))
            .collect();
        out.sort_unstable_by_key(|(slot, ..)| *slot);
        out
    }

    pub fn scan_register_any(&mut self, lx: &mut Lexer, pending_only: bool) -> R<i64> {
        let n = self.scan_number(lx, pending_only)?;
        match (0..=255).contains(&n) {
            true => Ok(n),
            false => {
                self.report(lx, &format!("Bad register code ({n})"));
                Ok(0)
            }
        }
    }

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

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

    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, test: &str) -> R<char> {
        self.read_relation(lx, pending_only, test)
    }
}

/// 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)
    }
    /// `\let\name=\relax`, for a construct the lowerer runs as a whole: plain's
    /// `\loop` leaves `\next` meaning `\relax` when it ends.
    pub fn let_relax(&mut self, name: CsId) {
        self.set_meaning(name, Meaning::Primitive(CsId::intern("relax")));
    }

    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)
    }

    /// A definition's parameter text and body exactly as `\def` reads them
    /// (ยง473, ยง476, ยง479), for the `\edef` the lowerer snapshots: the same
    /// numbering checks, the same recovery from a bad `#`, and the left brace
    /// of a trailing `#{` returned so the caller can end the body with it.
    /// `\edef`'s parameter text and body (ยง473 with `xpand` true): the
    /// parameter text as `\def` reads it, and the body EXPANDED AS IT IS
    /// READ, never read whole first. That difference is what lets a body
    /// hold `\unexpanded{... # ...}` or `\the\toks` over a list with a `#` in
    /// it: ยง477 links such a list into the body as it stands, past ยง479's
    /// check for a parameter number, so its `#` is a character of the body
    /// (written `##`, as a stored body writes one). Read first and expanded
    /// after, every one of those was `Illegal parameter number`. A `#` the
    /// expansion produces any other way is ยง479's, followed by a digit
    /// read with `get_x_token`.
    pub fn read_edef_parts(
        &mut self,
        lx: &mut Lexer,
        name: CsId,
        frozen: &mut Frozen,
    ) -> R<(Vec<Token>, Vec<Token>)> {
        let (params, hash_brace) = self.scan_parameter_text(lx)?;
        validate_params(&params)?;
        let count = params
            .iter()
            .filter(|p| matches!(p, Token::Char(_, Cat::Param)))
            .count() as u32;
        let mut body = self.scan_toks_x(lx, Some((name, count)), frozen)?;
        // ยง473: a parameter text that ended with `#{` appends that brace.
        body.extend(hash_brace);
        Ok((params, body))
    }

    /// `\the` of a quantity the stomach holds (`\spacefactor`, `\prevdepth`,
    /// the rest of [`crate::stomach::Internal`]), which only the run knows:
    /// the value is copied, where the `\edef` stands, into a scratch register
    /// of its kind, and the body reads that register -- so it holds the value
    /// of the moment, as ยง478's characters would. `None`, with nothing read,
    /// for any other quantity.
    fn freeze_internal(&mut self, lx: &mut Lexer, frozen: &mut Frozen) -> Option<Vec<Token>> {
        let t = self.take(lx, false)?;
        let internal = match &t {
            Token::Cs(w) => crate::stomach::Internal::of_name(self.unaliased(*w).name()),
            Token::Char(..) => None,
        };
        let Some(i) = internal else {
            lx.back_input(&[t]);
            return None;
        };
        let (file, kind) = match i.is_dimen() {
            true => (crate::compiler::DIMEN_BASE, "dimen"),
            false => (0, "count"),
        };
        let at = frozen.next_scratch;
        frozen.next_scratch -= 1;
        frozen.snapshots.push(crate::ir::Cmd::SetCount(
            file + at,
            crate::ir::Num::Count(i.slot()),
        ));
        let mut toks = vec![Token::cs("the"), Token::cs(kind)];
        toks.extend(str_toks(&at.to_string()));
        Some(toks)
    }

    /// The loop of ยง473 with `xpand` true, after the left brace: `def` is the
    /// macro being defined and its parameter count, when this is a body.
    fn scan_toks_x(
        &mut self,
        lx: &mut Lexer,
        def: Option<(CsId, u32)>,
        frozen: &mut Frozen,
    ) -> R<Vec<Token>> {
        let as_written = |list: &[Token]| match def {
            Some(_) => as_body(list),
            None => list.to_vec(),
        };
        let mut depth = 1usize;
        let mut out = Vec::new();
        let mut steps = 0usize;
        loop {
            steps += 1;
            if steps > 5_000_000 {
                return Err(TexError("TeX capacity exceeded".into()));
            }
            let Some(t) = self.take(lx, false) else {
                return Err(TexError("Runaway definition".into()));
            };
            // ยง477: expand what expands. A `\protected` macro does not.
            let cs = match &t {
                Token::Cs(n) => Some(*n),
                Token::Char(c, Cat::Active) => Some(Self::active_cs(*c)),
                Token::Char(..) => None,
            };
            if let Some(n) = cs {
                if n.noexpand_origin().is_none() {
                    let prim = match self.meanings.get(&n) {
                        Some(Meaning::Primitive(p)) => *p,
                        Some(_) => CsId::intern(""),
                        None => n,
                    };
                    // ยง367: the token after `\noexpand` goes in as itself when
                    // it would expand; anything else is read again as usual,
                    // so a brace after it (`\everyeof{\noexpand}` at the end of
                    // a `\scantokens`) still counts.
                    if prim.name() == "noexpand" {
                        if let Some(next) = self.take(lx, false) {
                            let expandable = match &next {
                                Token::Cs(m) => self.is_expandable(*m),
                                Token::Char(c, Cat::Active) => {
                                    self.is_expandable(Self::active_cs(*c))
                                }
                                Token::Char(..) => false,
                            };
                            match expandable {
                                true => out.push(unmarked(next)),
                                false => lx.back_input(&[next]),
                            }
                        }
                        continue;
                    }
                    // ยง477's `the` arm, `\unexpanded` with it (etex.ch): the
                    // list goes in as it stands.
                    if prim.name() == "unexpanded" {
                        let group = self.scan_general_text(lx)?;
                        out.extend(as_written(&group));
                        continue;
                    }
                    if prim.name() == "the" {
                        if let Some(list) = self.the_token_list(lx, false)? {
                            out.extend(as_written(&list));
                            continue;
                        }
                        if let Some(toks) = self.freeze_internal(lx, frozen) {
                            out.extend(toks);
                            continue;
                        }
                        let text = self.read_the(lx, false, false)?;
                        out.extend(str_toks(&text));
                        continue;
                    }
                    if prim.name() == "number" {
                        let text = self.read_the(lx, true, false)?;
                        out.extend(str_toks(&text));
                        continue;
                    }
                    let protected = matches!(
                        self.meanings.get(&n),
                        Some(Meaning::Macro(m)) if m.protected
                    );
                    if !protected && self.try_expand(lx, n, false)? {
                        continue;
                    }
                }
                out.push(unmarked(t));
                continue;
            }
            match &t {
                Token::Char(_, Cat::BeginGroup) => depth += 1,
                Token::Char(_, Cat::EndGroup) => {
                    depth -= 1;
                    if depth == 0 {
                        return Ok(out);
                    }
                }
                // ยง479: a parameter character is a parameter number or `##`,
                // the next token read with `get_x_token`.
                Token::Char(_, Cat::Param) if def.is_some() => {
                    let (name, count) = def.expect("just matched");
                    let next = loop {
                        let Some(next) = self.take(lx, false) else {
                            return Err(TexError("Runaway definition".into()));
                        };
                        match next {
                            Token::Cs(m) if self.try_expand(lx, m, false)? => continue,
                            next => break next,
                        }
                    };
                    let legal = match next {
                        Token::Char(_, Cat::Param) => true,
                        Token::Char(c, _) => c.to_digit(10).is_some_and(|d| d >= 1 && d <= count),
                        Token::Cs(_) => false,
                    };
                    out.push(t);
                    match legal {
                        true => out.push(next),
                        false => {
                            lx.back_input(&[next]);
                            let msg = format!(
                                "Illegal parameter number in definition of {}",
                                self.sprint_cs(name)
                            );
                            self.report(lx, &msg);
                            out.push(t);
                        }
                    }
                    continue;
                }
                _ => {}
            }
            out.push(t);
        }
    }

    pub fn read_def_parts(
        &mut self,
        lx: &mut Lexer,
        name: CsId,
    ) -> R<(Vec<Token>, Vec<Token>, Option<Token>)> {
        let (params, hash_brace) = self.scan_parameter_text(lx)?;
        validate_params(&params)?;
        let body = self.read_def_body(lx, name, &params)?;
        Ok((params, body, hash_brace))
    }

    /// ยง380's `get_x_token` for a caller outside the expander: the next token
    /// that does not expand, every one before it expanded, and what it MEANS
    /// as a primitive when it is a control sequence.
    pub fn next_unexpandable(&mut self, lx: &mut Lexer) -> R<Option<(Token, Option<CsId>)>> {
        while let Some(t) = lx.next_token(&self.cats) {
            let Token::Cs(n) = t else {
                return Ok(Some((t, None)));
            };
            if !self.try_expand(lx, n, false)? {
                return Ok(Some((t, Some(self.primitive_meaning(n)))));
            }
        }
        Ok(None)
    }

    /// The text of a `\write`, as ยง1352 reads it: `scan_toks(false, false)`,
    /// so ยง403's `scan_left_brace` expands its way to the brace and the list
    /// itself is taken UNEXPANDED. ยง1371's `write_out` expands it later.
    pub fn read_write_text(&mut self, lx: &mut Lexer) -> R<Vec<Token>> {
        self.scan_left_brace(lx)?;
        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, test: &str) -> R<char> {
        self.read_relation(lx, true, test)
    }
    /// ยง494's skip over pending tokens: to the matching `\else` (when
    /// `stop_at_else`) or `\fi`, consuming it, and saying whether it was an
    /// `\else`.
    pub fn skip_to_pending(&mut self, lx: &mut Lexer, stop_at_else: bool) -> R<bool> {
        self.skip_to(lx, stop_at_else, 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(Rc::new(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.
    ///
    /// `global` is `\xdef`, or an `\edef` under a `\global` prefix: the
    /// definition survives every enclosing group, as `do_def` makes a `\gdef`.
    /// The prefixes are spent here for the reason `do_def` spends them.
    /// ยง436's `scan_four_bit_int`, for a stream number: out of range is
    /// reported and read as 0.
    pub fn scan_stream_number(&mut self, lx: &mut Lexer, pending_only: bool) -> R<usize> {
        let n = self.scan_number(lx, pending_only)?;
        if !(0..=15).contains(&n) {
            self.report(lx, &format!("Bad number ({n})"));
            return Ok(0);
        }
        Ok(n as usize)
    }

    /// ยง1275's `\openin`: close stream `n`, then open it on `text` -- the file
    /// the name found, or `None` when nothing has it, which leaves the stream
    /// closed.
    pub fn open_read_stream(&mut self, n: usize, text: Option<String>) {
        self.read_streams[n] = text.map(|t| ReadStream {
            lines: t.lines().map(str::to_string).collect(),
        });
    }

    /// Whether stream `n` is closed, which is what `\ifeof` asks.
    pub fn read_stream_closed(&self, n: usize) -> bool {
        self.read_streams[n].is_none()
    }

    /// ยง1275's `\closein`.
    pub fn close_read_stream(&mut self, n: usize) {
        self.read_streams[n] = None;
    }

    /// `\read<number> to <cs>` (ยง1225): the next line or lines of the stream,
    /// as tokens, become the macro's body.
    pub fn compile_time_read(&mut self, lx: &mut Lexer) -> R<()> {
        let out = self.do_read(lx, false);
        self.spend_prefixes(out)
    }

    /// e-TeX's `\readline<number> to <cs>` (etex.ch ยง1445): one line, every
    /// character of it -- the `\endlinechar` too -- an other character, and
    /// the space a space.
    pub fn compile_time_readline(&mut self, lx: &mut Lexer) -> R<()> {
        let out = self.do_read(lx, true);
        self.spend_prefixes(out)
    }

    fn do_read(&mut self, lx: &mut Lexer, line_only: bool) -> R<()> {
        let global = self.global;
        let n = self.scan_number(lx, false)?;
        if !self.scan_keyword(lx, "to", false)? {
            self.report(lx, "Missing `to' inserted");
        }
        // ยง1215's `get_r_token`: the next non-blank token, which must be a
        // control sequence.
        let name = self.get_r_token(lx, false)?;
        let body = match line_only {
            true => self.read_line_toks(lx, n)?,
            false => self.read_toks(lx, n)?,
        };
        self.define_macro_with_params(name, Vec::new(), body, global)
    }

    /// etex.ch ยง1445's `j=1` arm of `read_toks`: the line's characters as
    /// they are, other except the space. LuaTeX leaves the `\endlinechar`
    /// off (`\meaning` of the line shows none, measured), where etex.ch
    /// keeps it.
    fn read_line_toks(&mut self, _lx: &Lexer, n: i64) -> R<Vec<Token>> {
        let m = usize::try_from(n).ok().filter(|m| *m < 16);
        let line = match m.and_then(|m| self.read_streams[m].as_mut()) {
            None => self.term_input()?,
            Some(stream) => match stream.lines.pop_front() {
                Some(line) => line,
                None => {
                    self.read_streams[m.expect("an open stream")] = None;
                    String::new()
                }
            },
        };
        let line = line.trim_end_matches([' ', '\t', '\r']);
        let toks: Vec<Token> = line
            .chars()
            .map(|c| match c {
                ' ' => Token::Char(' ', Cat::Space),
                c => Token::Char(c, Cat::Other),
            })
            .collect();
        Ok(toks)
    }

    /// ยง482's `read_toks`: a line from stream `n`, read with the category
    /// codes in force and ended by `\endlinechar`, and more lines while its
    /// braces are open. A `}` with no `{` before it ends the line there.
    fn read_toks(&mut self, lx: &Lexer, n: i64) -> R<Vec<Token>> {
        let m = usize::try_from(n).ok().filter(|m| *m < 16);
        let mut toks = Vec::new();
        // ยง483's `align_state`, less its 1000000.
        let mut depth = 0i64;
        loop {
            // ยง484: a closed stream, or a number outside 0..15, reads the
            // terminal.
            let line = match m.and_then(|m| self.read_streams[m].as_mut()) {
                None => self.term_input()?,
                Some(stream) => match stream.lines.pop_front() {
                    Some(line) => line,
                    // ยง485 and ยง486: a file that has run out is closed, and the
                    // line it gave is empty -- which reads as a `\par`. Running out
                    // with a brace still open is an error.
                    None => {
                        self.read_streams[m.expect("an open stream")] = None;
                        if depth != 0 {
                            self.report(lx, "File ended within \\read");
                            depth = 0;
                        }
                        String::new()
                    }
                },
            };
            // ยง31's `input_ln` drops the line's trailing blanks.
            let line = line.trim_end_matches([' ', '\t', '\r']);
            let mut mouth = Lexer::new(&format!("{line}\n"));
            while let Some(t) = mouth.next_token(&self.cats) {
                match t {
                    Token::Char(_, Cat::BeginGroup) => depth += 1,
                    Token::Char(_, Cat::EndGroup) => depth -= 1,
                    _ => {}
                }
                if depth < 0 {
                    depth = 0;
                    break;
                }
                toks.push(t);
            }
            if depth == 0 {
                return Ok(toks);
            }
        }
    }

    /// ยง71's `term_input`, reached from ยง484 when a `\read` finds no open
    /// stream: the next line of the terminal an embedder attached through
    /// [`with_terminal`]. The prompt ยง484 prints first (`\cs=` for a stream
    /// number of 0 or more) and ยง71's echo to the log are not kept; an
    /// embedded run returns the document's text, which neither belongs to.
    ///
    /// With no terminal attached, or in batch or nonstop mode, it is ยง484's
    /// fatal error; a terminal that has run out is ยง71's.
    fn term_input(&mut self) -> R<String> {
        let line = match self.interaction > 1 {
            true => TERMINAL.with(|t| t.borrow_mut().as_mut().map(VecDeque::pop_front)),
            false => None,
        };
        match line {
            Some(Some(line)) => Ok(line),
            Some(None) => Err(TexError("*** (job aborted, no legal \\end found)".into())),
            None => Err(TexError(
                "*** (cannot \\read from terminal in nonstop modes)".into(),
            )),
        }
    }

    pub fn define_macro_with_params(
        &mut self,
        name: CsId,
        params: Vec<Token>,
        body: Vec<Token>,
        global: bool,
    ) -> R<()> {
        validate_params(&params)?;
        let was = std::mem::replace(&mut self.global, global);
        self.set_meaning(name, Meaning::Macro(Rc::new(self.new_macro(params, body))));
        self.global = was;
        self.long = false;
        self.outer = false;
        self.protected = false;
        Ok(())
    }
}

/// A token list as an `\edef` body holds it, for ยง478's `the_toks` arm.
///
/// ยง478 links `\the\toks`'s list straight into the body, past the parameter
/// scan of ยง479, so a macro-parameter character in it is an ordinary `#` of the
/// body: `\edef\x{\the\toks0}` over `a#b` means `macro:->a##b`, and `\x`
/// expands to `a#b`. A body here is stored as written, where a lone `#` is the
/// start of a parameter and `##` is one `#`, so each one is doubled.
fn as_body(list: &[Token]) -> Vec<Token> {
    let mut out = Vec::with_capacity(list.len());
    for t in list {
        if matches!(t, Token::Char(_, Cat::Param)) {
            out.push(*t);
        }
        out.push(*t);
    }
    out
}

/// 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(())
}

/// `tex.web` ยง69's `print_roman_int`, over the same pool string
/// `"m2d5c2l5x2v5i"`: each letter is followed by the divisor that gives the
/// next one's value, and a subtractive pair (`cm`, `iv`) is found by looking
/// one or two letters ahead. A number that is not positive prints nothing.
/// Whether a new engine is LuaTeX in its register ranges: set once by the
/// command line's `--luatex` (and `-progname=lualatex`), for a whole process.
/// A LaTeX document's engine is made LuaTeX-ranged where it is built, whatever
/// this says, since what that path replaces is `lualatex`.
static LUATEX_REGISTERS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

/// Make every engine built after this LuaTeX-ranged, or TeX82-ranged again.
/// What an `\edef` body that reads a quantity only the run has leaves for
/// the lowerer: the copies into scratch registers (counting down from
/// `next_scratch`) that must run where the `\edef` stands.
pub struct Frozen {
    pub next_scratch: i64,
    pub snapshots: Vec<crate::ir::Cmd>,
}

pub fn set_luatex_registers(on: bool) {
    LUATEX_REGISTERS.store(on, std::sync::atomic::Ordering::Relaxed);
}

/// What an attribute register holds before anything assigns it: LuaTeX's
/// `UNUSED_ATTRIBUTE`, `-0x7FFFFFFF`, which `\the` prints as `-2147483647`.
pub const UNUSED_ATTRIBUTE: i64 = -0x7FFF_FFFF;

/// LuaTeX's highest register number (the LuaTeX manual, "Registers": 65536 of
/// each kind), against TeX82's 255.
pub const LUATEX_REGISTER_LIMIT: i64 = 65535;

fn default_register_limit() -> i64 {
    match LUATEX_REGISTERS.load(std::sync::atomic::Ordering::Relaxed) {
        true => LUATEX_REGISTER_LIMIT,
        false => 255,
    }
}

pub fn roman_int(mut n: i64) -> String {
    const POOL: &[u8] = b"m2d5c2l5x2v5i";
    let mut out = String::new();
    let mut j = 0usize;
    let mut v = 1000i64;
    loop {
        while n >= v {
            out.push(POOL[j] as char);
            n -= v;
        }
        if n <= 0 {
            return out;
        }
        let mut k = j + 2;
        let mut u = v / i64::from(POOL[k - 1] - b'0');
        if POOL[k - 1] == b'2' {
            k += 2;
            u /= i64::from(POOL[k - 1] - b'0');
        }
        if n + u >= v {
            out.push(POOL[k] as char);
            n += u;
        } else {
            j += 2;
            v /= i64::from(POOL[j - 1] - b'0');
        }
    }
}

/// ยง1238-ยง1240 on an integer: `\advance` is a 32-bit word's addition, which
/// wraps (`tests/cases/advance_wraps_at_32_bits.tex`), while `\multiply` and
/// `\divide` are ยง105's `mult_integers` and ยง106's `x_over_n`, which refuse a
/// result outside the 32-bit range and a zero divisor -- `None`, for the caller
/// to report. The quotient truncates toward zero.
fn arith_int(cur: i64, val: i64, op: Arith) -> Option<i64> {
    let result = match op {
        Arith::Add => return Some(i64::from((cur as i32).wrapping_add(val as i32))),
        Arith::Mul => cur.checked_mul(val),
        Arith::Div => match val {
            0 => None,
            d => cur.checked_div(d),
        },
    };
    result.filter(|v| (i64::from(i32::MIN)..=i64::from(i32::MAX)).contains(v))
}

/// ยง464's `str_toks`: a printed string as the tokens a `convert` primitive
/// (`\string`, `\meaning`) expands to -- category 12 for every character but
/// the space, which is a space token, so the result can delimit an argument.
pub fn str_toks(text: &str) -> Vec<Token> {
    text.chars()
        .map(|c| match c {
            ' ' => Token::Char(' ', Cat::Space),
            c => Token::Char(c, Cat::Other),
        })
        .collect()
}

/// What e-TeX's and LuaTeX's version `convert` commands expand to, measured
/// against luatex 1.24.0: `\eTeXrevision` is `.2`, `\eTeXVersion` is `2.2`
/// and `\luatexrevision` is `0`.
pub fn constant_text(primitive: &str) -> Option<&'static str> {
    match primitive {
        "eTeXrevision" => Some(".2"),
        "eTeXVersion" => Some("2.2"),
        "luatexrevision" => Some("0"),
        _ => None,
    }
}

impl Engine {
    /// The integer parameter `name` (`crate::intpar::NAMES`), by name.
    pub fn intpar_named(&self, name: &str) -> i64 {
        crate::intpar::index(name).map_or(0, |i| self.intpars.get(i))
    }
}

impl Engine {
    /// Whether `name` is a primitive that still means itself: what
    /// `\ifprimitive` asks (conditional.c compares `cur_cmd` and `cur_chr`
    /// with the primitive's own).
    pub fn means_its_primitive(&self, name: CsId) -> bool {
        let primitive = crate::primitives::is_primitive(name.name())
            || crate::intpar::index(name.name()).is_some()
            || crate::primitives::luatex_command(name.name()).is_some();
        primitive
            && match self.meanings.get(&name) {
                None => true,
                Some(Meaning::Primitive(p)) => *p == name,
                Some(_) => false,
            }
    }
}

impl Engine {
    /// Whether a `\csname` is reading its name now (`\ifincsname`).
    pub fn in_csname(&self) -> bool {
        self.in_csname > 0
    }
}

/// The control sequence luatex's `id_lookup` answers for a name it does not
/// find (`undefined_control_sequence`), which `\lastnamedcs` puts back after
/// an `\ifcsname` or `\begincsname` that found nothing. The NUL keeps any
/// document from spelling it, so it is never defined.
pub const UNDEFINED_CS: &str = "\u{0}undefined";

impl Engine {
    /// The control sequence a `\csname` (`defines`) or a `\begincsname` and
    /// `\ifcsname` built from `built`, recorded as `last_cs_name`.
    ///
    /// `\csname` makes the name `\relax` if it means nothing (ยง372) and always
    /// answers it. The other two look it up without entering it, and answer it
    /// only if it is defined. An empty name is luatex's `null_cs`, which none
    /// of them records and `\begincsname` never puts back.
    pub fn named_cs(&mut self, built: &str, defines: bool) -> Option<CsId> {
        let id = CsId::intern(built);
        if defines {
            self.define_if_undefined(built);
            self.last_cs_name = (!built.is_empty()).then_some(id);
            return Some(id);
        }
        // `null_cs` is a control sequence like any other to `\ifcsname`
        // (`\csname\endcsname` can be `\let`), but is never recorded.
        if built.is_empty() {
            self.last_cs_name = None;
            return (!self.is_undefined(id)).then_some(id);
        }
        match self.is_undefined(id) {
            false => {
                self.last_cs_name = Some(id);
                Some(id)
            }
            true => {
                self.last_cs_name = Some(CsId::intern(UNDEFINED_CS));
                None
            }
        }
    }
}

impl Engine {
    /// luatex's `diagnostic_trace` of a control sequence's entry: `{changing
    /// \a=macro:->x}`, as `show_eqtb` writes it.
    fn trace_entry(&mut self, verb: &str, name: CsId) {
        let shown = format!(
            "{{{verb} {}={}}}",
            self.sprint_cs(name),
            self.meaning_text(&Token::Cs(name))
        );
        self.diagnostic(&shown);
    }

    /// The same for integer parameter `i`: `{changing \tolerance=10000}`.
    fn trace_intpar(&mut self, verb: &str, i: usize) {
        let shown = format!(
            "{{{verb} {}{}={}}}",
            self.esc(),
            crate::intpar::NAMES[i],
            self.intpars.get(i)
        );
        self.diagnostic(&shown);
    }

    /// The same for token register or parameter `reg`: `{into \toks0=a}`.
    fn trace_toks(&mut self, verb: &str, reg: i64) {
        let name = match reg >= crate::params::TOKS_BASE {
            true => crate::params::TOKS_NAMES
                .get((reg - crate::params::TOKS_BASE) as usize)
                .map_or_else(String::new, |n| n.to_string()),
            false => format!("toks{reg}"),
        };
        let shown = format!("{{{verb} {}{name}={}}}", self.esc(), self.toks_shown(reg));
        self.diagnostic(&shown);
    }
}

impl Engine {
    /// The register in `slot`, spelt as `\showthe` and `\tracingassigns`
    /// spell it: `\count1`, `\dimen0`, `\hsize`.
    pub fn register_name_pub(&self, slot: i64) -> String {
        self.register_name(slot)
    }
}

impl Engine {
    /// Make table `to` the one the mouth reads with (LuaTeX's catcode tables,
    /// textcodes.c). The table being left keeps its codes for a later switch
    /// back; `\endlinechar`, which the table carries for the mouth, is the
    /// parameter's whichever table is current.
    fn switch_cat_table(&mut self, to: i64) {
        if to == self.cat_table {
            return;
        }
        let Some(next) = self.cat_tables.remove(&to) else {
            return;
        };
        let generation = self.cats.generation();
        let left = std::mem::replace(&mut self.cats, next);
        self.cat_tables.insert(self.cat_table, left);
        self.cat_table = to;
        self.cats.follow_generation(generation);
        self.cats
            .set_end_line_char(self.intpars.get(crate::intpar::END_LINE_CHAR));
    }

    /// Whether `\catcodetable` may switch to table `h` (`valid_catcode_table`).
    pub fn valid_cat_table(&self, h: i64) -> bool {
        h == self.cat_table
            || (self.cat_tables.contains_key(&h) && !self.unset_cat_tables.contains(&h))
    }

    /// textcodes.c's `get_cat_code(h, c)`: the code `c` has in table `h`. A
    /// table nothing has made answers `CATCODEDEFAULT`, 12, as it does there.
    pub fn cat_code_in(&self, table: i64, c: u32) -> i64 {
        let c = char::from_u32(c).unwrap_or('\0');
        let cat = match table == self.cat_table {
            true => self.cats.get(c),
            false => match self.cat_tables.get(&table) {
                Some(t) => t.get(c),
                None => Cat::Other,
            },
        };
        cat as i64
    }

    /// textcodes.c's `set_cat_code(h, c, v, level)`: assign in table `h`,
    /// saved for the group (or not, `global`) as `\catcode` is, making the
    /// table -- every code 12, and not yet one `\catcodetable` may select --
    /// when nothing has made it. A code outside 0..15 is not assigned.
    pub fn assign_cat_code_in(&mut self, table: i64, c: u32, v: i64, global: bool) {
        let (Some(c), Some(cat)) = (char::from_u32(c), cat_from_i64(v)) else {
            return;
        };
        if table == self.cat_table {
            self.save_as(
                Save::Cat(table, c, self.cats.get(c)),
                self.global_defs_applied(global),
            );
            self.cats.set(c, cat);
            return;
        }
        if let std::collections::hash_map::Entry::Vacant(e) = self.cat_tables.entry(table) {
            e.insert(CatTable::all_other());
            self.unset_cat_tables.insert(table);
        }
        let old = self.cat_tables[&table].get(c);
        self.save_as(Save::Cat(table, c, old), self.global_defs_applied(global));
        if let Some(t) = self.cat_tables.get_mut(&table) {
            t.set(c, cat);
        }
    }

    /// `\catcodetable=n` (maincontrol.c's `assign_internal_value`): a switch to
    /// a valid table, local unless `\global`, or `Invalid \catcode table`.
    pub fn compile_time_catcodetable(&mut self, lx: &mut Lexer) -> R<()> {
        self.skip_equals(lx)?;
        let to = self.scan_number(lx, false)?;
        let global = self.take_global_prefix();
        if !self.valid_cat_table(to) {
            self.report(lx, "Invalid \\catcode table");
            return Ok(());
        }
        if to != self.cat_table {
            self.save_as(Save::CatTable(self.cat_table), global);
            self.switch_cat_table(to);
        }
        Ok(())
    }

    /// `\savecatcodetable n` and `\initcatcodetable n` (maincontrol.c's
    /// `run_normal`): table `n` becomes a copy of the current one, or
    /// INITEX's. Neither may name the current table, or one outside 0..0x7FFF.
    pub fn compile_time_catcode_table_copy(&mut self, lx: &mut Lexer, init: bool) -> R<()> {
        let n = self.scan_number(lx, false)?;
        if !(0..=0x7FFF).contains(&n) || n == self.cat_table {
            self.report(lx, "Invalid \\catcode table");
            return Ok(());
        }
        let table = match init {
            true => CatTable::new(),
            false => self.cats.clone(),
        };
        self.cat_tables.insert(n, table);
        self.unset_cat_tables.remove(&n);
        Ok(())
    }
}

impl Engine {
    /// Whether this engine is a LuaTeX: LuaTeX-ranged by the command line's
    /// program name or by being a LaTeX run (`register_limit`), which is also
    /// what decides the few places luatex prints differently from tex.
    pub fn is_luatex(&self) -> bool {
        self.register_limit > 255
    }
}

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

    #[test]
    fn a_code_set_in_another_table_is_restored_there_and_does_not_validate_it() {
        let mut eng = Engine::new();
        // Table 4 does not exist: it reads 12 everywhere, as textcodes.c's
        // CATCODEDEFAULT, and assigning in it makes it without making it valid.
        assert_eq!(eng.cat_code_in(4, u32::from('a')), 12);
        eng.compile_time_begin_group(GroupKind::Simple, 1);
        eng.assign_cat_code_in(4, u32::from('a'), 11, false);
        assert_eq!(eng.cat_code_in(4, u32::from('a')), 11);
        assert!(!eng.valid_cat_table(4));
        // The current table is untouched by it.
        assert_eq!(eng.cat_code_in(0, u32::from('{')), 12);
        eng.compile_time_end_group().unwrap();
        assert_eq!(eng.cat_code_in(4, u32::from('a')), 12);
        // A global one survives the group.
        eng.compile_time_begin_group(GroupKind::Simple, 1);
        eng.assign_cat_code_in(0, u32::from('{'), 1, true);
        eng.compile_time_end_group().unwrap();
        assert_eq!(eng.cat_code_in(0, u32::from('{')), 1);
    }
}

/// luatex's conditionals in its order, `\currentiftype` being the position
/// plus one: measured for each but `\iffontchar`, which lies between
/// `\ifcsname` (19) and `\ifincsname` (21), and `\ifcondition`, which never
/// stays open to be asked about.
const CONDITIONAL_CODES: [Option<&str>; 25] = [
    Some("if"),
    Some("ifcat"),
    Some("ifnum"),
    Some("ifdim"),
    Some("ifodd"),
    Some("ifvmode"),
    Some("ifhmode"),
    Some("ifmmode"),
    Some("ifinner"),
    Some("ifvoid"),
    Some("ifhbox"),
    Some("ifvbox"),
    Some("ifx"),
    Some("ifeof"),
    Some("iftrue"),
    Some("iffalse"),
    Some("ifcase"),
    Some("ifdefined"),
    Some("ifcsname"),
    // `\iffontchar`, which texrs does not dispatch.
    None,
    Some("ifincsname"),
    Some("ifprimitive"),
    Some("ifabsnum"),
    Some("ifabsdim"),
    Some("ifcondition"),
];

/// The conditional `name` names, as the `'static` string the condition stack
/// keeps (`CONDITIONALS`), or `if` for a name that is not one.
pub fn conditional_name(name: &str) -> &'static str {
    CONDITIONALS
        .iter()
        .find(|c| **c == name)
        .copied()
        .unwrap_or("if")
}

impl Engine {
    /// The characters `\scantokens` reads as a file: `text` as ยง295 shows a
    /// token list, cut into lines at the `\newlinechar` (etex.ch's
    /// `pseudo_start`), each ended as a file's line is -- the last too, for
    /// `\scantokens` (`file`), but not for `\scantextokens`.
    fn pseudo_file_text(&self, text: &[Token], file: bool) -> String {
        let shown = self.tokens_shown(text);
        let nl = u32::try_from(self.intpars.get(crate::intpar::NEW_LINE_CHAR))
            .ok()
            .and_then(char::from_u32);
        let mut src: String = match nl {
            Some(nl) => shown.split(nl).collect::<Vec<_>>().join("\n"),
            None => shown,
        };
        if file {
            src.push('\n');
        }
        src
    }
}

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

    /// Tokens as the mouth reads `src` under INITEX's codes plus braces.
    fn tokens(eng: &Engine, src: &str) -> Vec<Token> {
        let mut lx = Lexer::new(src);
        std::iter::from_fn(|| lx.next_token(&eng.cats)).collect()
    }

    #[test]
    fn runs_what_was_put_back_and_stops_at_the_depth_it_was_given() {
        let mut eng = Engine::new();
        eng.cats.set('{', Cat::BeginGroup);
        eng.cats.set('}', Cat::EndGroup);
        // The file goes on after the tokens: local control must not read it.
        let mut lx = Lexer::new("\\def\\after{no}");
        let stop = lx.pending.len();
        lx.push_back(&tokens(
            &eng,
            "\\let\\a\\relax \\def\\b{x}\\catcode`\\@=11 ",
        ));
        eng.local_control(&mut lx, stop).unwrap();
        assert_eq!(eng.meaning_text(&Token::cs("a")), "\\relax");
        assert_eq!(eng.meaning_text(&Token::cs("b")), "macro:->x");
        assert_eq!(eng.cats.get('@'), Cat::Letter);
        assert_eq!(eng.meaning_text(&Token::cs("after")), "undefined");
        assert_eq!(lx.next_token(&eng.cats), Some(Token::cs("def")));
    }

    #[test]
    fn a_count_assignment_is_refused_by_name_not_dropped() {
        let mut eng = Engine::new();
        let mut lx = Lexer::new("");
        lx.push_back(&tokens(&eng, "\\count1=5 "));
        let err = eng.local_control(&mut lx, 0).unwrap_err();
        assert!(err.0.contains("\\count inside tex.runtoks"), "{}", err.0);
        // Outside it the engine assigns as before.
        assert!(eng.run("\\count1=5 ").is_ok());
    }
}